repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/states/azurearm_network.py
security_rule_absent
python
def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret
.. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L1055-L1119
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
load_balancer_present
python
def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret
.. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L1122-L1478
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
load_balancer_absent
python
def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret
.. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L1481-L1541
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
public_ip_address_present
python
def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret
.. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L1544-L1727
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
public_ip_address_absent
python
def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret
.. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L1730-L1790
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
network_interface_present
python
def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret
.. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L1793-L2047
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
network_interface_absent
python
def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret
.. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L2050-L2110
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
route_table_present
python
def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret
.. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L2113-L2251
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
route_table_absent
python
def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret
.. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L2254-L2314
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
route_present
python
def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret
.. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L2317-L2447
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
saltstack/salt
salt/states/azurearm_network.py
route_absent
python
def route_absent(name, route_table, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in route: ret['result'] = True ret['comment'] = 'Route {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': route, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_delete'](name, route_table, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route {0} has been deleted.'.format(name) ret['changes'] = { 'old': route, 'new': {} } return ret ret['comment'] = 'Failed to delete route {0}!'.format(name) return ret
.. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param route_table: The name of the existing route table containing the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/azurearm_network.py#L2450-L2514
null
# -*- coding: utf-8 -*- ''' Azure (ARM) Network State Module .. versionadded:: 2019.2.0 :maintainer: <devops@decisionlab.io> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as a dictionary of keyword arguments to the ``connection_auth`` parameter in order to work properly. Since the authentication parameters are sensitive, it's recommended to pass them to the states via pillar. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` Example Pillar for Azure Resource Manager authentication: .. code-block:: yaml azurearm: user_pass_auth: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 username: fletch password: 123pass mysubscription: subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617 tenant: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF client_id: ABCDEFAB-1234-ABCD-1234-ABCDEFABCDEF secret: XXXXXXXXXXXXXXXXXXXXXXXX cloud_environment: AZURE_PUBLIC_CLOUD Example states using Azure Resource Manager authentication: .. code-block:: jinja {% set profile = salt['pillar.get']('azurearm:mysubscription') %} Ensure virtual network exists: azurearm_network.virtual_network_present: - name: my_vnet - resource_group: my_rg - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: how_awesome: very contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} Ensure virtual network is absent: azurearm_network.virtual_network_absent: - name: other_vnet - resource_group: my_rg - connection_auth: {{ profile }} ''' # Python libs from __future__ import absolute_import import logging # Salt libs try: from salt.ext.six.moves import range as six_range except ImportError: six_range = range __virtualname__ = 'azurearm_network' log = logging.getLogger(__name__) def __virtual__(): ''' Only make this state available if the azurearm_network module is available. ''' return __virtualname__ if 'azurearm_network.check_ip_address_availability' in __salt__ else False def virtual_network_present(name, address_prefixes, resource_group, dns_servers=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a virtual network exists. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param address_prefixes: A list of CIDR blocks which can be used by subnets within the virtual network. :param dns_servers: A list of DNS server addresses. :param tags: A dictionary of strings can be passed as tag metadata to the virtual network object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure virtual network exists: azurearm_network.virtual_network_present: - name: vnet1 - resource_group: group1 - address_prefixes: - '10.0.0.0/8' - '192.168.0.0/16' - dns_servers: - '8.8.8.8' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in vnet: tag_changes = __utils__['dictdiffer.deep_diff'](vnet.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes dns_changes = set(dns_servers or []).symmetric_difference( set(vnet.get('dhcp_options', {}).get('dns_servers', []))) if dns_changes: ret['changes']['dns_servers'] = { 'old': vnet.get('dhcp_options', {}).get('dns_servers', []), 'new': dns_servers, } addr_changes = set(address_prefixes or []).symmetric_difference( set(vnet.get('address_space', {}).get('address_prefixes', []))) if addr_changes: ret['changes']['address_space'] = { 'address_prefixes': { 'old': vnet.get('address_space', {}).get('address_prefixes', []), 'new': address_prefixes, } } if kwargs.get('enable_ddos_protection', False) != vnet.get('enable_ddos_protection'): ret['changes']['enable_ddos_protection'] = { 'old': vnet.get('enable_ddos_protection'), 'new': kwargs.get('enable_ddos_protection') } if kwargs.get('enable_vm_protection', False) != vnet.get('enable_vm_protection'): ret['changes']['enable_vm_protection'] = { 'old': vnet.get('enable_vm_protection'), 'new': kwargs.get('enable_vm_protection') } if not ret['changes']: ret['result'] = True ret['comment'] = 'Virtual network {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Virtual network {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'address_space': {'address_prefixes': address_prefixes}, 'dhcp_options': {'dns_servers': dns_servers}, 'enable_ddos_protection': kwargs.get('enable_ddos_protection', False), 'enable_vm_protection': kwargs.get('enable_vm_protection', False), 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Virtual network {0} would be created.'.format(name) ret['result'] = None return ret vnet_kwargs = kwargs.copy() vnet_kwargs.update(connection_auth) vnet = __salt__['azurearm_network.virtual_network_create_or_update']( name=name, resource_group=resource_group, address_prefixes=address_prefixes, dns_servers=dns_servers, tags=tags, **vnet_kwargs ) if 'error' not in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create virtual network {0}! ({1})'.format(name, vnet.get('error')) return ret def virtual_network_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the resource group. :param name: Name of the virtual network. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret vnet = __salt__['azurearm_network.virtual_network_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in vnet: ret['result'] = True ret['comment'] = 'Virtual network {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Virtual network {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': vnet, 'new': {}, } return ret deleted = __salt__['azurearm_network.virtual_network_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Virtual network {0} has been deleted.'.format(name) ret['changes'] = { 'old': vnet, 'new': {} } return ret ret['comment'] = 'Failed to delete virtual network {0}!'.format(name) return ret def subnet_present(name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a subnet exists. :param name: Name of the subnet. :param address_prefix: A CIDR block used by the subnet within the virtual network. :param virtual_network: Name of the existing virtual network to contain the subnet. :param resource_group: The resource group assigned to the virtual network. :param security_group: The name of the existing network security group to assign to the subnet. :param route_table: The name of the existing route table to assign to the subnet. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure subnet exists: azurearm_network.subnet_present: - name: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - address_prefix: '192.168.1.0/24' - security_group: nsg1 - route_table: rt1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure virtual network exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in snet: if address_prefix != snet.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': snet.get('address_prefix'), 'new': address_prefix } nsg_name = None if snet.get('network_security_group'): nsg_name = snet['network_security_group']['id'].split('/')[-1] if security_group and (security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': security_group } rttbl_name = None if snet.get('route_table'): rttbl_name = snet['route_table']['id'].split('/')[-1] if route_table and (route_table != rttbl_name): ret['changes']['route_table'] = { 'old': rttbl_name, 'new': route_table } if not ret['changes']: ret['result'] = True ret['comment'] = 'Subnet {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Subnet {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'network_security_group': security_group, 'route_table': route_table } } if __opts__['test']: ret['comment'] = 'Subnet {0} would be created.'.format(name) ret['result'] = None return ret snet_kwargs = kwargs.copy() snet_kwargs.update(connection_auth) snet = __salt__['azurearm_network.subnet_create_or_update']( name=name, virtual_network=virtual_network, resource_group=resource_group, address_prefix=address_prefix, network_security_group=security_group, route_table=route_table, **snet_kwargs ) if 'error' not in snet: ret['result'] = True ret['comment'] = 'Subnet {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create subnet {0}! ({1})'.format(name, snet.get('error')) return ret def subnet_absent(name, virtual_network, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a virtual network does not exist in the virtual network. :param name: Name of the subnet. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret snet = __salt__['azurearm_network.subnet_get']( name, virtual_network, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in snet: ret['result'] = True ret['comment'] = 'Subnet {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Subnet {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': snet, 'new': {}, } return ret deleted = __salt__['azurearm_network.subnet_delete'](name, virtual_network, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Subnet {0} has been deleted.'.format(name) ret['changes'] = { 'old': snet, 'new': {} } return ret ret['comment'] = 'Failed to delete subnet {0}!'.format(name) return ret def network_security_group_present(name, resource_group, tags=None, security_rules=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network security group exists. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param tags: A dictionary of strings can be passed as tag metadata to the network security group object. :param security_rules: An optional list of dictionaries representing valid SecurityRule objects. See the documentation for the security_rule_present state or security_rule_create_or_update execution module for more information on required and optional parameters for security rules. The rules are only managed if this parameter is present. When this parameter is absent, implemented rules will not be removed, and will merely become unmanaged. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network security group exists: azurearm_network.network_security_group_present: - name: nsg1 - resource_group: group1 - security_rules: - name: nsg1_rule1 priority: 100 protocol: tcp access: allow direction: outbound source_address_prefix: virtualnetwork destination_address_prefix: internet source_port_range: '*' destination_port_range: '*' - name: nsg1_rule2 priority: 101 protocol: tcp access: allow direction: inbound source_address_prefix: internet destination_address_prefix: virtualnetwork source_port_range: '*' destination_port_ranges: - '80' - '443' - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in nsg: tag_changes = __utils__['dictdiffer.deep_diff'](nsg.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes if security_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts'](nsg.get('security_rules', []), security_rules) if comp_ret.get('comment'): ret['comment'] = '"security_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['security_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network security group {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network security group {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'resource_group': resource_group, 'tags': tags, 'security_rules': security_rules, } } if __opts__['test']: ret['comment'] = 'Network security group {0} would be created.'.format(name) ret['result'] = None return ret nsg_kwargs = kwargs.copy() nsg_kwargs.update(connection_auth) nsg = __salt__['azurearm_network.network_security_group_create_or_update']( name=name, resource_group=resource_group, tags=tags, security_rules=security_rules, **nsg_kwargs ) if 'error' not in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network security group {0}! ({1})'.format(name, nsg.get('error')) return ret def network_security_group_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network security group does not exist in the resource group. :param name: Name of the network security group. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret nsg = __salt__['azurearm_network.network_security_group_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in nsg: ret['result'] = True ret['comment'] = 'Network security group {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network security group {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': nsg, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_security_group_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network security group {0} has been deleted.'.format(name) ret['changes'] = { 'old': nsg, 'new': {} } return ret ret['comment'] = 'Failed to delete network security group {0}!'.format(name) return ret def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group, destination_address_prefix=None, destination_port_range=None, source_address_prefix=None, source_port_range=None, description=None, destination_address_prefixes=None, destination_port_ranges=None, source_address_prefixes=None, source_port_ranges=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a security rule exists. :param name: Name of the security rule. :param access: 'allow' or 'deny' :param direction: 'inbound' or 'outbound' :param priority: Integer between 100 and 4096 used for ordering rule application. :param protocol: 'tcp', 'udp', or '*' :param security_group: The name of the existing network security group to contain the security rule. :param resource_group: The resource group assigned to the network security group. :param description: Optional description of the security rule. :param destination_address_prefix: The CIDR or destination IP range. Asterix '*' can also be used to match all destination IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param destination_port_range: The destination port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param source_address_prefix: The CIDR or source IP range. Asterix '*' can also be used to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is an ingress rule, specifies where network traffic originates from. :param source_port_range: The source port or range. Integer or range between 0 and 65535. Asterix '*' can also be used to match all ports. :param destination_address_prefixes: A list of destination_address_prefix values. This parameter overrides destination_address_prefix and will cause any value entered there to be ignored. :param destination_port_ranges: A list of destination_port_range values. This parameter overrides destination_port_range and will cause any value entered there to be ignored. :param source_address_prefixes: A list of source_address_prefix values. This parameter overrides source_address_prefix and will cause any value entered there to be ignored. :param source_port_ranges: A list of source_port_range values. This parameter overrides source_port_range and will cause any value entered there to be ignored. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure security rule exists: azurearm_network.security_rule_present: - name: nsg1_rule2 - security_group: nsg1 - resource_group: group1 - priority: 101 - protocol: tcp - access: allow - direction: inbound - source_address_prefix: internet - destination_address_prefix: virtualnetwork - source_port_range: '*' - destination_port_ranges: - '80' - '443' - connection_auth: {{ profile }} - require: - azurearm_network: Ensure network security group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret exclusive_params = [ ('source_port_ranges', 'source_port_range'), ('source_address_prefixes', 'source_address_prefix'), ('destination_port_ranges', 'destination_port_range'), ('destination_address_prefixes', 'destination_address_prefix'), ] for params in exclusive_params: # pylint: disable=eval-used if not eval(params[0]) and not eval(params[1]): ret['comment'] = 'Either the {0} or {1} parameter must be provided!'.format(params[0], params[1]) return ret # pylint: disable=eval-used if eval(params[0]): # pylint: disable=eval-used if not isinstance(eval(params[0]), list): ret['comment'] = 'The {0} parameter must be a list!'.format(params[0]) return ret # pylint: disable=exec-used exec('{0} = None'.format(params[1])) rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rule: # access changes if access.capitalize() != rule.get('access'): ret['changes']['access'] = { 'old': rule.get('access'), 'new': access } # description changes if description != rule.get('description'): ret['changes']['description'] = { 'old': rule.get('description'), 'new': description } # direction changes if direction.capitalize() != rule.get('direction'): ret['changes']['direction'] = { 'old': rule.get('direction'), 'new': direction } # priority changes if int(priority) != rule.get('priority'): ret['changes']['priority'] = { 'old': rule.get('priority'), 'new': priority } # protocol changes if protocol.lower() != rule.get('protocol', '').lower(): ret['changes']['protocol'] = { 'old': rule.get('protocol'), 'new': protocol } # destination_port_range changes if destination_port_range != rule.get('destination_port_range'): ret['changes']['destination_port_range'] = { 'old': rule.get('destination_port_range'), 'new': destination_port_range } # source_port_range changes if source_port_range != rule.get('source_port_range'): ret['changes']['source_port_range'] = { 'old': rule.get('source_port_range'), 'new': source_port_range } # destination_port_ranges changes if sorted(destination_port_ranges or []) != sorted(rule.get('destination_port_ranges', [])): ret['changes']['destination_port_ranges'] = { 'old': rule.get('destination_port_ranges'), 'new': destination_port_ranges } # source_port_ranges changes if sorted(source_port_ranges or []) != sorted(rule.get('source_port_ranges', [])): ret['changes']['source_port_ranges'] = { 'old': rule.get('source_port_ranges'), 'new': source_port_ranges } # destination_address_prefix changes if (destination_address_prefix or '').lower() != rule.get('destination_address_prefix', '').lower(): ret['changes']['destination_address_prefix'] = { 'old': rule.get('destination_address_prefix'), 'new': destination_address_prefix } # source_address_prefix changes if (source_address_prefix or '').lower() != rule.get('source_address_prefix', '').lower(): ret['changes']['source_address_prefix'] = { 'old': rule.get('source_address_prefix'), 'new': source_address_prefix } # destination_address_prefixes changes if sorted(destination_address_prefixes or []) != sorted(rule.get('destination_address_prefixes', [])): if len(destination_address_prefixes or []) != len(rule.get('destination_address_prefixes', [])): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } else: local_dst_addrs, remote_dst_addrs = (sorted(destination_address_prefixes), sorted(rule.get('destination_address_prefixes'))) for idx in six_range(0, len(local_dst_addrs)): if local_dst_addrs[idx].lower() != remote_dst_addrs[idx].lower(): ret['changes']['destination_address_prefixes'] = { 'old': rule.get('destination_address_prefixes'), 'new': destination_address_prefixes } break # source_address_prefixes changes if sorted(source_address_prefixes or []) != sorted(rule.get('source_address_prefixes', [])): if len(source_address_prefixes or []) != len(rule.get('source_address_prefixes', [])): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } else: local_src_addrs, remote_src_addrs = (sorted(source_address_prefixes), sorted(rule.get('source_address_prefixes'))) for idx in six_range(0, len(local_src_addrs)): if local_src_addrs[idx].lower() != remote_src_addrs[idx].lower(): ret['changes']['source_address_prefixes'] = { 'old': rule.get('source_address_prefixes'), 'new': source_address_prefixes } break if not ret['changes']: ret['result'] = True ret['comment'] = 'Security rule {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Security rule {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'access': access, 'description': description, 'direction': direction, 'priority': priority, 'protocol': protocol, 'destination_address_prefix': destination_address_prefix, 'destination_address_prefixes': destination_address_prefixes, 'destination_port_range': destination_port_range, 'destination_port_ranges': destination_port_ranges, 'source_address_prefix': source_address_prefix, 'source_address_prefixes': source_address_prefixes, 'source_port_range': source_port_range, 'source_port_ranges': source_port_ranges, } } if __opts__['test']: ret['comment'] = 'Security rule {0} would be created.'.format(name) ret['result'] = None return ret rule_kwargs = kwargs.copy() rule_kwargs.update(connection_auth) rule = __salt__['azurearm_network.security_rule_create_or_update']( name=name, access=access, description=description, direction=direction, priority=priority, protocol=protocol, security_group=security_group, resource_group=resource_group, destination_address_prefix=destination_address_prefix, destination_address_prefixes=destination_address_prefixes, destination_port_range=destination_port_range, destination_port_ranges=destination_port_ranges, source_address_prefix=source_address_prefix, source_address_prefixes=source_address_prefixes, source_port_range=source_port_range, source_port_ranges=source_port_ranges, **rule_kwargs ) if 'error' not in rule: ret['result'] = True ret['comment'] = 'Security rule {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create security rule {0}! ({1})'.format(name, rule.get('error')) return ret def security_rule_absent(name, security_group, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a security rule does not exist in the network security group. :param name: Name of the security rule. :param security_group: The network security group containing the security rule. :param resource_group: The resource group assigned to the network security group. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rule = __salt__['azurearm_network.security_rule_get']( name, security_group, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rule: ret['result'] = True ret['comment'] = 'Security rule {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Security rule {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rule, 'new': {}, } return ret deleted = __salt__['azurearm_network.security_rule_delete'](name, security_group, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Security rule {0} has been deleted.'.format(name) ret['changes'] = { 'old': rule, 'new': {} } return ret ret['comment'] = 'Failed to delete security rule {0}!'.format(name) return ret def load_balancer_present(name, resource_group, sku=None, frontend_ip_configurations=None, backend_address_pools=None, load_balancing_rules=None, probes=None, inbound_nat_rules=None, inbound_nat_pools=None, outbound_nat_rules=None, tags=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a load balancer exists. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param sku: The load balancer SKU, which can be 'Basic' or 'Standard'. :param tags: A dictionary of strings can be passed as tag metadata to the load balancer object. :param frontend_ip_configurations: An optional list of dictionaries representing valid FrontendIPConfiguration objects. A frontend IP configuration can be either private (using private IP address and subnet parameters) or public (using a reference to a public IP address object). Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``private_ip_address``: The private IP address of the IP configuration. Required if 'private_ip_allocation_method' is 'Static'. - ``private_ip_allocation_method``: The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. - ``subnet``: Name of an existing subnet inside of which the frontend IP will reside. - ``public_ip_address``: Name of an existing public IP address which will be assigned to the frontend IP object. :param backend_address_pools: An optional list of dictionaries representing valid BackendAddressPool objects. Only the 'name' parameter is valid for a BackendAddressPool dictionary. All other parameters are read-only references from other objects linking to the backend address pool. Inbound traffic is randomly load balanced across IPs in the backend IPs. :param probes: An optional list of dictionaries representing valid Probe objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``protocol``: The protocol of the endpoint. Possible values are 'Http' or 'Tcp'. If 'Tcp' is specified, a received ACK is required for the probe to be successful. If 'Http' is specified, a 200 OK response from the specified URI is required for the probe to be successful. - ``port``: The port for communicating the probe. Possible values range from 1 to 65535, inclusive. - ``interval_in_seconds``: The interval, in seconds, for how frequently to probe the endpoint for health status. Typically, the interval is slightly less than half the allocated timeout period (in seconds) which allows two full probes before taking the instance out of rotation. The default value is 15, the minimum value is 5. - ``number_of_probes``: The number of probes where if no response, will result in stopping further traffic from being delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or slower than the typical times used in Azure. - ``request_path``: The URI used for requesting health status from the VM. Path is required if a protocol is set to 'Http'. Otherwise, it is not allowed. There is no default value. :param load_balancing_rules: An optional list of dictionaries representing valid LoadBalancingRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``load_distribution``: The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and 'SourceIPProtocol'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables 'Any Port'. - ``backend_port``: The port used for internal connections on the endpoint. Acceptable values are between 0 and 65535. Note that value 0 enables 'Any Port'. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. - ``disable_outbound_snat``: Configures SNAT for the VMs in the backend pool to use the public IP address specified in the frontend of the load balancing rule. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the load balancing rule object. - ``backend_address_pool``: Name of the backend address pool object used by the load balancing rule object. Inbound traffic is randomly load balanced across IPs in the backend IPs. - ``probe``: Name of the probe object used by the load balancing rule object. :param inbound_nat_rules: An optional list of dictionaries representing valid InboundNatRule objects. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT rule object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port``: The port for the external endpoint. Port numbers for each rule must be unique within the Load Balancer. Acceptable values range from 1 to 65534. - ``backend_port``: The port used for the internal endpoint. Acceptable values range from 1 to 65535. - ``idle_timeout_in_minutes``: The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The default value is 4 minutes. This element is only used when the protocol is set to TCP. - ``enable_floating_ip``: Configures a virtual machine's endpoint for the floating IP capability required to configure a SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn Availability Groups in SQL server. This setting can't be changed after you create the endpoint. :param inbound_nat_pools: An optional list of dictionaries representing valid InboundNatPool objects. They define an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound NAT rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the inbound NAT pool object. - ``protocol``: Possible values include 'Udp', 'Tcp', or 'All'. - ``frontend_port_range_start``: The first port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65534. - ``frontend_port_range_end``: The last port number in the range of external ports that will be used to provide Inbound NAT to NICs associated with a load balancer. Acceptable values range between 1 and 65535. - ``backend_port``: The port used for internal connections to the endpoint. Acceptable values are between 1 and 65535. :param outbound_nat_rules: An optional list of dictionaries representing valid OutboundNatRule objects. Valid parameters are: - ``name``: The name of the resource that is unique within a resource group. - ``frontend_ip_configuration``: Name of the frontend IP configuration object used by the outbound NAT rule object. - ``backend_address_pool``: Name of the backend address pool object used by the outbound NAT rule object. Outbound traffic is randomly load balanced across IPs in the backend IPs. - ``allocated_outbound_ports``: The number of outbound ports to be used for NAT. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure load balancer exists: azurearm_network.load_balancer_present: - name: lb1 - resource_group: group1 - location: eastus - frontend_ip_configurations: - name: lb1_feip1 public_ip_address: pub_ip1 - backend_address_pools: - name: lb1_bepool1 - probes: - name: lb1_webprobe1 protocol: tcp port: 80 interval_in_seconds: 5 number_of_probes: 2 - load_balancing_rules: - name: lb1_webprobe1 protocol: tcp frontend_port: 80 backend_port: 80 idle_timeout_in_minutes: 4 frontend_ip_configuration: lb1_feip1 backend_address_pool: lb1_bepool1 probe: lb1_webprobe1 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists - azurearm_network: Ensure public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in load_bal: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](load_bal.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # frontend_ip_configurations changes if frontend_ip_configurations: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('frontend_ip_configurations', []), frontend_ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"frontend_ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['frontend_ip_configurations'] = comp_ret['changes'] # backend_address_pools changes if backend_address_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('backend_address_pools', []), backend_address_pools ) if comp_ret.get('comment'): ret['comment'] = '"backend_address_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['backend_address_pools'] = comp_ret['changes'] # probes changes if probes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](load_bal.get('probes', []), probes) if comp_ret.get('comment'): ret['comment'] = '"probes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['probes'] = comp_ret['changes'] # load_balancing_rules changes if load_balancing_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('load_balancing_rules', []), load_balancing_rules, ['frontend_ip_configuration', 'backend_address_pool', 'probe'] ) if comp_ret.get('comment'): ret['comment'] = '"load_balancing_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['load_balancing_rules'] = comp_ret['changes'] # inbound_nat_rules changes if inbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_rules', []), inbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_rules'] = comp_ret['changes'] # inbound_nat_pools changes if inbound_nat_pools: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('inbound_nat_pools', []), inbound_nat_pools, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"inbound_nat_pools" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['inbound_nat_pools'] = comp_ret['changes'] # outbound_nat_rules changes if outbound_nat_rules: comp_ret = __utils__['azurearm.compare_list_of_dicts']( load_bal.get('outbound_nat_rules', []), outbound_nat_rules, ['frontend_ip_configuration'] ) if comp_ret.get('comment'): ret['comment'] = '"outbound_nat_rules" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['outbound_nat_rules'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Load balancer {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Load balancer {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'sku': sku, 'tags': tags, 'frontend_ip_configurations': frontend_ip_configurations, 'backend_address_pools': backend_address_pools, 'load_balancing_rules': load_balancing_rules, 'probes': probes, 'inbound_nat_rules': inbound_nat_rules, 'inbound_nat_pools': inbound_nat_pools, 'outbound_nat_rules': outbound_nat_rules, } } if __opts__['test']: ret['comment'] = 'Load balancer {0} would be created.'.format(name) ret['result'] = None return ret lb_kwargs = kwargs.copy() lb_kwargs.update(connection_auth) load_bal = __salt__['azurearm_network.load_balancer_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, frontend_ip_configurations=frontend_ip_configurations, backend_address_pools=backend_address_pools, load_balancing_rules=load_balancing_rules, probes=probes, inbound_nat_rules=inbound_nat_rules, inbound_nat_pools=inbound_nat_pools, outbound_nat_rules=outbound_nat_rules, **lb_kwargs ) if 'error' not in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create load balancer {0}! ({1})'.format(name, load_bal.get('error')) return ret def load_balancer_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a load balancer does not exist in the resource group. :param name: Name of the load balancer. :param resource_group: The resource group assigned to the load balancer. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret load_bal = __salt__['azurearm_network.load_balancer_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in load_bal: ret['result'] = True ret['comment'] = 'Load balancer {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Load balancer {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': load_bal, 'new': {}, } return ret deleted = __salt__['azurearm_network.load_balancer_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Load balancer {0} has been deleted.'.format(name) ret['changes'] = { 'old': load_bal, 'new': {} } return ret ret['comment'] = 'Failed to delete load balancer {0}!'.format(name) return ret def public_ip_address_present(name, resource_group, tags=None, sku=None, public_ip_allocation_method=None, public_ip_address_version=None, dns_settings=None, idle_timeout_in_minutes=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a public IP address exists. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param dns_settings: An optional dictionary representing a valid PublicIPAddressDnsSettings object. Parameters include 'domain_name_label' and 'reverse_fqdn', which accept strings. The 'domain_name_label' parameter is concatenated with the regionalized DNS zone make up the fully qualified domain name associated with the public IP address. If a domain name label is specified, an A DNS record is created for the public IP in the Microsoft Azure DNS system. The 'reverse_fqdn' parameter is a user-visible, fully qualified domain name that resolves to this public IP address. If the reverse FQDN is specified, then a PTR DNS record is created pointing from the IP address in the in-addr.arpa domain to the reverse FQDN. :param sku: The public IP address SKU, which can be 'Basic' or 'Standard'. :param public_ip_allocation_method: The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. :param public_ip_address_version: The public IP address version. Possible values are: 'IPv4' and 'IPv6'. :param idle_timeout_in_minutes: An integer representing the idle timeout of the public IP address. :param tags: A dictionary of strings can be passed as tag metadata to the public IP address object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure public IP exists: azurearm_network.public_ip_address_present: - name: pub_ip1 - resource_group: group1 - dns_settings: domain_name_label: decisionlab-ext-test-label - sku: basic - public_ip_allocation_method: static - public_ip_address_version: ipv4 - idle_timeout_in_minutes: 4 - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret if sku: sku = {'name': sku.capitalize()} pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in pub_ip: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key] != pub_ip.get('dns_settings', {}).get(key): ret['changes']['dns_settings'] = { 'old': pub_ip.get('dns_settings'), 'new': dns_settings } break # sku changes if sku: sku_changes = __utils__['dictdiffer.deep_diff'](pub_ip.get('sku', {}), sku) if sku_changes: ret['changes']['sku'] = sku_changes # public_ip_allocation_method changes if public_ip_allocation_method: if public_ip_allocation_method.capitalize() != pub_ip.get('public_ip_allocation_method'): ret['changes']['public_ip_allocation_method'] = { 'old': pub_ip.get('public_ip_allocation_method'), 'new': public_ip_allocation_method } # public_ip_address_version changes if public_ip_address_version: if public_ip_address_version.lower() != pub_ip.get('public_ip_address_version', '').lower(): ret['changes']['public_ip_address_version'] = { 'old': pub_ip.get('public_ip_address_version'), 'new': public_ip_address_version } # idle_timeout_in_minutes changes if idle_timeout_in_minutes and (int(idle_timeout_in_minutes) != pub_ip.get('idle_timeout_in_minutes')): ret['changes']['idle_timeout_in_minutes'] = { 'old': pub_ip.get('idle_timeout_in_minutes'), 'new': idle_timeout_in_minutes } if not ret['changes']: ret['result'] = True ret['comment'] = 'Public IP address {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Public IP address {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'dns_settings': dns_settings, 'sku': sku, 'public_ip_allocation_method': public_ip_allocation_method, 'public_ip_address_version': public_ip_address_version, 'idle_timeout_in_minutes': idle_timeout_in_minutes, } } if __opts__['test']: ret['comment'] = 'Public IP address {0} would be created.'.format(name) ret['result'] = None return ret pub_ip_kwargs = kwargs.copy() pub_ip_kwargs.update(connection_auth) pub_ip = __salt__['azurearm_network.public_ip_address_create_or_update']( name=name, resource_group=resource_group, sku=sku, tags=tags, dns_settings=dns_settings, public_ip_allocation_method=public_ip_allocation_method, public_ip_address_version=public_ip_address_version, idle_timeout_in_minutes=idle_timeout_in_minutes, **pub_ip_kwargs ) if 'error' not in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create public IP address {0}! ({1})'.format(name, pub_ip.get('error')) return ret def public_ip_address_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a public IP address does not exist in the resource group. :param name: Name of the public IP address. :param resource_group: The resource group assigned to the public IP address. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret pub_ip = __salt__['azurearm_network.public_ip_address_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in pub_ip: ret['result'] = True ret['comment'] = 'Public IP address {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Public IP address {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': pub_ip, 'new': {}, } return ret deleted = __salt__['azurearm_network.public_ip_address_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Public IP address {0} has been deleted.'.format(name) ret['changes'] = { 'old': pub_ip, 'new': {} } return ret ret['comment'] = 'Failed to delete public IP address {0}!'.format(name) return ret def network_interface_present(name, ip_configurations, subnet, virtual_network, resource_group, tags=None, virtual_machine=None, network_security_group=None, dns_settings=None, mac_address=None, primary=None, enable_accelerated_networking=None, enable_ip_forwarding=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a network interface exists. :param name: Name of the network interface. :param ip_configurations: A list of dictionaries representing valid NetworkInterfaceIPConfiguration objects. The 'name' key is required at minimum. At least one IP Configuration must be present. :param subnet: Name of the existing subnet assigned to the network interface. :param virtual_network: Name of the existing virtual network containing the subnet. :param resource_group: The resource group assigned to the virtual network. :param tags: A dictionary of strings can be passed as tag metadata to the network interface object. :param network_security_group: The name of the existing network security group to assign to the network interface. :param virtual_machine: The name of the existing virtual machine to assign to the network interface. :param dns_settings: An optional dictionary representing a valid NetworkInterfaceDnsSettings object. Valid parameters are: - ``dns_servers``: List of DNS server IP addresses. Use 'AzureProvidedDNS' to switch to Azure provided DNS resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only value in dns_servers collection. - ``internal_dns_name_label``: Relative DNS name for this NIC used for internal communications between VMs in the same virtual network. - ``internal_fqdn``: Fully qualified DNS name supporting internal communications between VMs in the same virtual network. - ``internal_domain_name_suffix``: Even if internal_dns_name_label is not specified, a DNS entry is created for the primary NIC of the VM. This DNS name can be constructed by concatenating the VM name with the value of internal_domain_name_suffix. :param mac_address: Optional string containing the MAC address of the network interface. :param primary: Optional boolean allowing the interface to be set as the primary network interface on a virtual machine with multiple interfaces attached. :param enable_accelerated_networking: Optional boolean indicating whether accelerated networking should be enabled for the interface. :param enable_ip_forwarding: Optional boolean indicating whether IP forwarding should be enabled for the interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure network interface exists: azurearm_network.network_interface_present: - name: iface1 - subnet: vnet1_sn1 - virtual_network: vnet1 - resource_group: group1 - ip_configurations: - name: iface1_ipc1 public_ip_address: pub_ip2 - dns_settings: internal_dns_name_label: decisionlab-int-test-label - primary: True - enable_accelerated_networking: True - enable_ip_forwarding: False - network_security_group: nsg1 - connection_auth: {{ profile }} - require: - azurearm_network: Ensure subnet exists - azurearm_network: Ensure network security group exists - azurearm_network: Ensure another public IP exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in iface: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](iface.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # mac_address changes if mac_address and (mac_address != iface.get('mac_address')): ret['changes']['mac_address'] = { 'old': iface.get('mac_address'), 'new': mac_address } # primary changes if primary is not None: if primary != iface.get('primary', True): ret['changes']['primary'] = { 'old': iface.get('primary'), 'new': primary } # enable_accelerated_networking changes if enable_accelerated_networking is not None: if enable_accelerated_networking != iface.get('enable_accelerated_networking'): ret['changes']['enable_accelerated_networking'] = { 'old': iface.get('enable_accelerated_networking'), 'new': enable_accelerated_networking } # enable_ip_forwarding changes if enable_ip_forwarding is not None: if enable_ip_forwarding != iface.get('enable_ip_forwarding'): ret['changes']['enable_ip_forwarding'] = { 'old': iface.get('enable_ip_forwarding'), 'new': enable_ip_forwarding } # network_security_group changes nsg_name = None if iface.get('network_security_group'): nsg_name = iface['network_security_group']['id'].split('/')[-1] if network_security_group and (network_security_group != nsg_name): ret['changes']['network_security_group'] = { 'old': nsg_name, 'new': network_security_group } # virtual_machine changes vm_name = None if iface.get('virtual_machine'): vm_name = iface['virtual_machine']['id'].split('/')[-1] if virtual_machine and (virtual_machine != vm_name): ret['changes']['virtual_machine'] = { 'old': vm_name, 'new': virtual_machine } # dns_settings changes if dns_settings: if not isinstance(dns_settings, dict): ret['comment'] = 'DNS settings must be provided as a dictionary!' return ret for key in dns_settings: if dns_settings[key].lower() != iface.get('dns_settings', {}).get(key, '').lower(): ret['changes']['dns_settings'] = { 'old': iface.get('dns_settings'), 'new': dns_settings } break # ip_configurations changes comp_ret = __utils__['azurearm.compare_list_of_dicts']( iface.get('ip_configurations', []), ip_configurations, ['public_ip_address', 'subnet'] ) if comp_ret.get('comment'): ret['comment'] = '"ip_configurations" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['ip_configurations'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Network interface {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Network interface {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'ip_configurations': ip_configurations, 'dns_settings': dns_settings, 'network_security_group': network_security_group, 'virtual_machine': virtual_machine, 'enable_accelerated_networking': enable_accelerated_networking, 'enable_ip_forwarding': enable_ip_forwarding, 'mac_address': mac_address, 'primary': primary, 'tags': tags, } } if __opts__['test']: ret['comment'] = 'Network interface {0} would be created.'.format(name) ret['result'] = None return ret iface_kwargs = kwargs.copy() iface_kwargs.update(connection_auth) iface = __salt__['azurearm_network.network_interface_create_or_update']( name=name, subnet=subnet, virtual_network=virtual_network, resource_group=resource_group, ip_configurations=ip_configurations, dns_settings=dns_settings, enable_accelerated_networking=enable_accelerated_networking, enable_ip_forwarding=enable_ip_forwarding, mac_address=mac_address, primary=primary, network_security_group=network_security_group, virtual_machine=virtual_machine, tags=tags, **iface_kwargs ) if 'error' not in iface: ret['result'] = True ret['comment'] = 'Network interface {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create network interface {0}! ({1})'.format(name, iface.get('error')) return ret def network_interface_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a network interface does not exist in the resource group. :param name: Name of the network interface. :param resource_group: The resource group assigned to the network interface. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret iface = __salt__['azurearm_network.network_interface_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in iface: ret['result'] = True ret['comment'] = 'Network interface {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Network interface {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': iface, 'new': {}, } return ret deleted = __salt__['azurearm_network.network_interface_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Network interface {0} has been deleted.'.format(name) ret['changes'] = { 'old': iface, 'new': {} } return ret ret['comment'] = 'Failed to delete network interface {0}!)'.format(name) return ret def route_table_present(name, resource_group, tags=None, routes=None, disable_bgp_route_propagation=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route table exists. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param routes: An optional list of dictionaries representing valid Route objects contained within a route table. See the documentation for the route_present state or route_create_or_update execution module for more information on required and optional parameters for routes. The routes are only managed if this parameter is present. When this parameter is absent, implemented routes will not be removed, and will merely become unmanaged. :param disable_bgp_route_propagation: An optional boolean parameter setting whether to disable the routes learned by BGP on the route table. :param tags: A dictionary of strings can be passed as tag metadata to the route table object. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route table exists: azurearm_network.route_table_present: - name: rt1 - resource_group: group1 - routes: - name: rt1_route1 address_prefix: '0.0.0.0/0' next_hop_type: internet - name: rt1_route2 address_prefix: '192.168.0.0/16' next_hop_type: vnetlocal - tags: contact_name: Elmer Fudd Gantry - connection_auth: {{ profile }} - require: - azurearm_resource: Ensure resource group exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in rt_tbl: # tag changes tag_changes = __utils__['dictdiffer.deep_diff'](rt_tbl.get('tags', {}), tags or {}) if tag_changes: ret['changes']['tags'] = tag_changes # disable_bgp_route_propagation changes # pylint: disable=line-too-long if disable_bgp_route_propagation and (disable_bgp_route_propagation != rt_tbl.get('disable_bgp_route_propagation')): ret['changes']['disable_bgp_route_propagation'] = { 'old': rt_tbl.get('disable_bgp_route_propagation'), 'new': disable_bgp_route_propagation } # routes changes if routes: comp_ret = __utils__['azurearm.compare_list_of_dicts'](rt_tbl.get('routes', []), routes) if comp_ret.get('comment'): ret['comment'] = '"routes" {0}'.format(comp_ret['comment']) return ret if comp_ret.get('changes'): ret['changes']['routes'] = comp_ret['changes'] if not ret['changes']: ret['result'] = True ret['comment'] = 'Route table {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route table {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'tags': tags, 'routes': routes, 'disable_bgp_route_propagation': disable_bgp_route_propagation, } } if __opts__['test']: ret['comment'] = 'Route table {0} would be created.'.format(name) ret['result'] = None return ret rt_tbl_kwargs = kwargs.copy() rt_tbl_kwargs.update(connection_auth) rt_tbl = __salt__['azurearm_network.route_table_create_or_update']( name=name, resource_group=resource_group, disable_bgp_route_propagation=disable_bgp_route_propagation, routes=routes, tags=tags, **rt_tbl_kwargs ) if 'error' not in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route table {0}! ({1})'.format(name, rt_tbl.get('error')) return ret def route_table_absent(name, resource_group, connection_auth=None): ''' .. versionadded:: 2019.2.0 Ensure a route table does not exist in the resource group. :param name: Name of the route table. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret rt_tbl = __salt__['azurearm_network.route_table_get']( name, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' in rt_tbl: ret['result'] = True ret['comment'] = 'Route table {0} was not found.'.format(name) return ret elif __opts__['test']: ret['comment'] = 'Route table {0} would be deleted.'.format(name) ret['result'] = None ret['changes'] = { 'old': rt_tbl, 'new': {}, } return ret deleted = __salt__['azurearm_network.route_table_delete'](name, resource_group, **connection_auth) if deleted: ret['result'] = True ret['comment'] = 'Route table {0} has been deleted.'.format(name) ret['changes'] = { 'old': rt_tbl, 'new': {} } return ret ret['comment'] = 'Failed to delete route table {0}!'.format(name) return ret def route_present(name, address_prefix, next_hop_type, route_table, resource_group, next_hop_ip_address=None, connection_auth=None, **kwargs): ''' .. versionadded:: 2019.2.0 Ensure a route exists within a route table. :param name: Name of the route. :param address_prefix: The destination CIDR to which the route applies. :param next_hop_type: The type of Azure hop the packet should be sent to. Possible values are: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. :param next_hop_ip_address: The IP address packets should be forwarded to. Next hop values are only allowed in routes where the next hop type is 'VirtualAppliance'. :param route_table: The name of the existing route table which will contain the route. :param resource_group: The resource group assigned to the route table. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure route exists: azurearm_network.route_present: - name: rt1_route2 - route_table: rt1 - resource_group: group1 - address_prefix: '192.168.0.0/16' - next_hop_type: vnetlocal - connection_auth: {{ profile }} - require: - azurearm_network: Ensure route table exists ''' ret = { 'name': name, 'result': False, 'comment': '', 'changes': {} } if not isinstance(connection_auth, dict): ret['comment'] = 'Connection information must be specified via connection_auth dictionary!' return ret route = __salt__['azurearm_network.route_get']( name, route_table, resource_group, azurearm_log_level='info', **connection_auth ) if 'error' not in route: if address_prefix != route.get('address_prefix'): ret['changes']['address_prefix'] = { 'old': route.get('address_prefix'), 'new': address_prefix } if next_hop_type.lower() != route.get('next_hop_type', '').lower(): ret['changes']['next_hop_type'] = { 'old': route.get('next_hop_type'), 'new': next_hop_type } if next_hop_type.lower() == 'virtualappliance' and next_hop_ip_address != route.get('next_hop_ip_address'): ret['changes']['next_hop_ip_address'] = { 'old': route.get('next_hop_ip_address'), 'new': next_hop_ip_address } if not ret['changes']: ret['result'] = True ret['comment'] = 'Route {0} is already present.'.format(name) return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Route {0} would be updated.'.format(name) return ret else: ret['changes'] = { 'old': {}, 'new': { 'name': name, 'address_prefix': address_prefix, 'next_hop_type': next_hop_type, 'next_hop_ip_address': next_hop_ip_address } } if __opts__['test']: ret['comment'] = 'Route {0} would be created.'.format(name) ret['result'] = None return ret route_kwargs = kwargs.copy() route_kwargs.update(connection_auth) route = __salt__['azurearm_network.route_create_or_update']( name=name, route_table=route_table, resource_group=resource_group, address_prefix=address_prefix, next_hop_type=next_hop_type, next_hop_ip_address=next_hop_ip_address, **route_kwargs ) if 'error' not in route: ret['result'] = True ret['comment'] = 'Route {0} has been created.'.format(name) return ret ret['comment'] = 'Failed to create route {0}! ({1})'.format(name, route.get('error')) return ret
saltstack/salt
salt/utils/jid.py
gen_jid
python
def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid())
Generate a jid
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L17-L39
[ "def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n" ]
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
saltstack/salt
salt/utils/jid.py
is_jid
python
def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False
Returns True if the passed in value is a job id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L42-L54
null
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid()) def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
saltstack/salt
salt/utils/jid.py
jid_to_time
python
def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret
Convert a salt job id into the time when the job was invoked
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L57-L79
null
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid()) def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
saltstack/salt
salt/utils/jid.py
format_job_instance
python
def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret
Format the job instance correctly
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L82-L99
null
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid()) def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
saltstack/salt
salt/utils/jid.py
format_jid_instance
python
def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret
Format the jid correctly
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L102-L108
[ "def jid_to_time(jid):\n '''\n Convert a salt job id into the time when the job was invoked\n '''\n jid = six.text_type(jid)\n if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):\n return ''\n year = jid[:4]\n month = jid[4:6]\n day = jid[6:8]\n hour = jid[8:10]\n minute = jid[10:12]\n second = jid[12:14]\n micro = jid[14:20]\n\n ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year,\n months[int(month)],\n day,\n hour,\n minute,\n second,\n micro)\n return ret\n", "def format_job_instance(job):\n '''\n Format the job instance correctly\n '''\n ret = {'Function': job.get('fun', 'unknown-function'),\n 'Arguments': list(job.get('arg', [])),\n # unlikely but safeguard from invalid returns\n 'Target': job.get('tgt', 'unknown-target'),\n 'Target-type': job.get('tgt_type', 'list'),\n 'User': job.get('user', 'root')}\n\n if 'metadata' in job:\n ret['Metadata'] = job.get('metadata', {})\n else:\n if 'kwargs' in job:\n if 'metadata' in job['kwargs']:\n ret['Metadata'] = job['kwargs'].get('metadata', {})\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid()) def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
saltstack/salt
salt/utils/jid.py
format_jid_instance_ext
python
def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret
Format the jid correctly with jid included
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L111-L119
[ "def jid_to_time(jid):\n '''\n Convert a salt job id into the time when the job was invoked\n '''\n jid = six.text_type(jid)\n if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):\n return ''\n year = jid[:4]\n month = jid[4:6]\n day = jid[6:8]\n hour = jid[8:10]\n minute = jid[10:12]\n second = jid[12:14]\n micro = jid[14:20]\n\n ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year,\n months[int(month)],\n day,\n hour,\n minute,\n second,\n micro)\n return ret\n", "def format_job_instance(job):\n '''\n Format the job instance correctly\n '''\n ret = {'Function': job.get('fun', 'unknown-function'),\n 'Arguments': list(job.get('arg', [])),\n # unlikely but safeguard from invalid returns\n 'Target': job.get('tgt', 'unknown-target'),\n 'Target-type': job.get('tgt_type', 'list'),\n 'User': job.get('user', 'root')}\n\n if 'metadata' in job:\n ret['Metadata'] = job.get('metadata', {})\n else:\n if 'kwargs' in job:\n if 'metadata' in job['kwargs']:\n ret['Metadata'] = job['kwargs'].get('metadata', {})\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid()) def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
saltstack/salt
salt/utils/jid.py
jid_dir
python
def jid_dir(jid, job_dir=None, hash_type='sha256'): ''' Return the jid_dir for the given job id ''' if not isinstance(jid, six.string_types): jid = six.text_type(jid) jhash = getattr(hashlib, hash_type)( salt.utils.stringutils.to_bytes(jid)).hexdigest() parts = [] if job_dir is not None: parts.append(job_dir) parts.extend([jhash[:2], jhash[2:]]) return os.path.join(*parts)
Return the jid_dir for the given job id
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/jid.py#L122-L135
null
# -*- coding: utf-8 -*- ''' Functions for creating and working with job IDs ''' from __future__ import absolute_import, print_function, unicode_literals from calendar import month_abbr as months import datetime import hashlib import os import salt.utils.stringutils from salt.ext import six LAST_JID_DATETIME = None def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global LAST_JID_DATETIME # pylint: disable=global-statement if opts.get('utc_jid', False): jid_dt = datetime.datetime.utcnow() else: jid_dt = datetime.datetime.now() if not opts.get('unique_jid', False): return '{0:%Y%m%d%H%M%S%f}'.format(jid_dt) if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt return '{0:%Y%m%d%H%M%S%f}_{1}'.format(jid_dt, os.getpid()) def is_jid(jid): ''' Returns True if the passed in value is a job id ''' if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return False try: int(jid[:20]) return True except ValueError: return False def jid_to_time(jid): ''' Convert a salt job id into the time when the job was invoked ''' jid = six.text_type(jid) if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'): return '' year = jid[:4] month = jid[4:6] day = jid[6:8] hour = jid[8:10] minute = jid[10:12] second = jid[12:14] micro = jid[14:20] ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year, months[int(month)], day, hour, minute, second, micro) return ret def format_job_instance(job): ''' Format the job instance correctly ''' ret = {'Function': job.get('fun', 'unknown-function'), 'Arguments': list(job.get('arg', [])), # unlikely but safeguard from invalid returns 'Target': job.get('tgt', 'unknown-target'), 'Target-type': job.get('tgt_type', 'list'), 'User': job.get('user', 'root')} if 'metadata' in job: ret['Metadata'] = job.get('metadata', {}) else: if 'kwargs' in job: if 'metadata' in job['kwargs']: ret['Metadata'] = job['kwargs'].get('metadata', {}) return ret def format_jid_instance(jid, job): ''' Format the jid correctly ''' ret = format_job_instance(job) ret.update({'StartTime': jid_to_time(jid)}) return ret def format_jid_instance_ext(jid, job): ''' Format the jid correctly with jid included ''' ret = format_job_instance(job) ret.update({ 'JID': jid, 'StartTime': jid_to_time(jid)}) return ret
saltstack/salt
salt/modules/system.py
init
python
def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret
Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L64-L76
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
reboot
python
def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret
Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L94-L109
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
shutdown
python
def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret
Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L112-L127
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
_date_bin_set_datetime
python
def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True
set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L130-L169
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
has_settable_hwclock
python
def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False
Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L172-L187
[ "def which_bin(exes):\n '''\n Scan over some possible executables and return the first one that is found\n '''\n if not isinstance(exes, Iterable):\n return None\n for exe in exes:\n path = which(exe)\n if not path:\n continue\n return path\n return None\n" ]
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
_swclock_to_hwclock
python
def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True
Set hardware clock to value of software clock.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L190-L198
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
_offset_to_min
python
def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset
Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L221-L235
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
_get_offset_time
python
def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time
Will return the current time adjusted using the input timezone offset. :rtype datetime:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L238-L251
[ "def _offset_to_min(utc_offset):\n '''\n Helper function that converts the utc offset string into number of minutes\n offset. Input is in form \"[+-]?HHMM\". Example valid inputs are \"+0500\"\n \"-0300\" and \"0800\". These would return -300, 180, 480 respectively.\n '''\n match = re.match(r\"^([+-])?(\\d\\d)(\\d\\d)$\", utc_offset)\n if not match:\n raise SaltInvocationError(\"Invalid UTC offset\")\n\n sign = -1 if match.group(1) == '-' else 1\n hours_offset = int(match.group(2))\n minutes_offset = int(match.group(3))\n total_offset = sign * (hours_offset * 60 + minutes_offset)\n return total_offset\n" ]
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
set_system_time
python
def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset)
Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L276-L312
[ "def _try_parse_datetime(time_str, fmts):\n '''\n Attempts to parse the input time_str as a date.\n\n :param str time_str: A string representing the time\n :param list fmts: A list of date format strings.\n\n :return: Returns a datetime object if parsed properly. Otherwise None\n :rtype datetime:\n '''\n result = None\n for fmt in fmts:\n try:\n result = datetime.strptime(time_str, fmt)\n break\n except ValueError:\n pass\n return result\n" ]
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
set_system_date_time
python
def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True
Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L337-L405
[ "def _date_bin_set_datetime(new_date):\n '''\n set the system date/time using the date command\n\n Note using a strictly posix-compliant date binary we can only set the date\n up to the minute.\n '''\n cmd = ['date']\n\n # if there is a timezone in the datetime object use that offset\n # This will modify the new_date to be the equivalent time in UTC\n if new_date.utcoffset() is not None:\n new_date = new_date - new_date.utcoffset()\n new_date = new_date.replace(tzinfo=_FixedOffset(0))\n cmd.append('-u')\n\n # the date can be set in the following format:\n # Note that setting the time with a resolution of seconds\n # is not a posix feature, so we will attempt it and if it\n # fails we will try again only using posix features\n\n # date MMDDhhmm[[CC]YY[.ss]]\n non_posix = (\"{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}\"\n .format(*new_date.timetuple()))\n non_posix_cmd = cmd + [non_posix]\n\n ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False)\n if ret_non_posix['retcode'] != 0:\n # We will now try the command again following posix\n # date MMDDhhmm[[CC]YY]\n posix = \" {1:02}{2:02}{3:02}{4:02}{0:04}\".format(*new_date.timetuple())\n posix_cmd = cmd + [posix]\n\n ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False)\n if ret_posix['retcode'] != 0:\n # if both fail it's likely an invalid date string\n # so we will give back the error from the first attempt\n msg = 'date failed: {0}'.format(ret_non_posix['stderr'])\n raise CommandExecutionError(msg)\n return True\n", "def has_settable_hwclock():\n '''\n Returns True if the system has a hardware clock capable of being\n set from software.\n\n CLI Example:\n\n salt '*' system.has_settable_hwclock\n '''\n if salt.utils.path.which_bin(['hwclock']) is not None:\n res = __salt__['cmd.run_all'](\n ['hwclock', '--test', '--systohc'], python_shell=False,\n output_loglevel='quiet', ignore_retcode=True\n )\n return res['retcode'] == 0\n return False\n", "def _swclock_to_hwclock():\n '''\n Set hardware clock to value of software clock.\n '''\n res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False)\n if res['retcode'] != 0:\n msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr'])\n raise CommandExecutionError(msg)\n return True\n", "def _get_offset_time(utc_offset):\n '''\n Will return the current time adjusted using the input timezone offset.\n\n :rtype datetime:\n '''\n if utc_offset is not None:\n minutes = _offset_to_min(utc_offset)\n offset = timedelta(minutes=minutes)\n offset_time = datetime.utcnow() + offset\n offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes))\n else:\n offset_time = datetime.now()\n return offset_time\n" ]
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
get_computer_desc
python
def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t')
Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L496-L535
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _strip_quotes(str_q):\n '''\n Helper function to strip off the ' or \" off of a string\n '''\n if str_q[0] == str_q[-1] and str_q.startswith((\"'\", '\"')):\n return str_q[1:-1]\n return str_q\n" ]
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
set_computer_desc
python
def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False
Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L538-L586
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n" ]
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0 @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/modules/system.py
set_reboot_required_witnessed
python
def set_reboot_required_witnessed(): ''' This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed ''' errcode = -1 dir_path = os.path.dirname(NILRT_REBOOT_WITNESS_PATH) if not os.path.exists(dir_path): try: os.makedirs(dir_path) except OSError as ex: raise SaltInvocationError('Error creating {0} (-{1}): {2}' .format(dir_path, ex.errno, ex.strerror)) rdict = __salt__['cmd.run_all']('touch {0}'.format(NILRT_REBOOT_WITNESS_PATH)) errcode = rdict['retcode'] return errcode == 0
This function is used to remember that an event indicating that a reboot is required was witnessed. This function writes to a temporary filesystem so the event gets cleared upon reboot. Returns: bool: ``True`` if successful, otherwise ``False`` .. code-block:: bash salt '*' system.set_reboot_required_witnessed
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/system.py#L626-L651
null
# -*- coding: utf-8 -*- ''' Support for reboot, shutdown, etc on POSIX-like systems. .. note:: If you have configured a wrapper such as ``molly-guard`` to intercept *interactive* shutdown commands, be aware that calling ``system.halt``, ``system.poweroff``, ``system.reboot``, and ``system.shutdown`` with ``salt-call`` will hang indefinitely while the wrapper script waits for user input. Calling them with ``salt`` will work as expected. ''' from __future__ import absolute_import, unicode_literals, print_function # Import Python libs from datetime import datetime, timedelta, tzinfo import re import os.path # Import Salt libs import salt.utils.files import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.utils.decorators import depends __virtualname__ = 'system' def __virtual__(): ''' Only supported on POSIX-like systems Windows, Solaris, and Mac have their own modules ''' if salt.utils.platform.is_windows(): return (False, 'This module is not available on Windows') if salt.utils.platform.is_darwin(): return (False, 'This module is not available on Mac OS') if salt.utils.platform.is_sunos(): return (False, 'This module is not available on SunOS') return __virtualname__ def halt(): ''' Halt a running system CLI Example: .. code-block:: bash salt '*' system.halt ''' cmd = ['halt'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def init(runlevel): ''' Change the system runlevel on sysV compatible systems CLI Example: .. code-block:: bash salt '*' system.init 3 ''' cmd = ['init', '{0}'.format(runlevel)] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def poweroff(): ''' Poweroff a running system CLI Example: .. code-block:: bash salt '*' system.poweroff ''' cmd = ['poweroff'] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def reboot(at_time=None): ''' Reboot the system at_time The wait time in minutes before the system will be rebooted. CLI Example: .. code-block:: bash salt '*' system.reboot ''' cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def shutdown(at_time=None): ''' Shutdown a running system at_time The wait time in minutes before the system will be shutdown. CLI Example: .. code-block:: bash salt '*' system.shutdown 5 ''' cmd = ['shutdown', '-h', ('{0}'.format(at_time) if at_time else 'now')] ret = __salt__['cmd.run'](cmd, python_shell=False) return ret def _date_bin_set_datetime(new_date): ''' set the system date/time using the date command Note using a strictly posix-compliant date binary we can only set the date up to the minute. ''' cmd = ['date'] # if there is a timezone in the datetime object use that offset # This will modify the new_date to be the equivalent time in UTC if new_date.utcoffset() is not None: new_date = new_date - new_date.utcoffset() new_date = new_date.replace(tzinfo=_FixedOffset(0)) cmd.append('-u') # the date can be set in the following format: # Note that setting the time with a resolution of seconds # is not a posix feature, so we will attempt it and if it # fails we will try again only using posix features # date MMDDhhmm[[CC]YY[.ss]] non_posix = ("{1:02}{2:02}{3:02}{4:02}{0:04}.{5:02}" .format(*new_date.timetuple())) non_posix_cmd = cmd + [non_posix] ret_non_posix = __salt__['cmd.run_all'](non_posix_cmd, python_shell=False) if ret_non_posix['retcode'] != 0: # We will now try the command again following posix # date MMDDhhmm[[CC]YY] posix = " {1:02}{2:02}{3:02}{4:02}{0:04}".format(*new_date.timetuple()) posix_cmd = cmd + [posix] ret_posix = __salt__['cmd.run_all'](posix_cmd, python_shell=False) if ret_posix['retcode'] != 0: # if both fail it's likely an invalid date string # so we will give back the error from the first attempt msg = 'date failed: {0}'.format(ret_non_posix['stderr']) raise CommandExecutionError(msg) return True def has_settable_hwclock(): ''' Returns True if the system has a hardware clock capable of being set from software. CLI Example: salt '*' system.has_settable_hwclock ''' if salt.utils.path.which_bin(['hwclock']) is not None: res = __salt__['cmd.run_all']( ['hwclock', '--test', '--systohc'], python_shell=False, output_loglevel='quiet', ignore_retcode=True ) return res['retcode'] == 0 return False def _swclock_to_hwclock(): ''' Set hardware clock to value of software clock. ''' res = __salt__['cmd.run_all'](['hwclock', '--systohc'], python_shell=False) if res['retcode'] != 0: msg = 'hwclock failed to set hardware clock from software clock: {0}'.format(res['stderr']) raise CommandExecutionError(msg) return True def _try_parse_datetime(time_str, fmts): ''' Attempts to parse the input time_str as a date. :param str time_str: A string representing the time :param list fmts: A list of date format strings. :return: Returns a datetime object if parsed properly. Otherwise None :rtype datetime: ''' result = None for fmt in fmts: try: result = datetime.strptime(time_str, fmt) break except ValueError: pass return result def _offset_to_min(utc_offset): ''' Helper function that converts the utc offset string into number of minutes offset. Input is in form "[+-]?HHMM". Example valid inputs are "+0500" "-0300" and "0800". These would return -300, 180, 480 respectively. ''' match = re.match(r"^([+-])?(\d\d)(\d\d)$", utc_offset) if not match: raise SaltInvocationError("Invalid UTC offset") sign = -1 if match.group(1) == '-' else 1 hours_offset = int(match.group(2)) minutes_offset = int(match.group(3)) total_offset = sign * (hours_offset * 60 + minutes_offset) return total_offset def _get_offset_time(utc_offset): ''' Will return the current time adjusted using the input timezone offset. :rtype datetime: ''' if utc_offset is not None: minutes = _offset_to_min(utc_offset) offset = timedelta(minutes=minutes) offset_time = datetime.utcnow() + offset offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes)) else: offset_time = datetime.now() return offset_time def get_system_time(utc_offset=None): ''' Get the system time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in HH:MM:SS AM/PM format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_time ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%I:%M:%S %p") def set_system_time(newtime, utc_offset=None): ''' Set the system time. :param str newtime: The time to set. Can be any of the following formats. - HH:MM:SS AM/PM - HH:MM AM/PM - HH:MM:SS (24 hour) - HH:MM (24 hour) Note that the salt command line parser parses the date/time before we obtain the argument (preventing us from doing utc) Therefore the argument must be passed in as a string. Meaning you may have to quote the text twice from the command line. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_time "'11:20'" ''' fmts = ['%I:%M:%S %p', '%I:%M %p', '%H:%M:%S', '%H:%M'] dt_obj = _try_parse_datetime(newtime, fmts) if dt_obj is None: return False return set_system_date_time(hours=dt_obj.hour, minutes=dt_obj.minute, seconds=dt_obj.second, utc_offset=utc_offset) def get_system_date_time(utc_offset=None): ''' Get the system date/time. :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system time in YYYY-MM-DD hh:mm:ss format. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date_time "'-0500'" ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%Y-%m-%d %H:%M:%S") def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) Updates hardware clock, if present, in addition to software (kernel) clock. :param int years: Years digit, ie: 2015 :param int months: Months digit: 1 - 12 :param int days: Days digit: 1 - 31 :param int hours: Hours digit: 0 - 23 :param int minutes: Minutes digit: 0 - 59 :param int seconds: Seconds digit: 0 - 59 :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: True if successful. Otherwise False. :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_system_date_time 2015 5 12 11 37 53 "'-0500'" ''' # Get the current date/time date_time = _get_offset_time(utc_offset) # Check for passed values. If not passed, use current values if years is None: years = date_time.year if months is None: months = date_time.month if days is None: days = date_time.day if hours is None: hours = date_time.hour if minutes is None: minutes = date_time.minute if seconds is None: seconds = date_time.second try: new_datetime = datetime(years, months, days, hours, minutes, seconds, 0, date_time.tzinfo) except ValueError as err: raise SaltInvocationError(err.message) if not _date_bin_set_datetime(new_datetime): return False if has_settable_hwclock(): # Now that we've successfully set the software clock, we should # update hardware clock for time to persist though reboot. return _swclock_to_hwclock() return True def get_system_date(utc_offset=None): ''' Get the system date :param str utc_offset: The utc offset in 4 digit (+0600) format with an optional sign (+/-). Will default to None which will use the local timezone. To set the time based off of UTC use "'+0000'". Note: if being passed through the command line will need to be quoted twice to allow negative offsets. :return: Returns the system date. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_system_date ''' offset_time = _get_offset_time(utc_offset) return datetime.strftime(offset_time, "%a %m/%d/%Y") def set_system_date(newdate, utc_offset=None): ''' Set the system date. Use <mm-dd-yy> format for the date. :param str newdate: The date to set. Can be any of the following formats: - YYYY-MM-DD - MM-DD-YYYY - MM-DD-YY - MM/DD/YYYY - MM/DD/YY - YYYY/MM/DD CLI Example: .. code-block:: bash salt '*' system.set_system_date '03-28-13' ''' fmts = ['%Y-%m-%d', '%m-%d-%Y', '%m-%d-%y', '%m/%d/%Y', '%m/%d/%y', '%Y/%m/%d'] # Get date/time object from newdate dt_obj = _try_parse_datetime(newdate, fmts) if dt_obj is None: raise SaltInvocationError("Invalid date format") # Set time using set_system_date_time() return set_system_date_time(years=dt_obj.year, months=dt_obj.month, days=dt_obj.day, utc_offset=utc_offset) # Class from: <https://docs.python.org/2.7/library/datetime.html> # A class building tzinfo objects for fixed-offset time zones. # Note that _FixedOffset(0) is a way to build a UTC tzinfo object. class _FixedOffset(tzinfo): ''' Fixed offset in minutes east from UTC. ''' def __init__(self, offset): super(_FixedOffset, self).__init__() self.__offset = timedelta(minutes=offset) def utcoffset(self, dt): # pylint: disable=W0613 return self.__offset def tzname(self, dt): # pylint: disable=W0613 return None def dst(self, dt): # pylint: disable=W0613 return timedelta(0) def _strip_quotes(str_q): ''' Helper function to strip off the ' or " off of a string ''' if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q def get_computer_desc(): ''' Get PRETTY_HOSTNAME value stored in /etc/machine-info If this file doesn't exist or the variable doesn't exist return False. :return: Value of PRETTY_HOSTNAME if this does not exist False. :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_desc ''' hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: desc = __salt__['cmd.run']( [hostname_cmd, 'status', '--pretty'], python_shell=False ) else: desc = None pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') try: with salt.utils.files.fopen('/etc/machine-info', 'r') as mach_info: for line in mach_info.readlines(): line = salt.utils.stringutils.to_unicode(line) match = pattern.match(line) if match: # get rid of whitespace then strip off quotes desc = _strip_quotes(match.group(1).strip()) # no break so we get the last occurance except IOError: pass if desc is None: return False return desc.replace(r'\"', r'"').replace(r'\n', '\n').replace(r'\t', '\t') def set_computer_desc(desc): ''' Set PRETTY_HOSTNAME value stored in /etc/machine-info This will create the file if it does not exist. If it is unable to create or modify this file returns False. :param str desc: The computer description :return: False on failure. True if successful. CLI Example: .. code-block:: bash salt '*' system.set_computer_desc "Michael's laptop" ''' desc = salt.utils.stringutils.to_unicode( desc).replace('"', r'\"').replace('\n', r'\n').replace('\t', r'\t') hostname_cmd = salt.utils.path.which('hostnamectl') if hostname_cmd: result = __salt__['cmd.retcode']( [hostname_cmd, 'set-hostname', '--pretty', desc], python_shell=False ) return True if result == 0 else False if not os.path.isfile('/etc/machine-info'): with salt.utils.files.fopen('/etc/machine-info', 'w'): pass pattern = re.compile(r'^\s*PRETTY_HOSTNAME=(.*)$') new_line = salt.utils.stringutils.to_str('PRETTY_HOSTNAME="{0}"'.format(desc)) try: with salt.utils.files.fopen('/etc/machine-info', 'r+') as mach_info: lines = mach_info.readlines() for i, line in enumerate(lines): if pattern.match(salt.utils.stringutils.to_unicode(line)): lines[i] = new_line break else: # PRETTY_HOSTNAME line was not found, add it to the end lines.append(new_line) # time to write our changes to the file mach_info.seek(0, 0) mach_info.truncate() mach_info.writelines(lines) return True except IOError: return False def set_computer_name(hostname): ''' Modify hostname. CLI Example: .. code-block:: bash salt '*' system.set_computer_name master.saltstack.com ''' return __salt__['network.mod_hostname'](hostname) def get_computer_name(): ''' Get hostname. CLI Example: .. code-block:: bash salt '*' network.get_hostname ''' return __salt__['network.get_hostname']() def _is_nilrt_family(): ''' Determine whether the minion is running on NI Linux RT ''' return __grains__.get('os_family') == 'NILinuxRT' NILRT_REBOOT_WITNESS_PATH = '/var/volatile/tmp/salt/reboot_witnessed' @depends('_is_nilrt_family') @depends('_is_nilrt_family') def get_reboot_required_witnessed(): ''' Determine if at any time during the current boot session the salt minion witnessed an event indicating that a reboot is required. Returns: bool: ``True`` if the a reboot request was witnessed, ``False`` otherwise CLI Example: .. code-block:: bash salt '*' system.get_reboot_required_witnessed ''' return os.path.exists(NILRT_REBOOT_WITNESS_PATH)
saltstack/salt
salt/transport/ipc.py
IPCServer.handle_stream
python
def handle_stream(self, stream): ''' Override this to handle the streams as they arrive :param IOStream stream: An IOStream for processing See https://tornado.readthedocs.io/en/latest/iostream.html#tornado.iostream.IOStream for additional details. ''' @tornado.gen.coroutine def _null(msg): raise tornado.gen.Return(None) def write_callback(stream, header): if header.get('mid'): @tornado.gen.coroutine def return_message(msg): pack = salt.transport.frame.frame_msg_ipc( msg, header={'mid': header['mid']}, raw_body=True, ) yield stream.write(pack) return return_message else: return _null if six.PY2: encoding = None else: encoding = 'utf-8' unpacker = msgpack.Unpacker(encoding=encoding) while not stream.closed(): try: wire_bytes = yield stream.read_bytes(4096, partial=True) unpacker.feed(wire_bytes) for framed_msg in unpacker: body = framed_msg['body'] self.io_loop.spawn_callback(self.payload_handler, body, write_callback(stream, framed_msg['head'])) except tornado.iostream.StreamClosedError: log.trace('Client disconnected from IPC %s', self.socket_path) break except socket.error as exc: # On occasion an exception will occur with # an error code of 0, it's a spurious exception. if exc.errno == 0: log.trace('Exception occured with error number 0, ' 'spurious exception: %s', exc) else: log.error('Exception occurred while ' 'handling stream: %s', exc) except Exception as exc: log.error('Exception occurred while ' 'handling stream: %s', exc)
Override this to handle the streams as they arrive :param IOStream stream: An IOStream for processing See https://tornado.readthedocs.io/en/latest/iostream.html#tornado.iostream.IOStream for additional details.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L150-L202
[ "def write_callback(stream, header):\n if header.get('mid'):\n @tornado.gen.coroutine\n def return_message(msg):\n pack = salt.transport.frame.frame_msg_ipc(\n msg,\n header={'mid': header['mid']},\n raw_body=True,\n )\n yield stream.write(pack)\n return return_message\n else:\n return _null\n" ]
class IPCServer(object): ''' A Tornado IPC server very similar to Tornado's TCPServer class but using either UNIX domain sockets or TCP sockets ''' def __init__(self, opts, socket_path, io_loop=None, payload_handler=None): ''' Create a new Tornado IPC server :param dict opts: Salt options :param str/int socket_path: Path on the filesystem for the socket to bind to. This socket does not need to exist prior to calling this method, but parent directories should. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. :param IOLoop io_loop: A Tornado ioloop to handle scheduling :param func payload_handler: A function to customize handling of incoming data. ''' self.opts = opts self.socket_path = socket_path self._started = False self.payload_handler = payload_handler # Placeholders for attributes to be populated by method calls self.sock = None self.io_loop = io_loop or IOLoop.current() self._closing = False def start(self): ''' Perform the work necessary to start up a Tornado IPC server Blocks until socket is established ''' # Start up the ioloop log.trace('IPCServer: binding to socket: %s', self.socket_path) if isinstance(self.socket_path, int): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.opts.get('ipc_so_sndbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.opts['ipc_so_sndbuf']) if self.opts.get('ipc_so_rcvbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.opts['ipc_so_rcvbuf']) self.sock.setblocking(0) self.sock.bind(('127.0.0.1', self.socket_path)) # Based on default used in tornado.netutil.bind_sockets() self.sock.listen(self.opts['ipc_so_backlog']) else: # sndbuf/rcvbuf does not apply to unix sockets self.sock = tornado.netutil.bind_unix_socket(self.socket_path, backlog=self.opts['ipc_so_backlog']) with salt.utils.asynchronous.current_ioloop(self.io_loop): tornado.netutil.add_accept_handler( self.sock, self.handle_connection, ) self._started = True @tornado.gen.coroutine def handle_connection(self, connection, address): log.trace('IPCServer: Handling connection ' 'to address: %s', address) try: with salt.utils.asynchronous.current_ioloop(self.io_loop): stream = IOStream( connection, ) self.io_loop.spawn_callback(self.handle_stream, stream) except Exception as exc: log.error('IPC streaming error: %s', exc) def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return self._closing = True if hasattr(self.sock, 'close'): self.sock.close() def __del__(self): try: self.close() except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass
saltstack/salt
salt/transport/ipc.py
IPCServer.close
python
def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return self._closing = True if hasattr(self.sock, 'close'): self.sock.close()
Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L216-L226
null
class IPCServer(object): ''' A Tornado IPC server very similar to Tornado's TCPServer class but using either UNIX domain sockets or TCP sockets ''' def __init__(self, opts, socket_path, io_loop=None, payload_handler=None): ''' Create a new Tornado IPC server :param dict opts: Salt options :param str/int socket_path: Path on the filesystem for the socket to bind to. This socket does not need to exist prior to calling this method, but parent directories should. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. :param IOLoop io_loop: A Tornado ioloop to handle scheduling :param func payload_handler: A function to customize handling of incoming data. ''' self.opts = opts self.socket_path = socket_path self._started = False self.payload_handler = payload_handler # Placeholders for attributes to be populated by method calls self.sock = None self.io_loop = io_loop or IOLoop.current() self._closing = False def start(self): ''' Perform the work necessary to start up a Tornado IPC server Blocks until socket is established ''' # Start up the ioloop log.trace('IPCServer: binding to socket: %s', self.socket_path) if isinstance(self.socket_path, int): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.opts.get('ipc_so_sndbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.opts['ipc_so_sndbuf']) if self.opts.get('ipc_so_rcvbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.opts['ipc_so_rcvbuf']) self.sock.setblocking(0) self.sock.bind(('127.0.0.1', self.socket_path)) # Based on default used in tornado.netutil.bind_sockets() self.sock.listen(self.opts['ipc_so_backlog']) else: # sndbuf/rcvbuf does not apply to unix sockets self.sock = tornado.netutil.bind_unix_socket(self.socket_path, backlog=self.opts['ipc_so_backlog']) with salt.utils.asynchronous.current_ioloop(self.io_loop): tornado.netutil.add_accept_handler( self.sock, self.handle_connection, ) self._started = True @tornado.gen.coroutine def handle_stream(self, stream): ''' Override this to handle the streams as they arrive :param IOStream stream: An IOStream for processing See https://tornado.readthedocs.io/en/latest/iostream.html#tornado.iostream.IOStream for additional details. ''' @tornado.gen.coroutine def _null(msg): raise tornado.gen.Return(None) def write_callback(stream, header): if header.get('mid'): @tornado.gen.coroutine def return_message(msg): pack = salt.transport.frame.frame_msg_ipc( msg, header={'mid': header['mid']}, raw_body=True, ) yield stream.write(pack) return return_message else: return _null if six.PY2: encoding = None else: encoding = 'utf-8' unpacker = msgpack.Unpacker(encoding=encoding) while not stream.closed(): try: wire_bytes = yield stream.read_bytes(4096, partial=True) unpacker.feed(wire_bytes) for framed_msg in unpacker: body = framed_msg['body'] self.io_loop.spawn_callback(self.payload_handler, body, write_callback(stream, framed_msg['head'])) except tornado.iostream.StreamClosedError: log.trace('Client disconnected from IPC %s', self.socket_path) break except socket.error as exc: # On occasion an exception will occur with # an error code of 0, it's a spurious exception. if exc.errno == 0: log.trace('Exception occured with error number 0, ' 'spurious exception: %s', exc) else: log.error('Exception occurred while ' 'handling stream: %s', exc) except Exception as exc: log.error('Exception occurred while ' 'handling stream: %s', exc) def handle_connection(self, connection, address): log.trace('IPCServer: Handling connection ' 'to address: %s', address) try: with salt.utils.asynchronous.current_ioloop(self.io_loop): stream = IOStream( connection, ) self.io_loop.spawn_callback(self.handle_stream, stream) except Exception as exc: log.error('IPC streaming error: %s', exc) def __del__(self): try: self.close() except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass
saltstack/salt
salt/transport/ipc.py
IPCClient.connect
python
def connect(self, callback=None, timeout=None): ''' Connect to the IPC socket ''' if hasattr(self, '_connecting_future') and not self._connecting_future.done(): # pylint: disable=E0203 future = self._connecting_future # pylint: disable=E0203 else: if hasattr(self, '_connecting_future'): # read previous future result to prevent the "unhandled future exception" error self._connecting_future.exception() # pylint: disable=E0203 future = tornado.concurrent.Future() self._connecting_future = future self._connect(timeout=timeout) if callback is not None: def handle_future(future): response = future.result() self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) return future
Connect to the IPC socket
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L308-L328
null
class IPCClient(object): ''' A Tornado IPC client very similar to Tornado's TCPClient class but using either UNIX domain sockets or TCP sockets This was written because Tornado does not have its own IPC server/client implementation. :param IOLoop io_loop: A Tornado ioloop to handle scheduling :param str/int socket_path: A path on the filesystem where a socket belonging to a running IPCServer can be found. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. ''' # Create singleton map between two sockets instance_map = weakref.WeakKeyDictionary() def __new__(cls, socket_path, io_loop=None): io_loop = io_loop or tornado.ioloop.IOLoop.current() if io_loop not in IPCClient.instance_map: IPCClient.instance_map[io_loop] = weakref.WeakValueDictionary() loop_instance_map = IPCClient.instance_map[io_loop] # FIXME key = six.text_type(socket_path) client = loop_instance_map.get(key) if client is None: log.debug('Initializing new IPCClient for path: %s', key) client = object.__new__(cls) # FIXME client.__singleton_init__(io_loop=io_loop, socket_path=socket_path) client._instance_key = key loop_instance_map[key] = client client._refcount = 1 client._refcount_lock = threading.RLock() else: log.debug('Re-using IPCClient for %s', key) with client._refcount_lock: client._refcount += 1 return client def __singleton_init__(self, socket_path, io_loop=None): ''' Create a new IPC client IPC clients cannot bind to ports, but must connect to existing IPC servers. Clients can then send messages to the server. ''' self.io_loop = io_loop or tornado.ioloop.IOLoop.current() self.socket_path = socket_path self._closing = False self.stream = None if six.PY2: encoding = None else: encoding = 'utf-8' self.unpacker = msgpack.Unpacker(encoding=encoding) def __init__(self, socket_path, io_loop=None): # Handled by singleton __new__ pass def connected(self): return self.stream is not None and not self.stream.closed() @tornado.gen.coroutine def _connect(self, timeout=None): ''' Connect to a running IPCServer ''' if isinstance(self.socket_path, int): sock_type = socket.AF_INET sock_addr = ('127.0.0.1', self.socket_path) else: sock_type = socket.AF_UNIX sock_addr = self.socket_path self.stream = None if timeout is not None: timeout_at = time.time() + timeout while True: if self._closing: break if self.stream is None: with salt.utils.asynchronous.current_ioloop(self.io_loop): self.stream = IOStream( socket.socket(sock_type, socket.SOCK_STREAM), ) try: log.trace('IPCClient: Connecting to socket: %s', self.socket_path) yield self.stream.connect(sock_addr) self._connecting_future.set_result(True) break except Exception as e: if self.stream.closed(): self.stream = None if timeout is None or time.time() > timeout_at: if self.stream is not None: self.stream.close() self.stream = None self._connecting_future.set_exception(e) break yield tornado.gen.sleep(1) def __del__(self): try: with self._refcount_lock: # Make sure we actually close no matter if something # went wrong with our ref counting self._refcount = 1 try: self.close() except socket.error as exc: if exc.errno != errno.EBADF: # If its not a bad file descriptor error, raise raise except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return if self._refcount > 1: # Decrease refcount with self._refcount_lock: self._refcount -= 1 log.debug( 'This is not the last %s instance. Not closing yet.', self.__class__.__name__ ) return self._closing = True log.debug('Closing %s instance', self.__class__.__name__) if self.stream is not None and not self.stream.closed(): self.stream.close() # Remove the entry from the instance map so # that a closed entry may not be reused. # This forces this operation even if the reference # count of the entry has not yet gone to zero. if self.io_loop in self.__class__.instance_map: loop_instance_map = self.__class__.instance_map[self.io_loop] if self._instance_key in loop_instance_map: del loop_instance_map[self._instance_key] if not loop_instance_map: del self.__class__.instance_map[self.io_loop]
saltstack/salt
salt/transport/ipc.py
IPCClient._connect
python
def _connect(self, timeout=None): ''' Connect to a running IPCServer ''' if isinstance(self.socket_path, int): sock_type = socket.AF_INET sock_addr = ('127.0.0.1', self.socket_path) else: sock_type = socket.AF_UNIX sock_addr = self.socket_path self.stream = None if timeout is not None: timeout_at = time.time() + timeout while True: if self._closing: break if self.stream is None: with salt.utils.asynchronous.current_ioloop(self.io_loop): self.stream = IOStream( socket.socket(sock_type, socket.SOCK_STREAM), ) try: log.trace('IPCClient: Connecting to socket: %s', self.socket_path) yield self.stream.connect(sock_addr) self._connecting_future.set_result(True) break except Exception as e: if self.stream.closed(): self.stream = None if timeout is None or time.time() > timeout_at: if self.stream is not None: self.stream.close() self.stream = None self._connecting_future.set_exception(e) break yield tornado.gen.sleep(1)
Connect to a running IPCServer
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L331-L372
null
class IPCClient(object): ''' A Tornado IPC client very similar to Tornado's TCPClient class but using either UNIX domain sockets or TCP sockets This was written because Tornado does not have its own IPC server/client implementation. :param IOLoop io_loop: A Tornado ioloop to handle scheduling :param str/int socket_path: A path on the filesystem where a socket belonging to a running IPCServer can be found. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. ''' # Create singleton map between two sockets instance_map = weakref.WeakKeyDictionary() def __new__(cls, socket_path, io_loop=None): io_loop = io_loop or tornado.ioloop.IOLoop.current() if io_loop not in IPCClient.instance_map: IPCClient.instance_map[io_loop] = weakref.WeakValueDictionary() loop_instance_map = IPCClient.instance_map[io_loop] # FIXME key = six.text_type(socket_path) client = loop_instance_map.get(key) if client is None: log.debug('Initializing new IPCClient for path: %s', key) client = object.__new__(cls) # FIXME client.__singleton_init__(io_loop=io_loop, socket_path=socket_path) client._instance_key = key loop_instance_map[key] = client client._refcount = 1 client._refcount_lock = threading.RLock() else: log.debug('Re-using IPCClient for %s', key) with client._refcount_lock: client._refcount += 1 return client def __singleton_init__(self, socket_path, io_loop=None): ''' Create a new IPC client IPC clients cannot bind to ports, but must connect to existing IPC servers. Clients can then send messages to the server. ''' self.io_loop = io_loop or tornado.ioloop.IOLoop.current() self.socket_path = socket_path self._closing = False self.stream = None if six.PY2: encoding = None else: encoding = 'utf-8' self.unpacker = msgpack.Unpacker(encoding=encoding) def __init__(self, socket_path, io_loop=None): # Handled by singleton __new__ pass def connected(self): return self.stream is not None and not self.stream.closed() def connect(self, callback=None, timeout=None): ''' Connect to the IPC socket ''' if hasattr(self, '_connecting_future') and not self._connecting_future.done(): # pylint: disable=E0203 future = self._connecting_future # pylint: disable=E0203 else: if hasattr(self, '_connecting_future'): # read previous future result to prevent the "unhandled future exception" error self._connecting_future.exception() # pylint: disable=E0203 future = tornado.concurrent.Future() self._connecting_future = future self._connect(timeout=timeout) if callback is not None: def handle_future(future): response = future.result() self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) return future @tornado.gen.coroutine def __del__(self): try: with self._refcount_lock: # Make sure we actually close no matter if something # went wrong with our ref counting self._refcount = 1 try: self.close() except socket.error as exc: if exc.errno != errno.EBADF: # If its not a bad file descriptor error, raise raise except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return if self._refcount > 1: # Decrease refcount with self._refcount_lock: self._refcount -= 1 log.debug( 'This is not the last %s instance. Not closing yet.', self.__class__.__name__ ) return self._closing = True log.debug('Closing %s instance', self.__class__.__name__) if self.stream is not None and not self.stream.closed(): self.stream.close() # Remove the entry from the instance map so # that a closed entry may not be reused. # This forces this operation even if the reference # count of the entry has not yet gone to zero. if self.io_loop in self.__class__.instance_map: loop_instance_map = self.__class__.instance_map[self.io_loop] if self._instance_key in loop_instance_map: del loop_instance_map[self._instance_key] if not loop_instance_map: del self.__class__.instance_map[self.io_loop]
saltstack/salt
salt/transport/ipc.py
IPCClient.close
python
def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return if self._refcount > 1: # Decrease refcount with self._refcount_lock: self._refcount -= 1 log.debug( 'This is not the last %s instance. Not closing yet.', self.__class__.__name__ ) return self._closing = True log.debug('Closing %s instance', self.__class__.__name__) if self.stream is not None and not self.stream.closed(): self.stream.close() # Remove the entry from the instance map so # that a closed entry may not be reused. # This forces this operation even if the reference # count of the entry has not yet gone to zero. if self.io_loop in self.__class__.instance_map: loop_instance_map = self.__class__.instance_map[self.io_loop] if self._instance_key in loop_instance_map: del loop_instance_map[self._instance_key] if not loop_instance_map: del self.__class__.instance_map[self.io_loop]
Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L391-L426
null
class IPCClient(object): ''' A Tornado IPC client very similar to Tornado's TCPClient class but using either UNIX domain sockets or TCP sockets This was written because Tornado does not have its own IPC server/client implementation. :param IOLoop io_loop: A Tornado ioloop to handle scheduling :param str/int socket_path: A path on the filesystem where a socket belonging to a running IPCServer can be found. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. ''' # Create singleton map between two sockets instance_map = weakref.WeakKeyDictionary() def __new__(cls, socket_path, io_loop=None): io_loop = io_loop or tornado.ioloop.IOLoop.current() if io_loop not in IPCClient.instance_map: IPCClient.instance_map[io_loop] = weakref.WeakValueDictionary() loop_instance_map = IPCClient.instance_map[io_loop] # FIXME key = six.text_type(socket_path) client = loop_instance_map.get(key) if client is None: log.debug('Initializing new IPCClient for path: %s', key) client = object.__new__(cls) # FIXME client.__singleton_init__(io_loop=io_loop, socket_path=socket_path) client._instance_key = key loop_instance_map[key] = client client._refcount = 1 client._refcount_lock = threading.RLock() else: log.debug('Re-using IPCClient for %s', key) with client._refcount_lock: client._refcount += 1 return client def __singleton_init__(self, socket_path, io_loop=None): ''' Create a new IPC client IPC clients cannot bind to ports, but must connect to existing IPC servers. Clients can then send messages to the server. ''' self.io_loop = io_loop or tornado.ioloop.IOLoop.current() self.socket_path = socket_path self._closing = False self.stream = None if six.PY2: encoding = None else: encoding = 'utf-8' self.unpacker = msgpack.Unpacker(encoding=encoding) def __init__(self, socket_path, io_loop=None): # Handled by singleton __new__ pass def connected(self): return self.stream is not None and not self.stream.closed() def connect(self, callback=None, timeout=None): ''' Connect to the IPC socket ''' if hasattr(self, '_connecting_future') and not self._connecting_future.done(): # pylint: disable=E0203 future = self._connecting_future # pylint: disable=E0203 else: if hasattr(self, '_connecting_future'): # read previous future result to prevent the "unhandled future exception" error self._connecting_future.exception() # pylint: disable=E0203 future = tornado.concurrent.Future() self._connecting_future = future self._connect(timeout=timeout) if callback is not None: def handle_future(future): response = future.result() self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) return future @tornado.gen.coroutine def _connect(self, timeout=None): ''' Connect to a running IPCServer ''' if isinstance(self.socket_path, int): sock_type = socket.AF_INET sock_addr = ('127.0.0.1', self.socket_path) else: sock_type = socket.AF_UNIX sock_addr = self.socket_path self.stream = None if timeout is not None: timeout_at = time.time() + timeout while True: if self._closing: break if self.stream is None: with salt.utils.asynchronous.current_ioloop(self.io_loop): self.stream = IOStream( socket.socket(sock_type, socket.SOCK_STREAM), ) try: log.trace('IPCClient: Connecting to socket: %s', self.socket_path) yield self.stream.connect(sock_addr) self._connecting_future.set_result(True) break except Exception as e: if self.stream.closed(): self.stream = None if timeout is None or time.time() > timeout_at: if self.stream is not None: self.stream.close() self.stream = None self._connecting_future.set_exception(e) break yield tornado.gen.sleep(1) def __del__(self): try: with self._refcount_lock: # Make sure we actually close no matter if something # went wrong with our ref counting self._refcount = 1 try: self.close() except socket.error as exc: if exc.errno != errno.EBADF: # If its not a bad file descriptor error, raise raise except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass
saltstack/salt
salt/transport/ipc.py
IPCMessageClient.send
python
def send(self, msg, timeout=None, tries=None): ''' Send a message to an IPC socket If the socket is not currently connected, a connection will be established. :param dict msg: The message to be sent :param int timeout: Timeout when sending message (Currently unimplemented) ''' if not self.connected(): yield self.connect() pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True) yield self.stream.write(pack)
Send a message to an IPC socket If the socket is not currently connected, a connection will be established. :param dict msg: The message to be sent :param int timeout: Timeout when sending message (Currently unimplemented)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L462-L474
[ "def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument\n '''\n Frame the given message with our wire protocol for IPC\n\n For IPC, we don't need to be backwards compatible, so\n use the more efficient \"use_bin_type=True\" on Python 3.\n '''\n framed_msg = {}\n if header is None:\n header = {}\n\n framed_msg['head'] = header\n framed_msg['body'] = body\n if six.PY2:\n return salt.utils.msgpack.dumps(framed_msg)\n else:\n return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True)\n", "def connected(self):\n return self.stream is not None and not self.stream.closed()\n" ]
class IPCMessageClient(IPCClient): ''' Salt IPC message client Create an IPC client to send messages to an IPC server An example of a very simple IPCMessageClient connecting to an IPCServer. This example assumes an already running IPCMessage server. IMPORTANT: The below example also assumes a running IOLoop process. # Import Tornado libs import tornado.ioloop # Import Salt libs import salt.config import salt.transport.ipc io_loop = tornado.ioloop.IOLoop.current() ipc_server_socket_path = '/var/run/ipc_server.ipc' ipc_client = salt.transport.ipc.IPCMessageClient(ipc_server_socket_path, io_loop=io_loop) # Connect to the server ipc_client.connect() # Send some data ipc_client.send('Hello world') ''' # FIXME timeout unimplemented # FIXME tries unimplemented @tornado.gen.coroutine
saltstack/salt
salt/transport/ipc.py
IPCMessagePublisher.start
python
def start(self): ''' Perform the work necessary to start up a Tornado IPC server Blocks until socket is established ''' # Start up the ioloop log.trace('IPCMessagePublisher: binding to socket: %s', self.socket_path) if isinstance(self.socket_path, int): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.opts.get('ipc_so_sndbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.opts['ipc_so_sndbuf']) if self.opts.get('ipc_so_rcvbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.opts['ipc_so_rcvbuf']) self.sock.setblocking(0) self.sock.bind(('127.0.0.1', self.socket_path)) # Based on default used in tornado.netutil.bind_sockets() self.sock.listen(self.opts['ipc_so_backlog']) else: # sndbuf/rcvbuf does not apply to unix sockets self.sock = tornado.netutil.bind_unix_socket(self.socket_path, backlog=self.opts['ipc_so_backlog']) with salt.utils.asynchronous.current_ioloop(self.io_loop): tornado.netutil.add_accept_handler( self.sock, self.handle_connection, ) self._started = True
Perform the work necessary to start up a Tornado IPC server Blocks until socket is established
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L540-L568
null
class IPCMessagePublisher(object): ''' A Tornado IPC Publisher similar to Tornado's TCPServer class but using either UNIX domain sockets or TCP sockets ''' def __init__(self, opts, socket_path, io_loop=None): ''' Create a new Tornado IPC server :param dict opts: Salt options :param str/int socket_path: Path on the filesystem for the socket to bind to. This socket does not need to exist prior to calling this method, but parent directories should. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. :param IOLoop io_loop: A Tornado ioloop to handle scheduling ''' self.opts = opts self.socket_path = socket_path self._started = False # Placeholders for attributes to be populated by method calls self.sock = None self.io_loop = io_loop or IOLoop.current() self._closing = False self.streams = set() @tornado.gen.coroutine def _write(self, stream, pack): try: yield stream.write(pack) except tornado.iostream.StreamClosedError: log.trace('Client disconnected from IPC %s', self.socket_path) self.streams.discard(stream) except Exception as exc: log.error('Exception occurred while handling stream: %s', exc) if not stream.closed(): stream.close() self.streams.discard(stream) def publish(self, msg): ''' Send message to all connected sockets ''' if not self.streams: return pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True) for stream in self.streams: self.io_loop.spawn_callback(self._write, stream, pack) def handle_connection(self, connection, address): log.trace('IPCServer: Handling connection to address: %s', address) try: kwargs = {} if self.opts['ipc_write_buffer'] > 0: kwargs['max_write_buffer_size'] = self.opts['ipc_write_buffer'] log.trace('Setting IPC connection write buffer: %s', (self.opts['ipc_write_buffer'])) with salt.utils.asynchronous.current_ioloop(self.io_loop): stream = IOStream( connection, **kwargs ) self.streams.add(stream) def discard_after_closed(): self.streams.discard(stream) stream.set_close_callback(discard_after_closed) except Exception as exc: log.error('IPC streaming error: %s', exc) def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return self._closing = True for stream in self.streams: stream.close() self.streams.clear() if hasattr(self.sock, 'close'): self.sock.close() def __del__(self): try: self.close() except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass
saltstack/salt
salt/transport/ipc.py
IPCMessagePublisher.publish
python
def publish(self, msg): ''' Send message to all connected sockets ''' if not self.streams: return pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True) for stream in self.streams: self.io_loop.spawn_callback(self._write, stream, pack)
Send message to all connected sockets
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L583-L593
[ "def frame_msg_ipc(body, header=None, raw_body=False): # pylint: disable=unused-argument\n '''\n Frame the given message with our wire protocol for IPC\n\n For IPC, we don't need to be backwards compatible, so\n use the more efficient \"use_bin_type=True\" on Python 3.\n '''\n framed_msg = {}\n if header is None:\n header = {}\n\n framed_msg['head'] = header\n framed_msg['body'] = body\n if six.PY2:\n return salt.utils.msgpack.dumps(framed_msg)\n else:\n return salt.utils.msgpack.dumps(framed_msg, use_bin_type=True)\n" ]
class IPCMessagePublisher(object): ''' A Tornado IPC Publisher similar to Tornado's TCPServer class but using either UNIX domain sockets or TCP sockets ''' def __init__(self, opts, socket_path, io_loop=None): ''' Create a new Tornado IPC server :param dict opts: Salt options :param str/int socket_path: Path on the filesystem for the socket to bind to. This socket does not need to exist prior to calling this method, but parent directories should. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. :param IOLoop io_loop: A Tornado ioloop to handle scheduling ''' self.opts = opts self.socket_path = socket_path self._started = False # Placeholders for attributes to be populated by method calls self.sock = None self.io_loop = io_loop or IOLoop.current() self._closing = False self.streams = set() def start(self): ''' Perform the work necessary to start up a Tornado IPC server Blocks until socket is established ''' # Start up the ioloop log.trace('IPCMessagePublisher: binding to socket: %s', self.socket_path) if isinstance(self.socket_path, int): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.opts.get('ipc_so_sndbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.opts['ipc_so_sndbuf']) if self.opts.get('ipc_so_rcvbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.opts['ipc_so_rcvbuf']) self.sock.setblocking(0) self.sock.bind(('127.0.0.1', self.socket_path)) # Based on default used in tornado.netutil.bind_sockets() self.sock.listen(self.opts['ipc_so_backlog']) else: # sndbuf/rcvbuf does not apply to unix sockets self.sock = tornado.netutil.bind_unix_socket(self.socket_path, backlog=self.opts['ipc_so_backlog']) with salt.utils.asynchronous.current_ioloop(self.io_loop): tornado.netutil.add_accept_handler( self.sock, self.handle_connection, ) self._started = True @tornado.gen.coroutine def _write(self, stream, pack): try: yield stream.write(pack) except tornado.iostream.StreamClosedError: log.trace('Client disconnected from IPC %s', self.socket_path) self.streams.discard(stream) except Exception as exc: log.error('Exception occurred while handling stream: %s', exc) if not stream.closed(): stream.close() self.streams.discard(stream) def handle_connection(self, connection, address): log.trace('IPCServer: Handling connection to address: %s', address) try: kwargs = {} if self.opts['ipc_write_buffer'] > 0: kwargs['max_write_buffer_size'] = self.opts['ipc_write_buffer'] log.trace('Setting IPC connection write buffer: %s', (self.opts['ipc_write_buffer'])) with salt.utils.asynchronous.current_ioloop(self.io_loop): stream = IOStream( connection, **kwargs ) self.streams.add(stream) def discard_after_closed(): self.streams.discard(stream) stream.set_close_callback(discard_after_closed) except Exception as exc: log.error('IPC streaming error: %s', exc) def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return self._closing = True for stream in self.streams: stream.close() self.streams.clear() if hasattr(self.sock, 'close'): self.sock.close() def __del__(self): try: self.close() except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass
saltstack/salt
salt/transport/ipc.py
IPCMessagePublisher.close
python
def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return self._closing = True for stream in self.streams: stream.close() self.streams.clear() if hasattr(self.sock, 'close'): self.sock.close()
Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L616-L629
null
class IPCMessagePublisher(object): ''' A Tornado IPC Publisher similar to Tornado's TCPServer class but using either UNIX domain sockets or TCP sockets ''' def __init__(self, opts, socket_path, io_loop=None): ''' Create a new Tornado IPC server :param dict opts: Salt options :param str/int socket_path: Path on the filesystem for the socket to bind to. This socket does not need to exist prior to calling this method, but parent directories should. It may also be of type 'int', in which case it is used as the port for a tcp localhost connection. :param IOLoop io_loop: A Tornado ioloop to handle scheduling ''' self.opts = opts self.socket_path = socket_path self._started = False # Placeholders for attributes to be populated by method calls self.sock = None self.io_loop = io_loop or IOLoop.current() self._closing = False self.streams = set() def start(self): ''' Perform the work necessary to start up a Tornado IPC server Blocks until socket is established ''' # Start up the ioloop log.trace('IPCMessagePublisher: binding to socket: %s', self.socket_path) if isinstance(self.socket_path, int): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.opts.get('ipc_so_sndbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.opts['ipc_so_sndbuf']) if self.opts.get('ipc_so_rcvbuf'): self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.opts['ipc_so_rcvbuf']) self.sock.setblocking(0) self.sock.bind(('127.0.0.1', self.socket_path)) # Based on default used in tornado.netutil.bind_sockets() self.sock.listen(self.opts['ipc_so_backlog']) else: # sndbuf/rcvbuf does not apply to unix sockets self.sock = tornado.netutil.bind_unix_socket(self.socket_path, backlog=self.opts['ipc_so_backlog']) with salt.utils.asynchronous.current_ioloop(self.io_loop): tornado.netutil.add_accept_handler( self.sock, self.handle_connection, ) self._started = True @tornado.gen.coroutine def _write(self, stream, pack): try: yield stream.write(pack) except tornado.iostream.StreamClosedError: log.trace('Client disconnected from IPC %s', self.socket_path) self.streams.discard(stream) except Exception as exc: log.error('Exception occurred while handling stream: %s', exc) if not stream.closed(): stream.close() self.streams.discard(stream) def publish(self, msg): ''' Send message to all connected sockets ''' if not self.streams: return pack = salt.transport.frame.frame_msg_ipc(msg, raw_body=True) for stream in self.streams: self.io_loop.spawn_callback(self._write, stream, pack) def handle_connection(self, connection, address): log.trace('IPCServer: Handling connection to address: %s', address) try: kwargs = {} if self.opts['ipc_write_buffer'] > 0: kwargs['max_write_buffer_size'] = self.opts['ipc_write_buffer'] log.trace('Setting IPC connection write buffer: %s', (self.opts['ipc_write_buffer'])) with salt.utils.asynchronous.current_ioloop(self.io_loop): stream = IOStream( connection, **kwargs ) self.streams.add(stream) def discard_after_closed(): self.streams.discard(stream) stream.set_close_callback(discard_after_closed) except Exception as exc: log.error('IPC streaming error: %s', exc) def __del__(self): try: self.close() except TypeError: # This is raised when Python's GC has collected objects which # would be needed when calling self.close() pass
saltstack/salt
salt/transport/ipc.py
IPCMessageSubscriber.read_sync
python
def read_sync(self, timeout=None): ''' Read a message from an IPC socket The socket must already be connected. The associated IO Loop must NOT be running. :param int timeout: Timeout when receiving message :return: message data if successful. None if timed out. Will raise an exception for all other error conditions. ''' if self.saved_data: return self.saved_data.pop(0) self._sync_ioloop_running = True self._read_sync_future = self._read_sync(timeout) self.io_loop.start() self._sync_ioloop_running = False ret_future = self._read_sync_future self._read_sync_future = None return ret_future.result()
Read a message from an IPC socket The socket must already be connected. The associated IO Loop must NOT be running. :param int timeout: Timeout when receiving message :return: message data if successful. None if timed out. Will raise an exception for all other error conditions.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L743-L763
null
class IPCMessageSubscriber(IPCClient): ''' Salt IPC message subscriber Create an IPC client to receive messages from IPC publisher An example of a very simple IPCMessageSubscriber connecting to an IPCMessagePublisher. This example assumes an already running IPCMessagePublisher. IMPORTANT: The below example also assumes the IOLoop is NOT running. # Import Tornado libs import tornado.ioloop # Import Salt libs import salt.config import salt.transport.ipc # Create a new IO Loop. # We know that this new IO Loop is not currently running. io_loop = tornado.ioloop.IOLoop() ipc_publisher_socket_path = '/var/run/ipc_publisher.ipc' ipc_subscriber = salt.transport.ipc.IPCMessageSubscriber(ipc_server_socket_path, io_loop=io_loop) # Connect to the server # Use the associated IO Loop that isn't running. io_loop.run_sync(ipc_subscriber.connect) # Wait for some data package = ipc_subscriber.read_sync() ''' def __singleton_init__(self, socket_path, io_loop=None): super(IPCMessageSubscriber, self).__singleton_init__( socket_path, io_loop=io_loop) self._read_sync_future = None self._read_stream_future = None self._sync_ioloop_running = False self.saved_data = [] self._sync_read_in_progress = Semaphore() self.callbacks = set() self.reading = False @tornado.gen.coroutine def _read_sync(self, timeout): yield self._sync_read_in_progress.acquire() exc_to_raise = None ret = None try: while True: if self._read_stream_future is None: self._read_stream_future = self.stream.read_bytes(4096, partial=True) if timeout is None: wire_bytes = yield self._read_stream_future else: future_with_timeout = FutureWithTimeout( self.io_loop, self._read_stream_future, timeout) wire_bytes = yield future_with_timeout self._read_stream_future = None # Remove the timeout once we get some data or an exception # occurs. We will assume that the rest of the data is already # there or is coming soon if an exception doesn't occur. timeout = None self.unpacker.feed(wire_bytes) first = True for framed_msg in self.unpacker: if first: ret = framed_msg['body'] first = False else: self.saved_data.append(framed_msg['body']) if not first: # We read at least one piece of data break except TornadoTimeoutError: # In the timeout case, just return None. # Keep 'self._read_stream_future' alive. ret = None except tornado.iostream.StreamClosedError as exc: log.trace('Subscriber disconnected from IPC %s', self.socket_path) self._read_stream_future = None exc_to_raise = exc except Exception as exc: log.error('Exception occurred in Subscriber while handling stream: %s', exc) self._read_stream_future = None exc_to_raise = exc if self._sync_ioloop_running: # Stop the IO Loop so that self.io_loop.start() will return in # read_sync(). self.io_loop.spawn_callback(self.io_loop.stop) if exc_to_raise is not None: raise exc_to_raise # pylint: disable=E0702 self._sync_read_in_progress.release() raise tornado.gen.Return(ret) @tornado.gen.coroutine def _read_async(self, callback): while not self.stream.closed(): try: self._read_stream_future = self.stream.read_bytes(4096, partial=True) self.reading = True wire_bytes = yield self._read_stream_future self._read_stream_future = None self.unpacker.feed(wire_bytes) for framed_msg in self.unpacker: body = framed_msg['body'] self.io_loop.spawn_callback(callback, body) except tornado.iostream.StreamClosedError: log.trace('Subscriber disconnected from IPC %s', self.socket_path) break except Exception as exc: log.error('Exception occurred while Subscriber handling stream: %s', exc) def __run_callbacks(self, raw): for callback in self.callbacks: self.io_loop.spawn_callback(callback, raw) @tornado.gen.coroutine def read_async(self): ''' Asynchronously read messages and invoke a callback when they are ready. :param callback: A callback with the received data ''' while not self.connected(): try: yield self.connect(timeout=5) except tornado.iostream.StreamClosedError: log.trace('Subscriber closed stream on IPC %s before connect', self.socket_path) yield tornado.gen.sleep(1) except Exception as exc: log.error('Exception occurred while Subscriber connecting: %s', exc) yield tornado.gen.sleep(1) yield self._read_async(self.__run_callbacks) def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if not self._closing: IPCClient.close(self) if self._closing: # This will prevent this message from showing up: # '[ERROR ] Future exception was never retrieved: # StreamClosedError' if self._read_sync_future is not None and self._read_sync_future.done(): self._read_sync_future.exception() if self._read_stream_future is not None and self._read_stream_future.done(): self._read_stream_future.exception()
saltstack/salt
salt/transport/ipc.py
IPCMessageSubscriber.read_async
python
def read_async(self): ''' Asynchronously read messages and invoke a callback when they are ready. :param callback: A callback with the received data ''' while not self.connected(): try: yield self.connect(timeout=5) except tornado.iostream.StreamClosedError: log.trace('Subscriber closed stream on IPC %s before connect', self.socket_path) yield tornado.gen.sleep(1) except Exception as exc: log.error('Exception occurred while Subscriber connecting: %s', exc) yield tornado.gen.sleep(1) yield self._read_async(self.__run_callbacks)
Asynchronously read messages and invoke a callback when they are ready. :param callback: A callback with the received data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L788-L803
[ "def connected(self):\n return self.stream is not None and not self.stream.closed()\n" ]
class IPCMessageSubscriber(IPCClient): ''' Salt IPC message subscriber Create an IPC client to receive messages from IPC publisher An example of a very simple IPCMessageSubscriber connecting to an IPCMessagePublisher. This example assumes an already running IPCMessagePublisher. IMPORTANT: The below example also assumes the IOLoop is NOT running. # Import Tornado libs import tornado.ioloop # Import Salt libs import salt.config import salt.transport.ipc # Create a new IO Loop. # We know that this new IO Loop is not currently running. io_loop = tornado.ioloop.IOLoop() ipc_publisher_socket_path = '/var/run/ipc_publisher.ipc' ipc_subscriber = salt.transport.ipc.IPCMessageSubscriber(ipc_server_socket_path, io_loop=io_loop) # Connect to the server # Use the associated IO Loop that isn't running. io_loop.run_sync(ipc_subscriber.connect) # Wait for some data package = ipc_subscriber.read_sync() ''' def __singleton_init__(self, socket_path, io_loop=None): super(IPCMessageSubscriber, self).__singleton_init__( socket_path, io_loop=io_loop) self._read_sync_future = None self._read_stream_future = None self._sync_ioloop_running = False self.saved_data = [] self._sync_read_in_progress = Semaphore() self.callbacks = set() self.reading = False @tornado.gen.coroutine def _read_sync(self, timeout): yield self._sync_read_in_progress.acquire() exc_to_raise = None ret = None try: while True: if self._read_stream_future is None: self._read_stream_future = self.stream.read_bytes(4096, partial=True) if timeout is None: wire_bytes = yield self._read_stream_future else: future_with_timeout = FutureWithTimeout( self.io_loop, self._read_stream_future, timeout) wire_bytes = yield future_with_timeout self._read_stream_future = None # Remove the timeout once we get some data or an exception # occurs. We will assume that the rest of the data is already # there or is coming soon if an exception doesn't occur. timeout = None self.unpacker.feed(wire_bytes) first = True for framed_msg in self.unpacker: if first: ret = framed_msg['body'] first = False else: self.saved_data.append(framed_msg['body']) if not first: # We read at least one piece of data break except TornadoTimeoutError: # In the timeout case, just return None. # Keep 'self._read_stream_future' alive. ret = None except tornado.iostream.StreamClosedError as exc: log.trace('Subscriber disconnected from IPC %s', self.socket_path) self._read_stream_future = None exc_to_raise = exc except Exception as exc: log.error('Exception occurred in Subscriber while handling stream: %s', exc) self._read_stream_future = None exc_to_raise = exc if self._sync_ioloop_running: # Stop the IO Loop so that self.io_loop.start() will return in # read_sync(). self.io_loop.spawn_callback(self.io_loop.stop) if exc_to_raise is not None: raise exc_to_raise # pylint: disable=E0702 self._sync_read_in_progress.release() raise tornado.gen.Return(ret) def read_sync(self, timeout=None): ''' Read a message from an IPC socket The socket must already be connected. The associated IO Loop must NOT be running. :param int timeout: Timeout when receiving message :return: message data if successful. None if timed out. Will raise an exception for all other error conditions. ''' if self.saved_data: return self.saved_data.pop(0) self._sync_ioloop_running = True self._read_sync_future = self._read_sync(timeout) self.io_loop.start() self._sync_ioloop_running = False ret_future = self._read_sync_future self._read_sync_future = None return ret_future.result() @tornado.gen.coroutine def _read_async(self, callback): while not self.stream.closed(): try: self._read_stream_future = self.stream.read_bytes(4096, partial=True) self.reading = True wire_bytes = yield self._read_stream_future self._read_stream_future = None self.unpacker.feed(wire_bytes) for framed_msg in self.unpacker: body = framed_msg['body'] self.io_loop.spawn_callback(callback, body) except tornado.iostream.StreamClosedError: log.trace('Subscriber disconnected from IPC %s', self.socket_path) break except Exception as exc: log.error('Exception occurred while Subscriber handling stream: %s', exc) def __run_callbacks(self, raw): for callback in self.callbacks: self.io_loop.spawn_callback(callback, raw) @tornado.gen.coroutine def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if not self._closing: IPCClient.close(self) if self._closing: # This will prevent this message from showing up: # '[ERROR ] Future exception was never retrieved: # StreamClosedError' if self._read_sync_future is not None and self._read_sync_future.done(): self._read_sync_future.exception() if self._read_stream_future is not None and self._read_stream_future.done(): self._read_stream_future.exception()
saltstack/salt
salt/transport/ipc.py
IPCMessageSubscriber.close
python
def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if not self._closing: IPCClient.close(self) if self._closing: # This will prevent this message from showing up: # '[ERROR ] Future exception was never retrieved: # StreamClosedError' if self._read_sync_future is not None and self._read_sync_future.done(): self._read_sync_future.exception() if self._read_stream_future is not None and self._read_stream_future.done(): self._read_stream_future.exception()
Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/ipc.py#L805-L820
[ "def close(self):\n '''\n Routines to handle any cleanup before the instance shuts down.\n Sockets and filehandles should be closed explicitly, to prevent\n leaks.\n '''\n if self._closing:\n return\n\n if self._refcount > 1:\n # Decrease refcount\n with self._refcount_lock:\n self._refcount -= 1\n log.debug(\n 'This is not the last %s instance. Not closing yet.',\n self.__class__.__name__\n )\n return\n\n self._closing = True\n\n log.debug('Closing %s instance', self.__class__.__name__)\n\n if self.stream is not None and not self.stream.closed():\n self.stream.close()\n\n # Remove the entry from the instance map so\n # that a closed entry may not be reused.\n # This forces this operation even if the reference\n # count of the entry has not yet gone to zero.\n if self.io_loop in self.__class__.instance_map:\n loop_instance_map = self.__class__.instance_map[self.io_loop]\n if self._instance_key in loop_instance_map:\n del loop_instance_map[self._instance_key]\n if not loop_instance_map:\n del self.__class__.instance_map[self.io_loop]\n" ]
class IPCMessageSubscriber(IPCClient): ''' Salt IPC message subscriber Create an IPC client to receive messages from IPC publisher An example of a very simple IPCMessageSubscriber connecting to an IPCMessagePublisher. This example assumes an already running IPCMessagePublisher. IMPORTANT: The below example also assumes the IOLoop is NOT running. # Import Tornado libs import tornado.ioloop # Import Salt libs import salt.config import salt.transport.ipc # Create a new IO Loop. # We know that this new IO Loop is not currently running. io_loop = tornado.ioloop.IOLoop() ipc_publisher_socket_path = '/var/run/ipc_publisher.ipc' ipc_subscriber = salt.transport.ipc.IPCMessageSubscriber(ipc_server_socket_path, io_loop=io_loop) # Connect to the server # Use the associated IO Loop that isn't running. io_loop.run_sync(ipc_subscriber.connect) # Wait for some data package = ipc_subscriber.read_sync() ''' def __singleton_init__(self, socket_path, io_loop=None): super(IPCMessageSubscriber, self).__singleton_init__( socket_path, io_loop=io_loop) self._read_sync_future = None self._read_stream_future = None self._sync_ioloop_running = False self.saved_data = [] self._sync_read_in_progress = Semaphore() self.callbacks = set() self.reading = False @tornado.gen.coroutine def _read_sync(self, timeout): yield self._sync_read_in_progress.acquire() exc_to_raise = None ret = None try: while True: if self._read_stream_future is None: self._read_stream_future = self.stream.read_bytes(4096, partial=True) if timeout is None: wire_bytes = yield self._read_stream_future else: future_with_timeout = FutureWithTimeout( self.io_loop, self._read_stream_future, timeout) wire_bytes = yield future_with_timeout self._read_stream_future = None # Remove the timeout once we get some data or an exception # occurs. We will assume that the rest of the data is already # there or is coming soon if an exception doesn't occur. timeout = None self.unpacker.feed(wire_bytes) first = True for framed_msg in self.unpacker: if first: ret = framed_msg['body'] first = False else: self.saved_data.append(framed_msg['body']) if not first: # We read at least one piece of data break except TornadoTimeoutError: # In the timeout case, just return None. # Keep 'self._read_stream_future' alive. ret = None except tornado.iostream.StreamClosedError as exc: log.trace('Subscriber disconnected from IPC %s', self.socket_path) self._read_stream_future = None exc_to_raise = exc except Exception as exc: log.error('Exception occurred in Subscriber while handling stream: %s', exc) self._read_stream_future = None exc_to_raise = exc if self._sync_ioloop_running: # Stop the IO Loop so that self.io_loop.start() will return in # read_sync(). self.io_loop.spawn_callback(self.io_loop.stop) if exc_to_raise is not None: raise exc_to_raise # pylint: disable=E0702 self._sync_read_in_progress.release() raise tornado.gen.Return(ret) def read_sync(self, timeout=None): ''' Read a message from an IPC socket The socket must already be connected. The associated IO Loop must NOT be running. :param int timeout: Timeout when receiving message :return: message data if successful. None if timed out. Will raise an exception for all other error conditions. ''' if self.saved_data: return self.saved_data.pop(0) self._sync_ioloop_running = True self._read_sync_future = self._read_sync(timeout) self.io_loop.start() self._sync_ioloop_running = False ret_future = self._read_sync_future self._read_sync_future = None return ret_future.result() @tornado.gen.coroutine def _read_async(self, callback): while not self.stream.closed(): try: self._read_stream_future = self.stream.read_bytes(4096, partial=True) self.reading = True wire_bytes = yield self._read_stream_future self._read_stream_future = None self.unpacker.feed(wire_bytes) for framed_msg in self.unpacker: body = framed_msg['body'] self.io_loop.spawn_callback(callback, body) except tornado.iostream.StreamClosedError: log.trace('Subscriber disconnected from IPC %s', self.socket_path) break except Exception as exc: log.error('Exception occurred while Subscriber handling stream: %s', exc) def __run_callbacks(self, raw): for callback in self.callbacks: self.io_loop.spawn_callback(callback, raw) @tornado.gen.coroutine def read_async(self): ''' Asynchronously read messages and invoke a callback when they are ready. :param callback: A callback with the received data ''' while not self.connected(): try: yield self.connect(timeout=5) except tornado.iostream.StreamClosedError: log.trace('Subscriber closed stream on IPC %s before connect', self.socket_path) yield tornado.gen.sleep(1) except Exception as exc: log.error('Exception occurred while Subscriber connecting: %s', exc) yield tornado.gen.sleep(1) yield self._read_async(self.__run_callbacks)
saltstack/salt
salt/modules/schedule.py
list_
python
def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}}
List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L75-L159
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
is_enabled
python
def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {}
List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L162-L179
null
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
purge
python
def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret
Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L182-L231
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n", "def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
build_schedule_item
python
def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name]
Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L286-L393
null
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
add
python
def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret
Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L396-L468
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n", "def build_schedule_item(name, **kwargs):\n '''\n Build a schedule job\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600\n '''\n\n ret = {'comment': [],\n 'result': True}\n\n if not name:\n ret['comment'] = 'Job name is required.'\n ret['result'] = False\n return ret\n\n schedule = {}\n schedule[name] = salt.utils.odict.OrderedDict()\n schedule[name]['function'] = kwargs['function']\n\n time_conflict = False\n for item in ['seconds', 'minutes', 'hours', 'days']:\n if item in kwargs and 'when' in kwargs:\n time_conflict = True\n\n if item in kwargs and 'cron' in kwargs:\n time_conflict = True\n\n if time_conflict:\n ret['result'] = False\n ret['comment'] = 'Unable to use \"seconds\", \"minutes\", \"hours\", or \"days\" with \"when\" or \"cron\" options.'\n return ret\n\n if 'when' in kwargs and 'cron' in kwargs:\n ret['result'] = False\n ret['comment'] = 'Unable to use \"when\" and \"cron\" options together. Ignoring.'\n return ret\n\n for item in ['seconds', 'minutes', 'hours', 'days']:\n if item in kwargs:\n schedule[name][item] = kwargs[item]\n\n if 'return_job' in kwargs:\n schedule[name]['return_job'] = kwargs['return_job']\n\n if 'metadata' in kwargs:\n schedule[name]['metadata'] = kwargs['metadata']\n\n if 'job_args' in kwargs:\n schedule[name]['args'] = kwargs['job_args']\n\n if 'job_kwargs' in kwargs:\n schedule[name]['kwargs'] = kwargs['job_kwargs']\n\n if 'maxrunning' in kwargs:\n schedule[name]['maxrunning'] = kwargs['maxrunning']\n else:\n schedule[name]['maxrunning'] = 1\n\n if 'name' in kwargs:\n schedule[name]['name'] = kwargs['name']\n else:\n schedule[name]['name'] = name\n\n if 'enabled' in kwargs:\n schedule[name]['enabled'] = kwargs['enabled']\n else:\n schedule[name]['enabled'] = True\n\n if 'jid_include' not in kwargs or kwargs['jid_include']:\n schedule[name]['jid_include'] = True\n\n if 'splay' in kwargs:\n if isinstance(kwargs['splay'], dict):\n # Ensure ordering of start and end arguments\n schedule[name]['splay'] = salt.utils.odict.OrderedDict()\n schedule[name]['splay']['start'] = kwargs['splay']['start']\n schedule[name]['splay']['end'] = kwargs['splay']['end']\n else:\n schedule[name]['splay'] = kwargs['splay']\n\n if 'when' in kwargs:\n if not _WHEN_SUPPORTED:\n ret['result'] = False\n ret['comment'] = 'Missing dateutil.parser, \"when\" is unavailable.'\n return ret\n else:\n validate_when = kwargs['when']\n if not isinstance(validate_when, list):\n validate_when = [validate_when]\n for _when in validate_when:\n try:\n dateutil_parser.parse(_when)\n except ValueError:\n ret['result'] = False\n ret['comment'] = 'Schedule item {0} for \"when\" in invalid.'.format(_when)\n return ret\n\n for item in ['range', 'when', 'once', 'once_fmt', 'cron',\n 'returner', 'after', 'return_config', 'return_kwargs',\n 'until', 'run_on_start', 'skip_during_range']:\n if item in kwargs:\n schedule[name][item] = kwargs[item]\n\n return schedule[name]\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
modify
python
def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret
Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L471-L556
[ "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n", "def build_schedule_item(name, **kwargs):\n '''\n Build a schedule job\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600\n '''\n\n ret = {'comment': [],\n 'result': True}\n\n if not name:\n ret['comment'] = 'Job name is required.'\n ret['result'] = False\n return ret\n\n schedule = {}\n schedule[name] = salt.utils.odict.OrderedDict()\n schedule[name]['function'] = kwargs['function']\n\n time_conflict = False\n for item in ['seconds', 'minutes', 'hours', 'days']:\n if item in kwargs and 'when' in kwargs:\n time_conflict = True\n\n if item in kwargs and 'cron' in kwargs:\n time_conflict = True\n\n if time_conflict:\n ret['result'] = False\n ret['comment'] = 'Unable to use \"seconds\", \"minutes\", \"hours\", or \"days\" with \"when\" or \"cron\" options.'\n return ret\n\n if 'when' in kwargs and 'cron' in kwargs:\n ret['result'] = False\n ret['comment'] = 'Unable to use \"when\" and \"cron\" options together. Ignoring.'\n return ret\n\n for item in ['seconds', 'minutes', 'hours', 'days']:\n if item in kwargs:\n schedule[name][item] = kwargs[item]\n\n if 'return_job' in kwargs:\n schedule[name]['return_job'] = kwargs['return_job']\n\n if 'metadata' in kwargs:\n schedule[name]['metadata'] = kwargs['metadata']\n\n if 'job_args' in kwargs:\n schedule[name]['args'] = kwargs['job_args']\n\n if 'job_kwargs' in kwargs:\n schedule[name]['kwargs'] = kwargs['job_kwargs']\n\n if 'maxrunning' in kwargs:\n schedule[name]['maxrunning'] = kwargs['maxrunning']\n else:\n schedule[name]['maxrunning'] = 1\n\n if 'name' in kwargs:\n schedule[name]['name'] = kwargs['name']\n else:\n schedule[name]['name'] = name\n\n if 'enabled' in kwargs:\n schedule[name]['enabled'] = kwargs['enabled']\n else:\n schedule[name]['enabled'] = True\n\n if 'jid_include' not in kwargs or kwargs['jid_include']:\n schedule[name]['jid_include'] = True\n\n if 'splay' in kwargs:\n if isinstance(kwargs['splay'], dict):\n # Ensure ordering of start and end arguments\n schedule[name]['splay'] = salt.utils.odict.OrderedDict()\n schedule[name]['splay']['start'] = kwargs['splay']['start']\n schedule[name]['splay']['end'] = kwargs['splay']['end']\n else:\n schedule[name]['splay'] = kwargs['splay']\n\n if 'when' in kwargs:\n if not _WHEN_SUPPORTED:\n ret['result'] = False\n ret['comment'] = 'Missing dateutil.parser, \"when\" is unavailable.'\n return ret\n else:\n validate_when = kwargs['when']\n if not isinstance(validate_when, list):\n validate_when = [validate_when]\n for _when in validate_when:\n try:\n dateutil_parser.parse(_when)\n except ValueError:\n ret['result'] = False\n ret['comment'] = 'Schedule item {0} for \"when\" in invalid.'.format(_when)\n return ret\n\n for item in ['range', 'when', 'once', 'once_fmt', 'cron',\n 'returner', 'after', 'return_config', 'return_kwargs',\n 'until', 'run_on_start', 'skip_during_range']:\n if item in kwargs:\n schedule[name][item] = kwargs[item]\n\n return schedule[name]\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
run_job
python
def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret
Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L559-L595
[ "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
enable_job
python
def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret
Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L598-L650
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n", "def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
save
python
def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret
Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L708-L739
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
reload_
python
def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret
Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L816-L862
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n", "def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
move
python
def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret
Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L865-L928
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def delete(name, **kwargs):\n '''\n Delete a job from the minion's schedule\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.delete job1\n '''\n\n ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name),\n 'result': False}\n\n if not name:\n ret['comment'] = 'Job name is required.'\n\n if 'test' in kwargs and kwargs['test']:\n ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name)\n ret['result'] = True\n else:\n persist = True\n if 'persist' in kwargs:\n persist = kwargs['persist']\n\n if name in list_(show_all=True, where='opts', return_yaml=False):\n event_data = {'name': name, 'func': 'delete', 'persist': persist}\n elif name in list_(show_all=True, where='pillar', return_yaml=False):\n event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False}\n else:\n ret['comment'] = 'Job {0} does not exist.'.format(name)\n return ret\n\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire'](event_data, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n if name not in schedule:\n ret['result'] = True\n ret['comment'] = 'Deleted Job {0} from schedule.'.format(name)\n else:\n ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name)\n return ret\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret['comment'] = 'Event module not available. Schedule add failed.'\n return ret\n", "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/modules/schedule.py
postpone_job
python
def postpone_job(name, current_time, new_time, **kwargs): ''' Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S' ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret if not current_time: ret['comment'] = 'Job current time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if not new_time: ret['comment'] = 'Job new_time is required.' ret['result'] = False return ret else: try: # Validate date string datetime.datetime.strptime(new_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', new_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be postponed in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'func': 'postpone_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'new_time': new_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'postpone_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_postpone_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Postponed Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to postpone job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule postpone job failed.' return ret
Postpone a job in the minion's schedule Current time and new time should be in date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.postpone_job job current_time new_time salt '*' schedule.postpone_job job current_time new_time time_fmt='%Y-%m-%dT%H:%M:%S'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/schedule.py#L994-L1096
[ "def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n", "def list_(show_all=False,\n show_disabled=True,\n where=None,\n return_yaml=True):\n '''\n List the jobs currently scheduled on the minion\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' schedule.list\n\n # Show all jobs including hidden internal jobs\n salt '*' schedule.list show_all=True\n\n # Hide disabled jobs from list of jobs\n salt '*' schedule.list show_disabled=False\n\n '''\n\n schedule = {}\n try:\n eventer = salt.utils.event.get_event('minion', opts=__opts__)\n res = __salt__['event.fire']({'func': 'list',\n 'where': where}, 'manage_schedule')\n if res:\n event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30)\n if event_ret and event_ret['complete']:\n schedule = event_ret['schedule']\n except KeyError:\n # Effectively a no-op, since we can't really return without an event system\n ret = {}\n ret['comment'] = 'Event module not available. Schedule list failed.'\n ret['result'] = True\n log.debug('Event module not available. Schedule list failed.')\n return ret\n\n _hidden = ['enabled',\n 'skip_function',\n 'skip_during_range']\n for job in list(schedule.keys()): # iterate over a copy since we will mutate it\n if job in _hidden:\n continue\n\n # Default jobs added by salt begin with __\n # by default hide them unless show_all is True.\n if job.startswith('__') and not show_all:\n del schedule[job]\n continue\n\n # if enabled is not included in the job,\n # assume job is enabled.\n if 'enabled' not in schedule[job]:\n schedule[job]['enabled'] = True\n\n for item in pycopy.copy(schedule[job]):\n if item not in SCHEDULE_CONF:\n del schedule[job][item]\n continue\n if schedule[job][item] is None:\n del schedule[job][item]\n continue\n if schedule[job][item] == 'true':\n schedule[job][item] = True\n if schedule[job][item] == 'false':\n schedule[job][item] = False\n\n # if the job is disabled and show_disabled is False, skip job\n if not show_disabled and not schedule[job]['enabled']:\n del schedule[job]\n continue\n\n if '_seconds' in schedule[job]:\n # remove _seconds from the listing\n del schedule[job]['_seconds']\n\n if schedule:\n if return_yaml:\n tmp = {'schedule': schedule}\n return salt.utils.yaml.safe_dump(tmp, default_flow_style=False)\n else:\n return schedule\n else:\n return {'schedule': {}}\n", "def get_event(self,\n wait=5,\n tag='',\n full=False,\n match_type=None,\n no_block=False,\n auto_reconnect=False):\n '''\n Get a single publication.\n If no publication is available, then block for up to ``wait`` seconds.\n Return publication if it is available or ``None`` if no publication is\n available.\n\n If wait is 0, then block forever.\n\n tag\n Only return events matching the given tag. If not specified, or set\n to an empty string, all events are returned. It is recommended to\n always be selective on what is to be returned in the event that\n multiple requests are being multiplexed.\n\n match_type\n Set the function to match the search tag with event tags.\n - 'startswith' : search for event tags that start with tag\n - 'endswith' : search for event tags that end with tag\n - 'find' : search for event tags that contain tag\n - 'regex' : regex search '^' + tag event tags\n - 'fnmatch' : fnmatch tag event tags matching\n Default is opts['event_match_type'] or 'startswith'\n\n .. versionadded:: 2015.8.0\n\n no_block\n Define if getting the event should be a blocking call or not.\n Defaults to False to keep backwards compatibility.\n\n .. versionadded:: 2015.8.0\n\n Notes:\n\n Searches cached publications first. If no cached publications are found\n that match the given tag specification, new publications are received\n and checked.\n\n If a publication is received that does not match the tag specification,\n it is DISCARDED unless it is subscribed to via subscribe() which will\n cause it to be cached.\n\n If a caller is not going to call get_event immediately after sending a\n request, it MUST subscribe the result to ensure the response is not lost\n should other regions of code call get_event for other purposes.\n '''\n assert self._run_io_loop_sync\n\n match_func = self._get_match_func(match_type)\n\n ret = self._check_pending(tag, match_func)\n if ret is None:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n if auto_reconnect:\n raise_errors = self.raise_errors\n self.raise_errors = True\n while True:\n try:\n ret = self._get_event(wait, tag, match_func, no_block)\n break\n except tornado.iostream.StreamClosedError:\n self.close_pub()\n self.connect_pub(timeout=wait)\n continue\n self.raise_errors = raise_errors\n else:\n ret = self._get_event(wait, tag, match_func, no_block)\n\n if ret is None or full:\n return ret\n else:\n return ret['data']\n" ]
# -*- coding: utf-8 -*- ''' Module for managing the Salt schedule on a minion .. versionadded:: 2014.7.0 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import copy as pycopy import datetime import difflib import logging import os try: import dateutil.parser as dateutil_parser _WHEN_SUPPORTED = True _RANGE_SUPPORTED = True except ImportError: _WHEN_SUPPORTED = False _RANGE_SUPPORTED = False # Import salt libs import salt.utils.event import salt.utils.files import salt.utils.odict import salt.utils.yaml # Import 3rd-party libs from salt.ext import six __proxyenabled__ = ['*'] log = logging.getLogger(__name__) __func_alias__ = { 'list_': 'list', 'reload_': 'reload' } SCHEDULE_CONF = [ 'name', 'maxrunning', 'function', 'splay', 'range', 'when', 'once', 'once_fmt', 'returner', 'jid_include', 'args', 'kwargs', '_seconds', 'seconds', 'minutes', 'hours', 'days', 'enabled', 'return_job', 'metadata', 'cron', 'until', 'after', 'return_config', 'return_kwargs', 'run_on_start', 'skip_during_range', 'run_after_skip_range', ] def list_(show_all=False, show_disabled=True, where=None, return_yaml=True): ''' List the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.list # Show all jobs including hidden internal jobs salt '*' schedule.list show_all=True # Hide disabled jobs from list of jobs salt '*' schedule.list show_disabled=False ''' schedule = {} try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'list', 'where': where}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_list_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule list failed.' ret['result'] = True log.debug('Event module not available. Schedule list failed.') return ret _hidden = ['enabled', 'skip_function', 'skip_during_range'] for job in list(schedule.keys()): # iterate over a copy since we will mutate it if job in _hidden: continue # Default jobs added by salt begin with __ # by default hide them unless show_all is True. if job.startswith('__') and not show_all: del schedule[job] continue # if enabled is not included in the job, # assume job is enabled. if 'enabled' not in schedule[job]: schedule[job]['enabled'] = True for item in pycopy.copy(schedule[job]): if item not in SCHEDULE_CONF: del schedule[job][item] continue if schedule[job][item] is None: del schedule[job][item] continue if schedule[job][item] == 'true': schedule[job][item] = True if schedule[job][item] == 'false': schedule[job][item] = False # if the job is disabled and show_disabled is False, skip job if not show_disabled and not schedule[job]['enabled']: del schedule[job] continue if '_seconds' in schedule[job]: # remove _seconds from the listing del schedule[job]['_seconds'] if schedule: if return_yaml: tmp = {'schedule': schedule} return salt.utils.yaml.safe_dump(tmp, default_flow_style=False) else: return schedule else: return {'schedule': {}} def is_enabled(name): ''' List a Job only if its enabled .. versionadded:: 2015.5.3 CLI Example: .. code-block:: bash salt '*' schedule.is_enabled name=job_name ''' current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False) if name in current_schedule: return current_schedule[name] else: return {} def purge(**kwargs): ''' Purge all the jobs currently scheduled on the minion CLI Example: .. code-block:: bash salt '*' schedule.purge ''' ret = {'comment': [], 'result': True} for name in list_(show_all=True, return_yaml=False): if name == 'enabled': continue if name.startswith('__'): continue if 'test' in kwargs and kwargs['test']: ret['result'] = True ret['comment'].append('Job: {0} would be deleted from schedule.'.format(name)) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'func': 'delete', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: _schedule_ret = event_ret['schedule'] if name not in _schedule_ret: ret['result'] = True ret['comment'].append('Deleted job: {0} from schedule.'.format(name)) else: ret['comment'].append('Failed to delete job {0} from schedule.'.format(name)) ret['result'] = True except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' ret['result'] = True return ret def delete(name, **kwargs): ''' Delete a job from the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.delete job1 ''' ret = {'comment': 'Failed to delete job {0} from schedule.'.format(name), 'result': False} if not name: ret['comment'] = 'Job name is required.' if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be deleted from schedule.'.format(name) ret['result'] = True else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'delete', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'delete', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_delete_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name not in schedule: ret['result'] = True ret['comment'] = 'Deleted Job {0} from schedule.'.format(name) else: ret['comment'] = 'Failed to delete job {0} from schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def build_schedule_item(name, **kwargs): ''' Build a schedule job CLI Example: .. code-block:: bash salt '*' schedule.build_schedule_item job1 function='test.ping' seconds=3600 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() schedule[name]['function'] = kwargs['function'] time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: schedule[name][item] = kwargs[item] if 'return_job' in kwargs: schedule[name]['return_job'] = kwargs['return_job'] if 'metadata' in kwargs: schedule[name]['metadata'] = kwargs['metadata'] if 'job_args' in kwargs: schedule[name]['args'] = kwargs['job_args'] if 'job_kwargs' in kwargs: schedule[name]['kwargs'] = kwargs['job_kwargs'] if 'maxrunning' in kwargs: schedule[name]['maxrunning'] = kwargs['maxrunning'] else: schedule[name]['maxrunning'] = 1 if 'name' in kwargs: schedule[name]['name'] = kwargs['name'] else: schedule[name]['name'] = name if 'enabled' in kwargs: schedule[name]['enabled'] = kwargs['enabled'] else: schedule[name]['enabled'] = True if 'jid_include' not in kwargs or kwargs['jid_include']: schedule[name]['jid_include'] = True if 'splay' in kwargs: if isinstance(kwargs['splay'], dict): # Ensure ordering of start and end arguments schedule[name]['splay'] = salt.utils.odict.OrderedDict() schedule[name]['splay']['start'] = kwargs['splay']['start'] schedule[name]['splay']['end'] = kwargs['splay']['end'] else: schedule[name]['splay'] = kwargs['splay'] if 'when' in kwargs: if not _WHEN_SUPPORTED: ret['result'] = False ret['comment'] = 'Missing dateutil.parser, "when" is unavailable.' return ret else: validate_when = kwargs['when'] if not isinstance(validate_when, list): validate_when = [validate_when] for _when in validate_when: try: dateutil_parser.parse(_when) except ValueError: ret['result'] = False ret['comment'] = 'Schedule item {0} for "when" in invalid.'.format(_when) return ret for item in ['range', 'when', 'once', 'once_fmt', 'cron', 'returner', 'after', 'return_config', 'return_kwargs', 'until', 'run_on_start', 'skip_during_range']: if item in kwargs: schedule[name][item] = kwargs[item] return schedule[name] def add(name, **kwargs): ''' Add a job to the schedule CLI Example: .. code-block:: bash salt '*' schedule.add job1 function='test.ping' seconds=3600 # If function have some arguments, use job_args salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log']" seconds=60 ''' ret = {'comment': 'Failed to add job {0} to schedule.'.format(name), 'result': False} if name in list_(show_all=True, return_yaml=False): ret['comment'] = 'Job {0} already exists in schedule.'.format(name) ret['result'] = False return ret if not name: ret['comment'] = 'Job name is required.' ret['result'] = False time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" or "cron" options.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret persist = True if 'persist' in kwargs: persist = kwargs['persist'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new schedule_data = {} schedule_data[name] = _new if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be added to schedule.'.format(name) ret['result'] = True else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'name': name, 'schedule': schedule_data, 'func': 'add', 'persist': persist}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_add_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if name in schedule: ret['result'] = True ret['comment'] = 'Added job: {0} to schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule add failed.' return ret def modify(name, **kwargs): ''' Modify an existing job in the schedule CLI Example: .. code-block:: bash salt '*' schedule.modify job1 function='test.ping' seconds=3600 ''' ret = {'comment': '', 'changes': {}, 'result': True} time_conflict = False for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs and 'when' in kwargs: time_conflict = True if item in kwargs and 'cron' in kwargs: time_conflict = True if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' return ret if 'when' in kwargs and 'cron' in kwargs: ret['result'] = False ret['comment'] = 'Unable to use "when" and "cron" options together. Ignoring.' return ret current_schedule = list_(show_all=True, return_yaml=False) if name not in current_schedule: ret['comment'] = 'Job {0} does not exist in schedule.'.format(name) ret['result'] = False return ret _current = current_schedule[name] if '_seconds' in _current: _current['seconds'] = _current['_seconds'] del _current['_seconds'] _new = build_schedule_item(name, **kwargs) if 'result' in _new and not _new['result']: return _new if _new == _current: ret['comment'] = 'Job {0} in correct state'.format(name) return ret _current_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_current.items())] _new_lines = ['{0}:{1}\n'.format(key, value) for (key, value) in sorted(_new.items())] _diff = difflib.unified_diff(_current_lines, _new_lines) ret['changes']['diff'] = ''.join(_diff) if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be modified in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'func': 'modify', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'schedule': _new, 'where': 'pillar', 'func': 'modify', 'persist': False} out = __salt__['event.fire'](event_data, 'manage_schedule') if out: ret['comment'] = 'Modified job: {0} in schedule.'.format(name) else: ret['comment'] = 'Failed to modify job {0} in schedule.'.format(name) ret['result'] = False return ret def run_job(name, force=False): ''' Run a scheduled job on the minion immediately CLI Example: .. code-block:: bash salt '*' schedule.run_job job1 salt '*' schedule.run_job job1 force=True Force the job to run even if it is disabled. ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False schedule = list_(show_all=True, return_yaml=False) if name in schedule: data = schedule[name] if 'enabled' in data and not data['enabled'] and not force: ret['comment'] = 'Job {0} is disabled.'.format(name) else: out = __salt__['event.fire']({'name': name, 'func': 'run_job'}, 'manage_schedule') if out: ret['comment'] = 'Scheduling Job {0} on minion.'.format(name) else: ret['comment'] = 'Failed to run job {0} on minion.'.format(name) ret['result'] = False else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret def enable_job(name, **kwargs): ''' Enable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.enable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'enable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Enabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable_job(name, **kwargs): ''' Disable a job in the minion's schedule CLI Example: .. code-block:: bash salt '*' schedule.disable_job job1 ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be disabled in schedule.'.format(name) else: persist = True if 'persist' in kwargs: persist = kwargs['persist'] if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'func': 'disable_job', 'persist': persist} elif name in list_(show_all=True, where='pillar'): event_data = {'name': name, 'where': 'pillar', 'func': 'disable_job', 'persist': False} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and not schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Disabled Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to disable job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def save(**kwargs): ''' Save all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.save ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be saved.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'save_schedule'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_saved', wait=30) if event_ret and event_ret['complete']: ret['result'] = True ret['comment'] = 'Schedule (non-pillar items) saved.' else: ret['result'] = False ret['comment'] = 'Failed to save schedule.' except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule save failed.' return ret def enable(**kwargs): ''' Enable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.enable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be enabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'enable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and schedule['enabled']: ret['result'] = True ret['comment'] = 'Enabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to enable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule enable job failed.' return ret def disable(**kwargs): ''' Disable all scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.disable ''' ret = {'comment': [], 'result': True} if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Schedule would be disabled.' else: try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire']({'func': 'disable'}, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_disabled_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] if 'enabled' in schedule and not schedule['enabled']: ret['result'] = True ret['comment'] = 'Disabled schedule on minion.' else: ret['result'] = False ret['comment'] = 'Failed to disable schedule on minion.' return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule disable job failed.' return ret def reload_(): ''' Reload saved scheduled jobs on the minion CLI Example: .. code-block:: bash salt '*' schedule.reload ''' ret = {'comment': [], 'result': True} # If there a schedule defined in pillar, refresh it. if 'schedule' in __pillar__: out = __salt__['event.fire']({}, 'pillar_refresh') if out: ret['comment'].append('Reloaded schedule from pillar on minion.') else: ret['comment'].append('Failed to reload schedule from pillar on minion.') ret['result'] = False # move this file into an configurable opt sfn = '{0}/{1}/schedule.conf'.format(__opts__['config_dir'], os.path.dirname(__opts__['default_include'])) if os.path.isfile(sfn): with salt.utils.files.fopen(sfn, 'rb') as fp_: try: schedule = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: ret['comment'].append('Unable to read existing schedule file: {0}'.format(exc)) if schedule: if 'schedule' in schedule and schedule['schedule']: out = __salt__['event.fire']({'func': 'reload', 'schedule': schedule}, 'manage_schedule') if out: ret['comment'].append('Reloaded schedule on minion from schedule.conf.') else: ret['comment'].append('Failed to reload schedule on minion from schedule.conf.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False else: ret['comment'].append('Failed to reload schedule on minion. Saved file is empty or invalid.') ret['result'] = False return ret def move(name, target, **kwargs): ''' Move scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.move jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be moved from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] where = None elif name in pillar_schedule: schedule_data = pillar_schedule[name] where = 'pillar' else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: delete(name, where=where) ret['result'] = True ret['comment'] = 'Moved Job {0} from schedule.'.format(name) ret['minions'] = minions return ret return ret def copy(name, target, **kwargs): ''' Copy scheduled job to another minion or minions. CLI Example: .. code-block:: bash salt '*' schedule.copy jobname target ''' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if 'test' in kwargs and kwargs['test']: ret['comment'] = 'Job: {0} would be copied from schedule.'.format(name) else: opts_schedule = list_(show_all=True, where='opts', return_yaml=False) pillar_schedule = list_(show_all=True, where='pillar', return_yaml=False) if name in opts_schedule: schedule_data = opts_schedule[name] elif name in pillar_schedule: schedule_data = pillar_schedule[name] else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret schedule_opts = [] for key, value in six.iteritems(schedule_data): temp = '{0}={1}'.format(key, value) schedule_opts.append(temp) response = __salt__['publish.publish'](target, 'schedule.add', schedule_opts) # Get errors and list of affeced minions errors = [] minions = [] for minion in response: minions.append(minion) if not response[minion]: errors.append(minion) # parse response if not response: ret['comment'] = 'no servers answered the published schedule.add command' return ret elif errors: ret['comment'] = 'the following minions return False' ret['minions'] = errors return ret else: ret['result'] = True ret['comment'] = 'Copied Job {0} from schedule to minion(s).'.format(name) ret['minions'] = minions return ret return ret def skip_job(name, current_time, **kwargs): ''' Skip a job in the minion's schedule at specified time. Time to skip should be specified as date string format, default value is %Y-%m-%dT%H:%M:%S. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.skip_job job time ''' time_fmt = kwargs.get('time_fmt') or '%Y-%m-%dT%H:%M:%S' ret = {'comment': [], 'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False if not current_time: ret['comment'] = 'Job time is required.' ret['result'] = False else: # Validate date string try: datetime.datetime.strptime(current_time, time_fmt) except (TypeError, ValueError): log.error('Date string could not be parsed: %s, %s', current_time, time_fmt) ret['comment'] = 'Date string could not be parsed.' ret['result'] = False return ret if 'test' in __opts__ and __opts__['test']: ret['comment'] = 'Job: {0} would be skipped in schedule.'.format(name) else: if name in list_(show_all=True, where='opts', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'func': 'skip_job'} elif name in list_(show_all=True, where='pillar', return_yaml=False): event_data = {'name': name, 'time': current_time, 'time_fmt': time_fmt, 'where': 'pillar', 'func': 'skip_job'} else: ret['comment'] = 'Job {0} does not exist.'.format(name) ret['result'] = False return ret try: eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_skip_job_complete', wait=30) if event_ret and event_ret['complete']: schedule = event_ret['schedule'] # check item exists in schedule and is enabled if name in schedule and schedule[name]['enabled']: ret['result'] = True ret['comment'] = 'Added Skip Job {0} in schedule.'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to skip job {0} in schedule.'.format(name) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system ret['comment'] = 'Event module not available. Schedule skip job failed.' return ret def show_next_fire_time(name, **kwargs): ''' Show the next fire time for scheduled job .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' schedule.show_next_fire_time job_name ''' ret = {'result': True} if not name: ret['comment'] = 'Job name is required.' ret['result'] = False try: event_data = {'name': name, 'func': 'get_next_fire_time'} eventer = salt.utils.event.get_event('minion', opts=__opts__) res = __salt__['event.fire'](event_data, 'manage_schedule') if res: event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_next_fire_time_complete', wait=30) except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} ret['comment'] = 'Event module not available. Schedule show next fire time failed.' ret['result'] = True return ret if 'next_fire_time' in event_ret: ret['next_fire_time'] = event_ret['next_fire_time'] else: ret['comment'] = 'next fire time not available.' return ret
saltstack/salt
salt/utils/platform.py
is_proxy
python
def is_proxy(): ''' Return True if this minion is a proxy minion. Leverages the fact that is_linux() and is_windows both return False for proxies. TODO: Need to extend this for proxies that might run on other Unices ''' import __main__ as main # This is a hack. If a proxy minion is started by other # means, e.g. a custom script that creates the minion objects # then this will fail. ret = False try: # Changed this from 'salt-proxy in main...' to 'proxy in main...' # to support the testsuite's temp script that is called 'cli_salt_proxy' # # Add '--proxyid' in sys.argv so that salt-call --proxyid # is seen as a proxy minion if 'proxy' in main.__file__ or '--proxyid' in sys.argv: ret = True except AttributeError: pass return ret
Return True if this minion is a proxy minion. Leverages the fact that is_linux() and is_windows both return False for proxies. TODO: Need to extend this for proxies that might run on other Unices
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/platform.py#L24-L47
null
# -*- coding: utf-8 -*- ''' Functions for identifying which platform a machine is ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import os import subprocess import sys # Import Salt libs from salt.utils.decorators import memoize as real_memoize @real_memoize def is_windows(): ''' Simple function to return if a host is Windows or not ''' return sys.platform.startswith('win') @real_memoize @real_memoize def is_linux(): ''' Simple function to return if a host is Linux or not. Note for a proxy minion, we need to return something else ''' return sys.platform.startswith('linux') @real_memoize def is_darwin(): ''' Simple function to return if a host is Darwin (macOS) or not ''' return sys.platform.startswith('darwin') @real_memoize def is_sunos(): ''' Simple function to return if host is SunOS or not ''' return sys.platform.startswith('sunos') @real_memoize def is_smartos(): ''' Simple function to return if host is SmartOS (Illumos) or not ''' if not is_sunos(): return False else: return os.uname()[3].startswith('joyent_') @real_memoize def is_smartos_globalzone(): ''' Function to return if host is SmartOS (Illumos) global zone or not ''' if not is_smartos(): return False else: cmd = ['zonename'] try: zonename = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: return False if zonename.returncode: return False if zonename.stdout.read().strip() == 'global': return True return False @real_memoize def is_smartos_zone(): ''' Function to return if host is SmartOS (Illumos) and not the gz ''' if not is_smartos(): return False else: cmd = ['zonename'] try: zonename = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: return False if zonename.returncode: return False if zonename.stdout.read().strip() == 'global': return False return True @real_memoize def is_freebsd(): ''' Simple function to return if host is FreeBSD or not ''' return sys.platform.startswith('freebsd') @real_memoize def is_netbsd(): ''' Simple function to return if host is NetBSD or not ''' return sys.platform.startswith('netbsd') @real_memoize def is_openbsd(): ''' Simple function to return if host is OpenBSD or not ''' return sys.platform.startswith('openbsd') @real_memoize def is_aix(): ''' Simple function to return if host is AIX or not ''' return sys.platform.startswith('aix')
saltstack/salt
salt/utils/platform.py
is_smartos_globalzone
python
def is_smartos_globalzone(): ''' Function to return if host is SmartOS (Illumos) global zone or not ''' if not is_smartos(): return False else: cmd = ['zonename'] try: zonename = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: return False if zonename.returncode: return False if zonename.stdout.read().strip() == 'global': return True return False
Function to return if host is SmartOS (Illumos) global zone or not
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/platform.py#L87-L106
null
# -*- coding: utf-8 -*- ''' Functions for identifying which platform a machine is ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import os import subprocess import sys # Import Salt libs from salt.utils.decorators import memoize as real_memoize @real_memoize def is_windows(): ''' Simple function to return if a host is Windows or not ''' return sys.platform.startswith('win') @real_memoize def is_proxy(): ''' Return True if this minion is a proxy minion. Leverages the fact that is_linux() and is_windows both return False for proxies. TODO: Need to extend this for proxies that might run on other Unices ''' import __main__ as main # This is a hack. If a proxy minion is started by other # means, e.g. a custom script that creates the minion objects # then this will fail. ret = False try: # Changed this from 'salt-proxy in main...' to 'proxy in main...' # to support the testsuite's temp script that is called 'cli_salt_proxy' # # Add '--proxyid' in sys.argv so that salt-call --proxyid # is seen as a proxy minion if 'proxy' in main.__file__ or '--proxyid' in sys.argv: ret = True except AttributeError: pass return ret @real_memoize def is_linux(): ''' Simple function to return if a host is Linux or not. Note for a proxy minion, we need to return something else ''' return sys.platform.startswith('linux') @real_memoize def is_darwin(): ''' Simple function to return if a host is Darwin (macOS) or not ''' return sys.platform.startswith('darwin') @real_memoize def is_sunos(): ''' Simple function to return if host is SunOS or not ''' return sys.platform.startswith('sunos') @real_memoize def is_smartos(): ''' Simple function to return if host is SmartOS (Illumos) or not ''' if not is_sunos(): return False else: return os.uname()[3].startswith('joyent_') @real_memoize @real_memoize def is_smartos_zone(): ''' Function to return if host is SmartOS (Illumos) and not the gz ''' if not is_smartos(): return False else: cmd = ['zonename'] try: zonename = subprocess.Popen( cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError: return False if zonename.returncode: return False if zonename.stdout.read().strip() == 'global': return False return True @real_memoize def is_freebsd(): ''' Simple function to return if host is FreeBSD or not ''' return sys.platform.startswith('freebsd') @real_memoize def is_netbsd(): ''' Simple function to return if host is NetBSD or not ''' return sys.platform.startswith('netbsd') @real_memoize def is_openbsd(): ''' Simple function to return if host is OpenBSD or not ''' return sys.platform.startswith('openbsd') @real_memoize def is_aix(): ''' Simple function to return if host is AIX or not ''' return sys.platform.startswith('aix')
saltstack/salt
salt/modules/genesis.py
bootstrap
python
def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir)
Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L51-L224
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _mkpart(root, fs_format, fs_opts, mount_dir):\n '''\n Make a partition, and make it bootable\n\n .. versionadded:: Beryllium\n '''\n __salt__['partition.mklabel'](root, 'msdos')\n loop1 = __salt__['cmd.run']('losetup -f')\n log.debug('First loop device is %s', loop1)\n __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root))\n part_info = __salt__['partition.list'](loop1)\n start = six.text_type(2048 * 2048) + 'B'\n end = part_info['info']['size']\n __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end)\n __salt__['partition.set'](loop1, '1', 'boot', 'on')\n part_info = __salt__['partition.list'](loop1)\n loop2 = __salt__['cmd.run']('losetup -f')\n log.debug('Second loop device is %s', loop2)\n start = start.rstrip('B')\n __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1))\n _mkfs(loop2, fs_format, fs_opts)\n __salt__['mount.mount'](mount_dir, loop2)\n __salt__['cmd.run']((\n 'grub-install',\n '--target=i386-pc',\n '--debug',\n '--no-floppy',\n '--modules=part_msdos linux',\n '--boot-directory={0}/boot'.format(mount_dir),\n loop1\n ), python_shell=False)\n __salt__['mount.umount'](mount_dir)\n __salt__['cmd.run']('losetup -d {0}'.format(loop2))\n __salt__['cmd.run']('losetup -d {0}'.format(loop1))\n return part_info\n", "def _populate_cache(platform, pkg_cache, mount_dir):\n '''\n If a ``pkg_cache`` directory is specified, then use it to populate the\n disk image.\n '''\n if not pkg_cache:\n return\n if not os.path.isdir(pkg_cache):\n return\n\n if platform == 'pacman':\n cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir)\n\n __salt__['file.mkdir'](cache_dir, 'root', 'root', '755')\n __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True)\n", "def _bootstrap_yum(\n root,\n pkg_confs='/etc/yum*',\n pkgs=None,\n exclude_pkgs=None,\n epel_url=EPEL_URL,\n ):\n '''\n Bootstrap an image using the yum tools\n\n root\n The root of the image to install to. Will be created as a directory if\n it does not exist. (e.x.: /root/arch)\n\n pkg_confs\n The location of the conf files to copy into the image, to point yum\n to the right repos and configuration.\n\n pkgs\n A list of packages to be installed on this image. For RedHat, this\n will include ``yum``, ``centos-release`` and ``iputils`` by default.\n\n exclude_pkgs\n A list of packages to be excluded. If you do not want to install the\n defaults, you need to include them in this list.\n\n epel_url\n The URL to download the EPEL release package from.\n\n TODO: Set up a pre-install overlay, to copy files into /etc/ and so on,\n which are required for the install to work.\n '''\n if pkgs is None:\n pkgs = []\n elif isinstance(pkgs, six.string_types):\n pkgs = pkgs.split(',')\n\n default_pkgs = ('yum', 'centos-release', 'iputils')\n for pkg in default_pkgs:\n if pkg not in pkgs:\n pkgs.append(pkg)\n\n if exclude_pkgs is None:\n exclude_pkgs = []\n elif isinstance(exclude_pkgs, six.string_types):\n exclude_pkgs = exclude_pkgs.split(',')\n\n for pkg in exclude_pkgs:\n pkgs.remove(pkg)\n\n _make_nodes(root)\n release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')]\n __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files)))\n __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files)))\n __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs)))\n\n yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs\n __salt__['cmd.run'](yum_args, python_shell=False)\n\n if 'epel-release' not in exclude_pkgs:\n __salt__['cmd.run'](\n ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url),\n python_shell=False\n )\n", "def _bootstrap_deb(\n root,\n arch,\n flavor,\n repo_url=None,\n static_qemu=None,\n pkgs=None,\n exclude_pkgs=None,\n ):\n '''\n Bootstrap an image using the Debian tools\n\n root\n The root of the image to install to. Will be created as a directory if\n it does not exist. (e.x.: /root/wheezy)\n\n arch\n Architecture of the target image. (e.x.: amd64)\n\n flavor\n Flavor of Debian to install. (e.x.: wheezy)\n\n repo_url\n Base URL for the mirror to install from.\n (e.x.: http://ftp.debian.org/debian/)\n\n static_qemu\n Local path to the static qemu binary required for this arch.\n (e.x.: /usr/bin/qemu-amd64-static)\n\n pkgs\n A list of packages to be installed on this image.\n\n exclude_pkgs\n A list of packages to be excluded.\n '''\n\n if repo_url is None:\n repo_url = 'http://ftp.debian.org/debian/'\n\n if not salt.utils.path.which('debootstrap'):\n log.error('Required tool debootstrap is not installed.')\n return False\n\n if static_qemu and not salt.utils.validate.path.is_executable(static_qemu):\n log.error('Required tool qemu not present/readable at: %s', static_qemu)\n return False\n\n if isinstance(pkgs, (list, tuple)):\n pkgs = ','.join(pkgs)\n if isinstance(exclude_pkgs, (list, tuple)):\n exclude_pkgs = ','.join(exclude_pkgs)\n\n deb_args = [\n 'debootstrap',\n '--foreign',\n '--arch',\n _cmd_quote(arch)]\n\n if pkgs:\n deb_args += ['--include', _cmd_quote(pkgs)]\n if exclude_pkgs:\n deb_args += ['--exclude', _cmd_quote(exclude_pkgs)]\n\n deb_args += [\n _cmd_quote(flavor),\n _cmd_quote(root),\n _cmd_quote(repo_url),\n ]\n\n __salt__['cmd.run'](deb_args, python_shell=False)\n\n if static_qemu:\n __salt__['cmd.run'](\n 'cp {qemu} {root}/usr/bin/'.format(\n qemu=_cmd_quote(static_qemu), root=_cmd_quote(root)\n )\n )\n\n env = {'DEBIAN_FRONTEND': 'noninteractive',\n 'DEBCONF_NONINTERACTIVE_SEEN': 'true',\n 'LC_ALL': 'C',\n 'LANGUAGE': 'C',\n 'LANG': 'C',\n 'PATH': '/sbin:/bin:/usr/bin'}\n __salt__['cmd.run'](\n 'chroot {root} /debootstrap/debootstrap --second-stage'.format(\n root=_cmd_quote(root)\n ),\n env=env\n )\n __salt__['cmd.run'](\n 'chroot {root} dpkg --configure -a'.format(\n root=_cmd_quote(root)\n ),\n env=env\n )\n", "def _bootstrap_pacman(\n root,\n pkg_confs='/etc/pacman*',\n img_format='dir',\n pkgs=None,\n exclude_pkgs=None,\n ):\n '''\n Bootstrap an image using the pacman tools\n\n root\n The root of the image to install to. Will be created as a directory if\n it does not exist. (e.x.: /root/arch)\n\n pkg_confs\n The location of the conf files to copy into the image, to point pacman\n to the right repos and configuration.\n\n img_format\n The image format to be used. The ``dir`` type needs no special\n treatment, but others need special treatment.\n\n pkgs\n A list of packages to be installed on this image. For Arch Linux, this\n will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat``\n by default.\n\n exclude_pkgs\n A list of packages to be excluded. If you do not want to install the\n defaults, you need to include them in this list.\n '''\n _make_nodes(root)\n\n if pkgs is None:\n pkgs = []\n elif isinstance(pkgs, six.string_types):\n pkgs = pkgs.split(',')\n\n default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub')\n for pkg in default_pkgs:\n if pkg not in pkgs:\n pkgs.append(pkg)\n\n if exclude_pkgs is None:\n exclude_pkgs = []\n elif isinstance(exclude_pkgs, six.string_types):\n exclude_pkgs = exclude_pkgs.split(',')\n\n for pkg in exclude_pkgs:\n pkgs.remove(pkg)\n\n if img_format != 'dir':\n __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind')\n __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind')\n\n __salt__['file.mkdir'](\n '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755'\n )\n pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')]\n for pac_file in pac_files:\n __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root)))\n __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True)\n\n pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs\n __salt__['cmd.run'](pacman_args, python_shell=False)\n\n if img_format != 'dir':\n __salt__['mount.umount']('{0}/proc'.format(root))\n __salt__['mount.umount']('{0}/dev'.format(root))\n" ]
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_mkpart
python
def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info
Make a partition, and make it bootable .. versionadded:: Beryllium
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L227-L261
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_mkfs
python
def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts)
Make a filesystem using the appropriate module .. versionadded:: Beryllium
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L264-L278
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_populate_cache
python
def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True)
If a ``pkg_cache`` directory is specified, then use it to populate the disk image.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L281-L295
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_bootstrap_yum
python
def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False )
Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L298-L361
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_bootstrap_deb
python
def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env )
Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L364-L460
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_bootstrap_pacman
python
def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root))
Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L463-L531
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_make_nodes
python
def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path)
Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L534-L565
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
avail_platforms
python
def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret
Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L568-L584
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
pack
python
def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress)
Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L587-L599
[ "def _tar(name, root, path=None, compress='bzip2'):\n '''\n Pack up image in a tar format\n '''\n if path is None:\n path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img')\n if not __salt__['file.directory_exists'](path):\n try:\n __salt__['file.mkdir'](path)\n except Exception as exc:\n return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))}\n\n compression, ext = _compress(compress)\n\n tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext)\n out = __salt__['archive.tar'](\n options='{0}pcf'.format(compression),\n tarfile=tarfile,\n sources='.',\n dest=root,\n )\n" ]
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
unpack
python
def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress)
Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L602-L613
[ "def _untar(name, dest=None, path=None, compress='bz2'):\n '''\n Unpack a tarball to be used as a container\n '''\n if path is None:\n path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img')\n\n if not dest:\n dest = path\n\n if not __salt__['file.directory_exists'](dest):\n try:\n __salt__['file.mkdir'](dest)\n except Exception as exc:\n return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))}\n\n compression, ext = _compress(compress)\n\n tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext)\n out = __salt__['archive.tar'](\n options='{0}xf'.format(compression),\n tarfile=tarfile,\n dest=dest,\n )\n" ]
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_tar
python
def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, )
Pack up image in a tar format
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L616-L636
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n", "def _compress(compress):\n '''\n Resolve compression flags\n '''\n if compress in ('bz2', 'bzip2', 'j'):\n compression = 'j'\n ext = 'bz2'\n elif compress in ('gz', 'gzip', 'z'):\n compression = 'z'\n ext = 'gz'\n elif compress in ('xz', 'a', 'J'):\n compression = 'J'\n ext = 'xz'\n\n return compression, ext\n" ]
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
_compress
python
def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext
Resolve compression flags
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L665-L679
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
ldd_deps
python
def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret
Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L682-L724
null
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
saltstack/salt
salt/modules/genesis.py
mksls
python
def mksls(fmt, src, dst=None): ''' Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium ''' if fmt == 'kickstart': return salt.utils.kickstart.mksls(src, dst) elif fmt == 'preseed': return salt.utils.preseed.mksls(src, dst) elif fmt == 'autoyast': return salt.utils.yast.mksls(src, dst)
Convert an installation file/script to an SLS file. Currently supports ``kickstart``, ``preseed``, and ``autoyast``. CLI Examples: salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg salt <minion> genesis.mksls kickstart /path/to/kickstart.cfg /path/to/dest.sls .. versionadded:: Beryllium
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/genesis.py#L727-L744
[ "def mksls(src, dst=None):\n '''\n Convert a preseed file to an SLS file\n '''\n ps_opts = {}\n with salt.utils.files.fopen(src, 'r') as fh_:\n for line in fh_:\n line = salt.utils.stringutils.to_unicode(line)\n if line.startswith('#'):\n continue\n if not line.strip():\n continue\n\n comps = shlex.split(line)\n if comps[0] not in ps_opts.keys():\n ps_opts[comps[0]] = {}\n cmds = comps[1].split('/')\n\n pointer = ps_opts[comps[0]]\n for cmd in cmds:\n pointer = pointer.setdefault(cmd, {})\n\n pointer['type'] = comps[2]\n if len(comps) > 3:\n pointer['argument'] = comps[3]\n\n sls = {}\n\n # Set language\n # ( This looks like it maps to something else )\n sls[ps_opts['d-i']['languagechooser']['language-name-fb']['argument']] = {\n 'locale': ['system']\n }\n\n # Set keyboard\n # ( This looks like it maps to something else )\n sls[ps_opts['d-i']['kbd-chooser']['method']['argument']] = {\n 'keyboard': ['system']\n }\n\n # Set timezone\n timezone = ps_opts['d-i']['time']['zone']['argument']\n sls[timezone] = {'timezone': ['system']}\n if ps_opts['d-i']['tzconfig']['gmt']['argument'] == 'true':\n sls[timezone]['timezone'].append('utc')\n\n # Set network\n if 'netcfg' in ps_opts['d-i'].keys():\n iface = ps_opts['d-i']['netcfg']['choose_interface']['argument']\n sls[iface] = {}\n sls[iface]['enabled'] = True\n if ps_opts['d-i']['netcfg']['confirm_static'] == 'true':\n sls[iface]['proto'] = 'static'\n elif ps_opts['d-i']['netcfg']['disable_dhcp'] == 'false':\n sls[iface]['proto'] = 'dhcp'\n sls[iface]['netmask'] = ps_opts['d-i']['netcfg']['get_netmask']['argument']\n sls[iface]['domain'] = ps_opts['d-i']['netcfg']['get_domain']['argument']\n sls[iface]['gateway'] = ps_opts['d-i']['netcfg']['get_gateway']['argument']\n sls[iface]['hostname'] = ps_opts['d-i']['netcfg']['get_hostname']['argument']\n sls[iface]['ipaddress'] = ps_opts['d-i']['netcfg']['get_ipaddress']['argument']\n sls[iface]['nameservers'] = ps_opts['d-i']['netcfg']['get_nameservers']['argument']\n\n if dst is not None:\n with salt.utils.files.fopen(dst, 'w') as fh_:\n salt.utils.yaml.safe_dump(sls, fh_, default_flow_style=False)\n else:\n return salt.utils.yaml.safe_dump(sls, default_flow_style=False)\n", "def mksls(src, dst=None):\n '''\n Convert an AutoYAST file to an SLS file\n '''\n with salt.utils.files.fopen(src, 'r') as fh_:\n ps_opts = xml.to_dict(ET.fromstring(fh_.read()))\n\n if dst is not None:\n with salt.utils.files.fopen(dst, 'w') as fh_:\n salt.utils.yaml.safe_dump(ps_opts, fh_, default_flow_style=False)\n else:\n return salt.utils.yaml.safe_dump(ps_opts, default_flow_style=False)\n", "def mksls(src, dst=None):\n '''\n Convert a kickstart file to an SLS file\n '''\n mode = 'command'\n sls = {}\n ks_opts = {}\n with salt.utils.files.fopen(src, 'r') as fh_:\n for line in fh_:\n if line.startswith('#'):\n continue\n\n if mode == 'command':\n if line.startswith('auth ') or line.startswith('authconfig '):\n ks_opts['auth'] = parse_auth(line)\n elif line.startswith('autopart'):\n ks_opts['autopath'] = parse_autopart(line)\n elif line.startswith('autostep'):\n ks_opts['autostep'] = parse_autostep(line)\n elif line.startswith('bootloader'):\n ks_opts['bootloader'] = parse_bootloader(line)\n elif line.startswith('btrfs'):\n ks_opts['btrfs'] = parse_btrfs(line)\n elif line.startswith('cdrom'):\n ks_opts['cdrom'] = True\n elif line.startswith('clearpart'):\n ks_opts['clearpart'] = parse_clearpart(line)\n elif line.startswith('cmdline'):\n ks_opts['cmdline'] = True\n elif line.startswith('device'):\n ks_opts['device'] = parse_device(line)\n elif line.startswith('dmraid'):\n ks_opts['dmraid'] = parse_dmraid(line)\n elif line.startswith('driverdisk'):\n ks_opts['driverdisk'] = parse_driverdisk(line)\n elif line.startswith('firewall'):\n ks_opts['firewall'] = parse_firewall(line)\n elif line.startswith('firstboot'):\n ks_opts['firstboot'] = parse_firstboot(line)\n elif line.startswith('group'):\n ks_opts['group'] = parse_group(line)\n elif line.startswith('graphical'):\n ks_opts['graphical'] = True\n elif line.startswith('halt'):\n ks_opts['halt'] = True\n elif line.startswith('harddrive'):\n ks_opts['harddrive'] = True\n elif line.startswith('ignoredisk'):\n ks_opts['ignoredisk'] = parse_ignoredisk(line)\n elif line.startswith('install'):\n ks_opts['install'] = True\n elif line.startswith('iscsi'):\n ks_opts['iscsi'] = parse_iscsi(line)\n elif line.startswith('iscsiname'):\n ks_opts['iscsiname'] = parse_iscsiname(line)\n elif line.startswith('keyboard'):\n ks_opts['keyboard'] = parse_keyboard(line)\n elif line.startswith('lang'):\n ks_opts['lang'] = parse_lang(line)\n elif line.startswith('logvol'):\n if 'logvol' not in ks_opts.keys():\n ks_opts['logvol'] = []\n ks_opts['logvol'].append(parse_logvol(line))\n elif line.startswith('logging'):\n ks_opts['logging'] = parse_logging(line)\n elif line.startswith('mediacheck'):\n ks_opts['mediacheck'] = True\n elif line.startswith('monitor'):\n ks_opts['monitor'] = parse_monitor(line)\n elif line.startswith('multipath'):\n ks_opts['multipath'] = parse_multipath(line)\n elif line.startswith('network'):\n if 'network' not in ks_opts.keys():\n ks_opts['network'] = []\n ks_opts['network'].append(parse_network(line))\n elif line.startswith('nfs'):\n ks_opts['nfs'] = True\n elif line.startswith('part ') or line.startswith('partition'):\n if 'part' not in ks_opts.keys():\n ks_opts['part'] = []\n ks_opts['part'].append(parse_partition(line))\n elif line.startswith('poweroff'):\n ks_opts['poweroff'] = True\n elif line.startswith('raid'):\n if 'raid' not in ks_opts.keys():\n ks_opts['raid'] = []\n ks_opts['raid'].append(parse_raid(line))\n elif line.startswith('reboot'):\n ks_opts['reboot'] = parse_reboot(line)\n elif line.startswith('repo'):\n ks_opts['repo'] = parse_repo(line)\n elif line.startswith('rescue'):\n ks_opts['rescue'] = parse_rescue(line)\n elif line.startswith('rootpw'):\n ks_opts['rootpw'] = parse_rootpw(line)\n elif line.startswith('selinux'):\n ks_opts['selinux'] = parse_selinux(line)\n elif line.startswith('services'):\n ks_opts['services'] = parse_services(line)\n elif line.startswith('shutdown'):\n ks_opts['shutdown'] = True\n elif line.startswith('sshpw'):\n ks_opts['sshpw'] = parse_sshpw(line)\n elif line.startswith('skipx'):\n ks_opts['skipx'] = True\n elif line.startswith('text'):\n ks_opts['text'] = True\n elif line.startswith('timezone'):\n ks_opts['timezone'] = parse_timezone(line)\n elif line.startswith('updates'):\n ks_opts['updates'] = parse_updates(line)\n elif line.startswith('upgrade'):\n ks_opts['upgrade'] = parse_upgrade(line)\n elif line.startswith('url'):\n ks_opts['url'] = True\n elif line.startswith('user'):\n ks_opts['user'] = parse_user(line)\n elif line.startswith('vnc'):\n ks_opts['vnc'] = parse_vnc(line)\n elif line.startswith('volgroup'):\n ks_opts['volgroup'] = parse_volgroup(line)\n elif line.startswith('xconfig'):\n ks_opts['xconfig'] = parse_xconfig(line)\n elif line.startswith('zerombr'):\n ks_opts['zerombr'] = True\n elif line.startswith('zfcp'):\n ks_opts['zfcp'] = parse_zfcp(line)\n\n if line.startswith('%include'):\n rules = shlex.split(line)\n if not ks_opts['include']:\n ks_opts['include'] = []\n ks_opts['include'].append(rules[1])\n\n if line.startswith('%ksappend'):\n rules = shlex.split(line)\n if not ks_opts['ksappend']:\n ks_opts['ksappend'] = []\n ks_opts['ksappend'].append(rules[1])\n\n if line.startswith('%packages'):\n mode = 'packages'\n if 'packages' not in ks_opts.keys():\n ks_opts['packages'] = {'packages': {}}\n\n parser = argparse.ArgumentParser()\n opts = shlex.split(line)\n opts.pop(0)\n parser.add_argument('--default', dest='default', action='store_true')\n parser.add_argument('--excludedocs', dest='excludedocs',\n action='store_true')\n parser.add_argument('--ignoremissing', dest='ignoremissing',\n action='store_true')\n parser.add_argument('--instLangs', dest='instLangs', action='store')\n parser.add_argument('--multilib', dest='multilib', action='store_true')\n parser.add_argument('--nodefaults', dest='nodefaults',\n action='store_true')\n parser.add_argument('--optional', dest='optional', action='store_true')\n parser.add_argument('--nobase', dest='nobase', action='store_true')\n args = clean_args(vars(parser.parse_args(opts)))\n ks_opts['packages']['options'] = args\n\n continue\n\n if line.startswith('%pre'):\n mode = 'pre'\n\n parser = argparse.ArgumentParser()\n opts = shlex.split(line)\n opts.pop(0)\n parser.add_argument('--interpreter', dest='interpreter',\n action='store')\n parser.add_argument('--erroronfail', dest='erroronfail',\n action='store_true')\n parser.add_argument('--log', dest='log', action='store')\n args = clean_args(vars(parser.parse_args(opts)))\n ks_opts['pre'] = {'options': args, 'script': ''}\n\n continue\n\n if line.startswith('%post'):\n mode = 'post'\n\n parser = argparse.ArgumentParser()\n opts = shlex.split(line)\n opts.pop(0)\n parser.add_argument('--nochroot', dest='nochroot', action='store_true')\n parser.add_argument('--interpreter', dest='interpreter',\n action='store')\n parser.add_argument('--erroronfail', dest='erroronfail',\n action='store_true')\n parser.add_argument('--log', dest='log', action='store')\n args = clean_args(vars(parser.parse_args(opts)))\n ks_opts['post'] = {'options': args, 'script': ''}\n\n continue\n\n if line.startswith('%end'):\n mode = None\n\n if mode == 'packages':\n if line.startswith('-'):\n package = line.replace('-', '', 1).strip()\n ks_opts['packages']['packages'][package] = False\n else:\n ks_opts['packages']['packages'][line.strip()] = True\n\n if mode == 'pre':\n ks_opts['pre']['script'] += line\n\n if mode == 'post':\n ks_opts['post']['script'] += line\n\n # Set language\n sls[ks_opts['lang']['lang']] = {'locale': ['system']}\n\n # Set keyboard\n sls[ks_opts['keyboard']['xlayouts']] = {'keyboard': ['system']}\n\n # Set timezone\n sls[ks_opts['timezone']['timezone']] = {'timezone': ['system']}\n if 'utc' in ks_opts['timezone'].keys():\n sls[ks_opts['timezone']['timezone']]['timezone'].append('utc')\n\n # Set network\n if 'network' in ks_opts.keys():\n for interface in ks_opts['network']:\n device = interface.get('device', None)\n if device is not None:\n del interface['device']\n sls[device] = {'proto': interface['bootproto']}\n del interface['bootproto']\n\n if 'onboot' in interface.keys():\n if 'no' in interface['onboot']:\n sls[device]['enabled'] = False\n else:\n sls[device]['enabled'] = True\n del interface['onboot']\n\n if 'noipv4' in interface.keys():\n sls[device]['ipv4'] = {'enabled': False}\n del interface['noipv4']\n if 'noipv6' in interface.keys():\n sls[device]['ipv6'] = {'enabled': False}\n del interface['noipv6']\n\n for option in interface:\n if type(interface[option]) is bool:\n sls[device][option] = {'enabled': [interface[option]]}\n else:\n sls[device][option] = interface[option]\n if 'hostname' in interface:\n sls['system'] = {\n 'network.system': {\n 'enabled': True,\n 'hostname': interface['hostname'],\n 'apply_hostname': True,\n }\n }\n\n # Set selinux\n if 'selinux' in ks_opts.keys():\n for mode in ks_opts['selinux']:\n sls[mode] = {'selinux': ['mode']}\n\n # Get package data together\n if 'nobase' not in ks_opts['packages']['options']:\n sls['base'] = {'pkg_group': ['installed']}\n\n packages = ks_opts['packages']['packages']\n for package in packages:\n if not packages[package]:\n continue\n if package and packages[package] is True:\n if package.startswith('@'):\n pkg_group = package.replace('@', '', 1)\n sls[pkg_group] = {'pkg_group': ['installed']}\n else:\n sls[package] = {'pkg': ['installed']}\n elif packages[package] is False:\n sls[package] = {'pkg': ['absent']}\n\n if dst:\n with salt.utils.files.fopen(dst, 'w') as fp_:\n salt.utils.yaml.safe_dump(sls, fp_, default_flow_style=False)\n else:\n return salt.utils.yaml.safe_dump(sls, default_flow_style=False)\n" ]
# -*- coding: utf-8 -*- ''' Module for managing container and VM images .. versionadded:: 2014.7.0 ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import os import uuid import pprint import logging try: from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: from pipes import quote as _cmd_quote # Import salt libs import salt.syspaths import salt.utils.kickstart import salt.utils.path import salt.utils.preseed import salt.utils.stringutils import salt.utils.validate.path import salt.utils.yast from salt.exceptions import SaltInvocationError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) CMD_MAP = { 'yum': ('yum', 'rpm'), 'deb': ('debootstrap',), 'pacman': ('pacman',), } EPEL_URL = 'http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm' def __virtual__(): ''' By default, this will be available on all platforms; but not all distros will necessarily be supported ''' return True def bootstrap( platform, root, img_format='dir', fs_format='ext2', fs_opts=None, arch=None, flavor=None, repo_url=None, static_qemu=None, img_size=None, mount_dir=None, pkg_cache=None, pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Create an image for a specific platform. Please note that this function *MUST* be run as root, as images that are created make files belonging to root. platform Which platform to use to create the image. Currently supported platforms are rpm, deb and pacman. root Local path to create the root of the image filesystem. img_format Which format to create the image in. By default, just copies files into a directory on the local filesystem (``dir``). Future support will exist for ``sparse``. fs_format When using a non-``dir`` ``img_format``, which filesystem to format the image to. By default, ``ext2``. fs_opts When using a non-``dir`` ``img_format``, a dict of opts may be specified. arch Architecture to install packages for, if supported by the underlying bootstrap tool. Currently only used for deb. flavor Which flavor of operating system to install. This correlates to a specific directory on the distribution repositories. For instance, ``wheezy`` on Debian. repo_url Mainly important for Debian-based repos. Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkg_confs The location of the conf files to copy into the image, to point the installer to the right repos and configuration. img_size If img_format is not ``dir``, then the size of the image must be specified. mount_dir If img_format is not ``dir``, then the image must be mounted somewhere. If the ``mount_dir`` is not specified, then it will be created at ``/opt/salt-genesis.<random_uuid>``. This directory will be unmounted and removed when the process is finished. pkg_cache This points to a directory containing a cache of package files to be copied to the image. It does not need to be specified. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. CLI Examples: .. code-block:: bash salt myminion genesis.bootstrap pacman /root/arch salt myminion genesis.bootstrap rpm /root/redhat salt myminion genesis.bootstrap deb /root/wheezy arch=amd64 \ flavor=wheezy static_qemu=/usr/bin/qemu-x86_64-static ''' if img_format not in ('dir', 'sparse'): raise SaltInvocationError('The img_format must be "sparse" or "dir"') if img_format == 'dir': # We can just use the root as the root if not __salt__['file.directory_exists'](root): try: __salt__['file.mkdir'](root) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} elif img_format == 'sparse': if not img_size: raise SaltInvocationError('An img_size must be specified for a sparse file') if not mount_dir: mount_dir = '/opt/salt-genesis.{0}'.format(uuid.uuid4()) __salt__['file.mkdir'](mount_dir, 'root', 'root', '755') __salt__['cmd.run'](('fallocate', '-l', img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = six.text_type(2048 * 2048) __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) __salt__['mount.mount'](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) if mount_dir: root = mount_dir if pkgs is None: pkgs = [] if exclude_pkgs is None: exclude_pkgs = [] if platform in ('rpm', 'yum'): _bootstrap_yum( root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, ) elif platform == 'deb': _bootstrap_deb( root, arch=arch, flavor=flavor, repo_url=repo_url, static_qemu=static_qemu, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) elif platform == 'pacman': _bootstrap_pacman( root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, ) if img_format != 'dir': blkinfo = __salt__['disk.blkid'](loop2) __salt__['file.replace']( '{0}/boot/grub/grub.cfg'.format(mount_dir), 'ad4103fa-d940-47ca-8506-301d8071d467', # This seems to be the default blkinfo[loop2]['UUID'] ) __salt__['mount.umount'](root) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) __salt__['file.rmdir'](mount_dir) def _mkpart(root, fs_format, fs_opts, mount_dir): ''' Make a partition, and make it bootable .. versionadded:: Beryllium ''' __salt__['partition.mklabel'](root, 'msdos') loop1 = __salt__['cmd.run']('losetup -f') log.debug('First loop device is %s', loop1) __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root)) part_info = __salt__['partition.list'](loop1) start = six.text_type(2048 * 2048) + 'B' end = part_info['info']['size'] __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end) __salt__['partition.set'](loop1, '1', 'boot', 'on') part_info = __salt__['partition.list'](loop1) loop2 = __salt__['cmd.run']('losetup -f') log.debug('Second loop device is %s', loop2) start = start.rstrip('B') __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1)) _mkfs(loop2, fs_format, fs_opts) __salt__['mount.mount'](mount_dir, loop2) __salt__['cmd.run'](( 'grub-install', '--target=i386-pc', '--debug', '--no-floppy', '--modules=part_msdos linux', '--boot-directory={0}/boot'.format(mount_dir), loop1 ), python_shell=False) __salt__['mount.umount'](mount_dir) __salt__['cmd.run']('losetup -d {0}'.format(loop2)) __salt__['cmd.run']('losetup -d {0}'.format(loop1)) return part_info def _mkfs(root, fs_format, fs_opts=None): ''' Make a filesystem using the appropriate module .. versionadded:: Beryllium ''' if fs_opts is None: fs_opts = {} if fs_format in ('ext2', 'ext3', 'ext4'): __salt__['extfs.mkfs'](root, fs_format, **fs_opts) elif fs_format in ('btrfs',): __salt__['btrfs.mkfs'](root, **fs_opts) elif fs_format in ('xfs',): __salt__['xfs.mkfs'](root, **fs_opts) def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman/pkg'.format(mount_dir) __salt__['file.mkdir'](cache_dir, 'root', 'root', '755') __salt__['file.copy'](pkg_cache, cache_dir, recurse=True, remove_existing=True) def _bootstrap_yum( root, pkg_confs='/etc/yum*', pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, ): ''' Bootstrap an image using the yum tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point yum to the right repos and configuration. pkgs A list of packages to be installed on this image. For RedHat, this will include ``yum``, ``centos-release`` and ``iputils`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. epel_url The URL to download the EPEL release package from. TODO: Set up a pre-install overlay, to copy files into /etc/ and so on, which are required for the install to work. ''' if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('yum', 'centos-release', 'iputils') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) _make_nodes(root) release_files = [rf for rf in os.listdir('/etc') if rf.endswith('release')] __salt__['cmd.run']('cp /etc/resolv/conf {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {rfs} {root}/etc'.format(root=_cmd_quote(root), rfs=' '.join(release_files))) __salt__['cmd.run']('cp -r {confs} {root}/etc'.format(root=_cmd_quote(root), confs=_cmd_quote(pkg_confs))) yum_args = ['yum', 'install', '--installroot={0}'.format(_cmd_quote(root)), '-y'] + pkgs __salt__['cmd.run'](yum_args, python_shell=False) if 'epel-release' not in exclude_pkgs: __salt__['cmd.run']( ('rpm', '--root={0}'.format(_cmd_quote(root)), '-Uvh', epel_url), python_shell=False ) def _bootstrap_deb( root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the Debian tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/wheezy) arch Architecture of the target image. (e.x.: amd64) flavor Flavor of Debian to install. (e.x.: wheezy) repo_url Base URL for the mirror to install from. (e.x.: http://ftp.debian.org/debian/) static_qemu Local path to the static qemu binary required for this arch. (e.x.: /usr/bin/qemu-amd64-static) pkgs A list of packages to be installed on this image. exclude_pkgs A list of packages to be excluded. ''' if repo_url is None: repo_url = 'http://ftp.debian.org/debian/' if not salt.utils.path.which('debootstrap'): log.error('Required tool debootstrap is not installed.') return False if static_qemu and not salt.utils.validate.path.is_executable(static_qemu): log.error('Required tool qemu not present/readable at: %s', static_qemu) return False if isinstance(pkgs, (list, tuple)): pkgs = ','.join(pkgs) if isinstance(exclude_pkgs, (list, tuple)): exclude_pkgs = ','.join(exclude_pkgs) deb_args = [ 'debootstrap', '--foreign', '--arch', _cmd_quote(arch)] if pkgs: deb_args += ['--include', _cmd_quote(pkgs)] if exclude_pkgs: deb_args += ['--exclude', _cmd_quote(exclude_pkgs)] deb_args += [ _cmd_quote(flavor), _cmd_quote(root), _cmd_quote(repo_url), ] __salt__['cmd.run'](deb_args, python_shell=False) if static_qemu: __salt__['cmd.run']( 'cp {qemu} {root}/usr/bin/'.format( qemu=_cmd_quote(static_qemu), root=_cmd_quote(root) ) ) env = {'DEBIAN_FRONTEND': 'noninteractive', 'DEBCONF_NONINTERACTIVE_SEEN': 'true', 'LC_ALL': 'C', 'LANGUAGE': 'C', 'LANG': 'C', 'PATH': '/sbin:/bin:/usr/bin'} __salt__['cmd.run']( 'chroot {root} /debootstrap/debootstrap --second-stage'.format( root=_cmd_quote(root) ), env=env ) __salt__['cmd.run']( 'chroot {root} dpkg --configure -a'.format( root=_cmd_quote(root) ), env=env ) def _bootstrap_pacman( root, pkg_confs='/etc/pacman*', img_format='dir', pkgs=None, exclude_pkgs=None, ): ''' Bootstrap an image using the pacman tools root The root of the image to install to. Will be created as a directory if it does not exist. (e.x.: /root/arch) pkg_confs The location of the conf files to copy into the image, to point pacman to the right repos and configuration. img_format The image format to be used. The ``dir`` type needs no special treatment, but others need special treatment. pkgs A list of packages to be installed on this image. For Arch Linux, this will include ``pacman``, ``linux``, ``grub``, and ``systemd-sysvcompat`` by default. exclude_pkgs A list of packages to be excluded. If you do not want to install the defaults, you need to include them in this list. ''' _make_nodes(root) if pkgs is None: pkgs = [] elif isinstance(pkgs, six.string_types): pkgs = pkgs.split(',') default_pkgs = ('pacman', 'linux', 'systemd-sysvcompat', 'grub') for pkg in default_pkgs: if pkg not in pkgs: pkgs.append(pkg) if exclude_pkgs is None: exclude_pkgs = [] elif isinstance(exclude_pkgs, six.string_types): exclude_pkgs = exclude_pkgs.split(',') for pkg in exclude_pkgs: pkgs.remove(pkg) if img_format != 'dir': __salt__['mount.mount']('{0}/proc'.format(root), '/proc', fstype='', opts='bind') __salt__['mount.mount']('{0}/dev'.format(root), '/dev', fstype='', opts='bind') __salt__['file.mkdir']( '{0}/var/lib/pacman/local'.format(root), 'root', 'root', '755' ) pac_files = [rf for rf in os.listdir('/etc') if rf.startswith('pacman.')] for pac_file in pac_files: __salt__['cmd.run']('cp -r /etc/{0} {1}/etc'.format(pac_file, _cmd_quote(root))) __salt__['file.copy']('/var/lib/pacman/sync', '{0}/var/lib/pacman/sync'.format(root), recurse=True) pacman_args = ['pacman', '--noconfirm', '-r', _cmd_quote(root), '-S'] + pkgs __salt__['cmd.run'](pacman_args, python_shell=False) if img_format != 'dir': __salt__['mount.umount']('{0}/proc'.format(root)) __salt__['mount.umount']('{0}/dev'.format(root)) def _make_nodes(root): ''' Make the minimum number of nodes inside of /dev/. Based on: https://wiki.archlinux.org/index.php/Linux_Containers ''' dirs = ( ('{0}/etc'.format(root), 'root', 'root', '755'), ('{0}/dev'.format(root), 'root', 'root', '755'), ('{0}/proc'.format(root), 'root', 'root', '755'), ('{0}/dev/pts'.format(root), 'root', 'root', '755'), ('{0}/dev/shm'.format(root), 'root', 'root', '1755'), ) nodes = ( ('{0}/dev/null'.format(root), 'c', 1, 3, 'root', 'root', '666'), ('{0}/dev/zero'.format(root), 'c', 1, 5, 'root', 'root', '666'), ('{0}/dev/random'.format(root), 'c', 1, 8, 'root', 'root', '666'), ('{0}/dev/urandom'.format(root), 'c', 1, 9, 'root', 'root', '666'), ('{0}/dev/tty'.format(root), 'c', 5, 0, 'root', 'root', '666'), ('{0}/dev/tty0'.format(root), 'c', 4, 0, 'root', 'root', '666'), ('{0}/dev/console'.format(root), 'c', 5, 1, 'root', 'root', '600'), ('{0}/dev/full'.format(root), 'c', 1, 7, 'root', 'root', '666'), ('{0}/dev/initctl'.format(root), 'p', 0, 0, 'root', 'root', '600'), ('{0}/dev/ptmx'.format(root), 'c', 5, 2, 'root', 'root', '666'), ) for path in dirs: __salt__['file.mkdir'](*path) for path in nodes: __salt__['file.mknod'](*path) def avail_platforms(): ''' Return which platforms are available CLI Example: .. code-block:: bash salt myminion genesis.avail_platforms ''' ret = {} for platform in CMD_MAP: ret[platform] = True for cmd in CMD_MAP[platform]: if not salt.utils.path.which(cmd): ret[platform] = False return ret def pack(name, root, path=None, pack_format='tar', compress='bzip2'): ''' Pack up a directory structure, into a specific format CLI Examples: .. code-block:: bash salt myminion genesis.pack centos /root/centos salt myminion genesis.pack centos /root/centos pack_format='tar' ''' if pack_format == 'tar': _tar(name, root, path, compress) def unpack(name, dest=None, path=None, pack_format='tar', compress='bz2'): ''' Unpack an image into a directory structure CLI Example: .. code-block:: bash salt myminion genesis.unpack centos /root/centos ''' if pack_format == 'tar': _untar(name, dest, path, compress) def _tar(name, root, path=None, compress='bzip2'): ''' Pack up image in a tar format ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not __salt__['file.directory_exists'](path): try: __salt__['file.mkdir'](path) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}pcf'.format(compression), tarfile=tarfile, sources='.', dest=root, ) def _untar(name, dest=None, path=None, compress='bz2'): ''' Unpack a tarball to be used as a container ''' if path is None: path = os.path.join(salt.syspaths.BASE_FILE_ROOTS_DIR, 'img') if not dest: dest = path if not __salt__['file.directory_exists'](dest): try: __salt__['file.mkdir'](dest) except Exception as exc: return {'Error': salt.utils.stringutils.to_unicode(pprint.pformat(exc))} compression, ext = _compress(compress) tarfile = '{0}/{1}.tar.{2}'.format(path, name, ext) out = __salt__['archive.tar']( options='{0}xf'.format(compression), tarfile=tarfile, dest=dest, ) def _compress(compress): ''' Resolve compression flags ''' if compress in ('bz2', 'bzip2', 'j'): compression = 'j' ext = 'bz2' elif compress in ('gz', 'gzip', 'z'): compression = 'z' ext = 'gz' elif compress in ('xz', 'a', 'J'): compression = 'J' ext = 'xz' return compression, ext def ldd_deps(filename, ret=None): ''' Recurse through a set of dependencies reported by ``ldd``, to find associated dependencies. Please note that this does not necessarily resolve all (non-package) dependencies for a file; but it does help. CLI Example: salt myminion genesis.ldd_deps bash salt myminion genesis.ldd_deps /bin/bash ''' if not os.path.exists(filename): filename = salt.utils.path.which(filename) if ret is None: ret = [] out = __salt__['cmd.run'](('ldd', filename), python_shell=False) for line in out.splitlines(): if not line.strip(): continue dep_path = '' if '=>' in line: comps = line.split(' => ') dep_comps = comps[1].strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] else: dep_comps = line.strip().split() if os.path.exists(dep_comps[0]): dep_path = dep_comps[0] if dep_path: if dep_path not in ret: ret.append(dep_path) new_deps = ldd_deps(dep_path, ret) for dep in new_deps: if dep not in ret: ret.append(dep) return ret
saltstack/salt
salt/modules/win_psget.py
_pshell
python
def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret
Execute the desired powershell command and ensure that it returns data in json format and load that into python
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L53-L75
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
avail_modules
python
def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names
List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L94-L118
[ "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
list_modules
python
def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names
List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L121-L154
[ "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
install
python
def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules()
Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L157-L199
[ "def list_modules(desc=False):\n '''\n List currently installed PSGet Modules on the system.\n\n :param desc: If ``True``, the verbose description will be returned.\n :type desc: ``bool``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'win01' psget.list_modules\n salt 'win01' psget.list_modules desc=True\n '''\n cmd = 'Get-InstalledModule'\n modules = _pshell(cmd)\n if isinstance(modules, dict):\n ret = []\n if desc:\n modules_ret = {}\n modules_ret[modules['Name']] = copy.deepcopy(modules)\n modules = modules_ret\n return modules\n ret.append(modules['Name'])\n return ret\n names = []\n if desc:\n names = {}\n for module in modules:\n if desc:\n names[module['Name']] = module\n continue\n names.append(module['Name'])\n return names\n", "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
update
python
def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules()
Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L202-L234
[ "def list_modules(desc=False):\n '''\n List currently installed PSGet Modules on the system.\n\n :param desc: If ``True``, the verbose description will be returned.\n :type desc: ``bool``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'win01' psget.list_modules\n salt 'win01' psget.list_modules desc=True\n '''\n cmd = 'Get-InstalledModule'\n modules = _pshell(cmd)\n if isinstance(modules, dict):\n ret = []\n if desc:\n modules_ret = {}\n modules_ret[modules['Name']] = copy.deepcopy(modules)\n modules = modules_ret\n return modules\n ret.append(modules['Name'])\n return ret\n names = []\n if desc:\n names = {}\n for module in modules:\n if desc:\n names[module['Name']] = module\n continue\n names.append(module['Name'])\n return names\n", "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
remove
python
def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L237-L253
[ "def list_modules(desc=False):\n '''\n List currently installed PSGet Modules on the system.\n\n :param desc: If ``True``, the verbose description will be returned.\n :type desc: ``bool``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'win01' psget.list_modules\n salt 'win01' psget.list_modules desc=True\n '''\n cmd = 'Get-InstalledModule'\n modules = _pshell(cmd)\n if isinstance(modules, dict):\n ret = []\n if desc:\n modules_ret = {}\n modules_ret[modules['Name']] = copy.deepcopy(modules)\n modules = modules_ret\n return modules\n ret.append(modules['Name'])\n return ret\n names = []\n if desc:\n names = {}\n for module in modules:\n if desc:\n names[module['Name']] = module\n continue\n names.append(module['Name'])\n return names\n", "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
register_repository
python
def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules()
Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L256-L288
[ "def list_modules(desc=False):\n '''\n List currently installed PSGet Modules on the system.\n\n :param desc: If ``True``, the verbose description will be returned.\n :type desc: ``bool``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'win01' psget.list_modules\n salt 'win01' psget.list_modules desc=True\n '''\n cmd = 'Get-InstalledModule'\n modules = _pshell(cmd)\n if isinstance(modules, dict):\n ret = []\n if desc:\n modules_ret = {}\n modules_ret[modules['Name']] = copy.deepcopy(modules)\n modules = modules_ret\n return modules\n ret.append(modules['Name'])\n return ret\n names = []\n if desc:\n names = {}\n for module in modules:\n if desc:\n names[module['Name']] = module\n continue\n names.append(module['Name'])\n return names\n", "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/modules/win_psget.py
get_repository
python
def get_repository(name): ''' Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo ''' # Putting quotes around the parameter protects against command injection cmd = 'Get-PSRepository "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules()
Get the details of a local PSGet repository :param name: Name of the repository :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.get_repository MyRepo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L291-L307
[ "def list_modules(desc=False):\n '''\n List currently installed PSGet Modules on the system.\n\n :param desc: If ``True``, the verbose description will be returned.\n :type desc: ``bool``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'win01' psget.list_modules\n salt 'win01' psget.list_modules desc=True\n '''\n cmd = 'Get-InstalledModule'\n modules = _pshell(cmd)\n if isinstance(modules, dict):\n ret = []\n if desc:\n modules_ret = {}\n modules_ret[modules['Name']] = copy.deepcopy(modules)\n modules = modules_ret\n return modules\n ret.append(modules['Name'])\n return ret\n names = []\n if desc:\n names = {}\n for module in modules:\n if desc:\n names[module['Name']] = module\n continue\n names.append(module['Name'])\n return names\n", "def _pshell(cmd, cwd=None, json_depth=2):\n '''\n Execute the desired powershell command and ensure that it returns data\n in json format and load that into python\n '''\n if 'convertto-json' not in cmd.lower():\n cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth)\n log.debug('DSC: %s', cmd)\n results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True)\n\n if 'pid' in results:\n del results['pid']\n\n if 'retcode' not in results or results['retcode'] != 0:\n # run_all logs an error to log.error, fail hard back to the user\n raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results)\n\n try:\n ret = salt.utils.json.loads(results['stdout'], strict=False)\n except ValueError:\n raise CommandExecutionError('No JSON results from powershell', info=results)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for managing PowerShell through PowerShellGet (PSGet) :depends: - PowerShell 5.0 - PSGet Support for PowerShell ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import copy import logging # Import Salt libs import salt.utils.json import salt.utils.platform import salt.utils.versions from salt.exceptions import CommandExecutionError # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'psget' def __virtual__(): ''' Set the system module of the kernel is Windows ''' # Verify Windows if not salt.utils.platform.is_windows(): log.debug('Module PSGet: Only available on Windows systems') return False, 'Module PSGet: Only available on Windows systems' # Verify PowerShell powershell_info = __salt__['cmd.shell_info']('powershell') if not powershell_info['installed']: log.debug('Module PSGet: Requires PowerShell') return False, 'Module PSGet: Requires PowerShell' # Verify PowerShell 5.0 or greater if salt.utils.versions.compare(powershell_info['version'], '<', '5.0'): log.debug('Module PSGet: Requires PowerShell 5 or newer') return False, 'Module PSGet: Requires PowerShell 5 or newer.' return __virtualname__ def _pshell(cmd, cwd=None, json_depth=2): ''' Execute the desired powershell command and ensure that it returns data in json format and load that into python ''' if 'convertto-json' not in cmd.lower(): cmd = '{0} | ConvertTo-Json -Depth {1}'.format(cmd, json_depth) log.debug('DSC: %s', cmd) results = __salt__['cmd.run_all'](cmd, shell='powershell', cwd=cwd, python_shell=True) if 'pid' in results: del results['pid'] if 'retcode' not in results or results['retcode'] != 0: # run_all logs an error to log.error, fail hard back to the user raise CommandExecutionError('Issue executing powershell {0}'.format(cmd), info=results) try: ret = salt.utils.json.loads(results['stdout'], strict=False) except ValueError: raise CommandExecutionError('No JSON results from powershell', info=results) return ret def bootstrap(): ''' Make sure that nuget-anycpu.exe is installed. This will download the official nuget-anycpu.exe from the internet. CLI Example: .. code-block:: bash salt 'win01' psget.bootstrap ''' cmd = 'Get-PackageProvider -Name NuGet -ForceBootstrap' ret = _pshell(cmd) return ret def avail_modules(desc=False): ''' List available modules in registered Powershell module repositories. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.avail_modules salt 'win01' psget.avail_modules desc=True ''' cmd = 'Find-Module' modules = _pshell(cmd) names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module['Description'] continue names.append(module['Name']) return names def list_modules(desc=False): ''' List currently installed PSGet Modules on the system. :param desc: If ``True``, the verbose description will be returned. :type desc: ``bool`` CLI Example: .. code-block:: bash salt 'win01' psget.list_modules salt 'win01' psget.list_modules desc=True ''' cmd = 'Get-InstalledModule' modules = _pshell(cmd) if isinstance(modules, dict): ret = [] if desc: modules_ret = {} modules_ret[modules['Name']] = copy.deepcopy(modules) modules = modules_ret return modules ret.append(modules['Name']) return ret names = [] if desc: names = {} for module in modules: if desc: names[module['Name']] = module continue names.append(module['Name']) return names def install(name, minimum_version=None, required_version=None, scope=None, repository=None): ''' Install a Powershell module from powershell gallery on the system. :param name: Name of a Powershell module :type name: ``str`` :param minimum_version: The maximum version to install, e.g. 1.23.2 :type minimum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` :param scope: The scope to install the module to, e.g. CurrentUser, Computer :type scope: ``str`` :param repository: The friendly name of a private repository, e.g. MyREpo :type repository: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.install PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if minimum_version is not None: flags.append(('MinimumVersion', minimum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) if scope is not None: flags.append(('Scope', scope)) if repository is not None: flags.append(('Repository', repository)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Install-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def update(name, maximum_version=None, required_version=None): ''' Update a PowerShell module to a specific version, or the newest :param name: Name of a Powershell module :type name: ``str`` :param maximum_version: The maximum version to install, e.g. 1.23.2 :type maximum_version: ``str`` :param required_version: Install a specific version :type required_version: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.update PowerPlan ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] if maximum_version is not None: flags.append(('MaximumVersion', maximum_version)) if required_version is not None: flags.append(('RequiredVersion', required_version)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Update-Module {0} -Force'.format(params) _pshell(cmd) return name in list_modules() def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command injection cmd = 'Uninstall-Module "{0}"'.format(name) no_ret = _pshell(cmd) return name not in list_modules() def register_repository(name, location, installation_policy=None): ''' Register a PSGet repository on the local machine :param name: The name for the repository :type name: ``str`` :param location: The URI for the repository :type location: ``str`` :param installation_policy: The installation policy for packages, e.g. Trusted, Untrusted :type installation_policy: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.register_repository MyRepo https://myrepo.mycompany.com/packages ''' # Putting quotes around the parameter protects against command injection flags = [('Name', name)] flags.append(('SourceLocation', location)) if installation_policy is not None: flags.append(('InstallationPolicy', installation_policy)) params = '' for flag, value in flags: params += '-{0} {1} '.format(flag, value) cmd = 'Register-PSRepository {0}'.format(params) no_ret = _pshell(cmd) return name not in list_modules()
saltstack/salt
salt/states/lxc.py
present
python
def present(name, running=None, clone_from=None, snapshot=False, profile=None, network_profile=None, template=None, options=None, image=None, config=None, fstype=None, size=None, backing=None, vgname=None, lvname=None, thinpool=None, path=None): ''' .. versionchanged:: 2015.8.0 The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>` state has been merged into this state. Create the named container if it does not exist name The name of the container to be created path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 running : False * If ``True``, ensure that the container is running * If ``False``, ensure that the container is stopped * If ``None``, do nothing with regards to the running state of the container .. versionadded:: 2015.8.0 clone_from Create named container as a clone of the specified container snapshot : False Use Copy On Write snapshots (LVM). Only supported with ``clone_from``. profile Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. network_profile Network Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. .. versionadded:: 2015.5.2 **Container Creation Arguments** template The template to use. For example, ``ubuntu`` or ``fedora``. For a full list of available templates, check out the :mod:`lxc.templates <salt.modules.lxc.templates>` function. Conflicts with the ``image`` argument. .. note:: The ``download`` template requires the following three parameters to be defined in ``options``: * **dist** - The name of the distribution * **release** - Release name/version * **arch** - Architecture of the container The available images can be listed using the :mod:`lxc.images <salt.modules.lxc.images>` function. options .. versionadded:: 2015.5.0 Template-specific options to pass to the lxc-create command. These correspond to the long options (ones beginning with two dashes) that the template script accepts. For example: .. code-block:: yaml web01: lxc.present: - template: download - options: dist: centos release: 6 arch: amd64 Remember to double-indent the options, due to :ref:`how PyYAML works <nested-dict-indentation>`. For available template options, refer to the lxc template scripts which are ususally located under ``/usr/share/lxc/templates``, or run ``lxc-create -t <template> -h``. image A tar archive to use as the rootfs for the container. Conflicts with the ``template`` argument. backing The type of storage to use. Set to ``lvm`` to use an LVM group. Defaults to filesystem within /var/lib/lxc. fstype Filesystem type to use on LVM logical volume size Size of the volume to create. Only applicable if ``backing`` is set to ``lvm``. vgname : lxc Name of the LVM volume group in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. lvname Name of the LVM logical volume in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. thinpool Name of a pool volume that will be used for thin-provisioning this container. Only applicable if ``backing`` is set to ``lvm``. ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' already exists'.format(name), 'changes': {}} if not any((template, image, clone_from)): # Take a peek into the profile to see if there is a clone source there. # Otherwise, we're assuming this is a template/image creation. Also # check to see if none of the create types are in the profile. If this # is the case, then bail out early. c_profile = __salt__['lxc.get_container_profile'](profile) if not any(x for x in c_profile if x in ('template', 'image', 'clone_from')): ret['result'] = False ret['comment'] = ('No template, image, or clone_from parameter ' 'was found in either the state\'s arguments or ' 'the LXC profile') else: try: # Assign the profile's clone_from param to the state, so that # we know to invoke lxc.clone to create the container. clone_from = c_profile['clone_from'] except KeyError: pass # Sanity check(s) if clone_from and not __salt__['lxc.exists'](clone_from, path=path): ret['result'] = False ret['comment'] = ('Clone source \'{0}\' does not exist' .format(clone_from)) if not ret['result']: return ret action = 'cloned from {0}'.format(clone_from) if clone_from else 'created' state = {'old': __salt__['lxc.state'](name, path=path)} if __opts__['test']: if state['old'] is None: ret['comment'] = ( 'Container \'{0}\' will be {1}'.format( name, 'cloned from {0}'.format(clone_from) if clone_from else 'created') ) ret['result'] = None return ret else: if running is None: # Container exists and we're not managing whether or not it's # running. Set the result back to True and return return ret elif running: if state['old'] in ('frozen', 'stopped'): ret['comment'] = ( 'Container \'{0}\' would be {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) ret['result'] = None return ret else: ret['comment'] += ' and is running' return ret else: if state['old'] in ('frozen', 'running'): ret['comment'] = ( 'Container \'{0}\' would be stopped'.format(name) ) ret['result'] = None return ret else: ret['comment'] += ' and is stopped' return ret if state['old'] is None: # Container does not exist try: if clone_from: result = __salt__['lxc.clone'](name, clone_from, profile=profile, network_profile=network_profile, snapshot=snapshot, size=size, path=path, backing=backing) else: result = __salt__['lxc.create']( name, profile=profile, network_profile=network_profile, template=template, options=options, image=image, config=config, fstype=fstype, size=size, backing=backing, vgname=vgname, path=path, lvname=lvname, thinpool=thinpool) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror else: if clone_from: ret['comment'] = ('Cloned container \'{0}\' as \'{1}\'' .format(clone_from, name)) else: ret['comment'] = 'Created container \'{0}\''.format(name) state['new'] = result['state']['new'] if ret['result'] is True: # Enforce the "running" parameter if running is None: # Don't do anything pass elif running: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'running': ret['comment'] += ' and is running' else: error = ', but it could not be started' try: start_func = 'lxc.unfreeze' if c_state == 'frozen' \ else 'lxc.start' state['new'] = __salt__[start_func]( name, path=path )['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was started' else: ret['comment'] = ( 'Container \'{0}\' was {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) else: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'stopped': if state['old'] is not None: ret['comment'] += ' and is stopped' else: error = ', but it could not be stopped' try: state['new'] = __salt__['lxc.stop']( name, path=path )['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was stopped' else: ret['comment'] = ('Container \'{0}\' was stopped' .format(name)) if 'new' not in state: # Make sure we know the final state of the container before we return state['new'] = __salt__['lxc.state'](name, path=path) if state['old'] != state['new']: ret['changes']['state'] = state return ret
.. versionchanged:: 2015.8.0 The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>` state has been merged into this state. Create the named container if it does not exist name The name of the container to be created path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 running : False * If ``True``, ensure that the container is running * If ``False``, ensure that the container is stopped * If ``None``, do nothing with regards to the running state of the container .. versionadded:: 2015.8.0 clone_from Create named container as a clone of the specified container snapshot : False Use Copy On Write snapshots (LVM). Only supported with ``clone_from``. profile Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. network_profile Network Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. .. versionadded:: 2015.5.2 **Container Creation Arguments** template The template to use. For example, ``ubuntu`` or ``fedora``. For a full list of available templates, check out the :mod:`lxc.templates <salt.modules.lxc.templates>` function. Conflicts with the ``image`` argument. .. note:: The ``download`` template requires the following three parameters to be defined in ``options``: * **dist** - The name of the distribution * **release** - Release name/version * **arch** - Architecture of the container The available images can be listed using the :mod:`lxc.images <salt.modules.lxc.images>` function. options .. versionadded:: 2015.5.0 Template-specific options to pass to the lxc-create command. These correspond to the long options (ones beginning with two dashes) that the template script accepts. For example: .. code-block:: yaml web01: lxc.present: - template: download - options: dist: centos release: 6 arch: amd64 Remember to double-indent the options, due to :ref:`how PyYAML works <nested-dict-indentation>`. For available template options, refer to the lxc template scripts which are ususally located under ``/usr/share/lxc/templates``, or run ``lxc-create -t <template> -h``. image A tar archive to use as the rootfs for the container. Conflicts with the ``template`` argument. backing The type of storage to use. Set to ``lvm`` to use an LVM group. Defaults to filesystem within /var/lib/lxc. fstype Filesystem type to use on LVM logical volume size Size of the volume to create. Only applicable if ``backing`` is set to ``lvm``. vgname : lxc Name of the LVM volume group in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. lvname Name of the LVM logical volume in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. thinpool Name of a pool volume that will be used for thin-provisioning this container. Only applicable if ``backing`` is set to ``lvm``.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxc.py#L15-L330
null
# -*- coding: utf-8 -*- ''' Manage Linux Containers ======================= ''' from __future__ import absolute_import, print_function, unicode_literals __docformat__ = 'restructuredtext en' # Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError # Container existence/non-existence def absent(name, stop=False, path=None): ''' Ensure a container is not present, destroying it if present name Name of the container to destroy stop stop before destroying default: false .. versionadded:: 2015.5.2 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: yaml web01: lxc.absent ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Container \'{0}\' does not exist'.format(name)} if not __salt__['lxc.exists'](name, path=path): return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Container \'{0}\' would be destroyed'.format(name) return ret try: result = __salt__['lxc.destroy'](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] = 'Failed to destroy container: {0}'.format(exc) else: ret['changes']['state'] = result['state'] ret['comment'] = 'Container \'{0}\' was destroyed'.format(name) return ret # Container state (running/frozen/stopped) def running(name, restart=False, path=None): ''' .. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named container, it just starts the container if it is not running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 restart : False Restart container if it is already running .. code-block:: yaml web01: lxc.running web02: lxc.running: - restart: True ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already running'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'running' and not restart: return ret elif state['old'] == 'stopped' and restart: # No need to restart since container is not running restart = False if restart: if state['old'] != 'stopped': action = ('restart', 'restarted') else: action = ('start', 'started') else: if state['old'] == 'frozen': action = ('unfreeze', 'unfrozen') else: action = ('start', 'started') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: if state['old'] == 'frozen' and not restart: result = __salt__['lxc.unfreeze'](name, path=path) else: if restart: result = __salt__['lxc.restart'](name, path=path) else: result = __salt__['lxc.start'](name, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['restarted'] = result['restarted'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def frozen(name, start=True, path=None): ''' .. versionadded:: 2015.5.0 Ensure that a container is frozen .. note:: This state does not enforce the existence of the named container, it just freezes the container if it is running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 start : True Start container first, if necessary. If ``False``, then this state will fail if the container is not running. .. code-block:: yaml web01: lxc.frozen web02: lxc.frozen: - start: False ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already frozen'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) elif state['old'] == 'stopped' and not start: ret['result'] = False ret['comment'] = 'Container \'{0}\' is stopped'.format(name) if ret['result'] is False or state['old'] == 'frozen': return ret if state['old'] == 'stopped': action = ('start and freeze', 'started and frozen') else: action = ('freeze', 'frozen') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.freeze'](name, start=start, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'frozen': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['started'] = result['started'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def stopped(name, kill=False, path=None): ''' Ensure that a container is stopped .. note:: This state does not enforce the existence of the named container, it just stops the container if it running or frozen. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`, or use the :mod:`lxc.absent <salt.states.lxc.absent>` state to ensure that the container does not exist. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 kill : False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespective of this argument. .. versionadded:: 2015.5.0 .. code-block:: yaml web01: lxc.stopped ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already stopped'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'stopped': return ret if kill: action = ('force-stop', 'force-stopped') else: action = ('stop', 'stopped') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.stop'](name, kill=kill, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) if state['old'] != state['new']: ret['changes']['state'] = state return ret def set_pass(name, **kwargs): # pylint: disable=W0613 ''' .. deprecated:: 2015.5.0 This state function has been disabled, as it did not conform to design guidelines. Specifically, due to the fact that :mod:`lxc.set_password <salt.modules.lxc.set_password>` uses ``chpasswd(8)`` to set the password, there was no method to make this action idempotent (in other words, the password would be changed every time). This makes this state redundant, since the following state will do the same thing: .. code-block:: yaml setpass: module.run: - name: set_pass - m_name: root - password: secret ''' return {'name': name, 'comment': 'The lxc.set_pass state is no longer supported. Please ' 'see the LXC states documentation for further ' 'information.', 'result': False, 'changes': {}} def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): ''' .. warning:: This state is unsuitable for setting parameters that appear more than once in an LXC config file, or parameters which must appear in a certain order (such as when configuring more than one network interface). `Issue #35523`_ was opened to track the addition of a suitable replacement or fix. Edit LXC configuration options .. deprecated:: 2015.5.0 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash setconf: lxc.edited_conf: - name: ubuntu - lxc_conf: - network.ipv4.ip: 10.0.3.6 - lxc_conf_unset: - lxc.utsname .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523 ''' if __opts__['test']: return {'name': name, 'comment': '{0} lxc.conf will be edited'.format(name), 'result': True, 'changes': {}} if not lxc_conf_unset: lxc_conf_unset = {} if not lxc_conf: lxc_conf = {} cret = __salt__['lxc.update_lxc_conf'](name, lxc_conf=lxc_conf, lxc_conf_unset=lxc_conf_unset) cret['name'] = name return cret
saltstack/salt
salt/states/lxc.py
absent
python
def absent(name, stop=False, path=None): ''' Ensure a container is not present, destroying it if present name Name of the container to destroy stop stop before destroying default: false .. versionadded:: 2015.5.2 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: yaml web01: lxc.absent ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Container \'{0}\' does not exist'.format(name)} if not __salt__['lxc.exists'](name, path=path): return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Container \'{0}\' would be destroyed'.format(name) return ret try: result = __salt__['lxc.destroy'](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] = 'Failed to destroy container: {0}'.format(exc) else: ret['changes']['state'] = result['state'] ret['comment'] = 'Container \'{0}\' was destroyed'.format(name) return ret
Ensure a container is not present, destroying it if present name Name of the container to destroy stop stop before destroying default: false .. versionadded:: 2015.5.2 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: yaml web01: lxc.absent
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxc.py#L333-L379
null
# -*- coding: utf-8 -*- ''' Manage Linux Containers ======================= ''' from __future__ import absolute_import, print_function, unicode_literals __docformat__ = 'restructuredtext en' # Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError # Container existence/non-existence def present(name, running=None, clone_from=None, snapshot=False, profile=None, network_profile=None, template=None, options=None, image=None, config=None, fstype=None, size=None, backing=None, vgname=None, lvname=None, thinpool=None, path=None): ''' .. versionchanged:: 2015.8.0 The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>` state has been merged into this state. Create the named container if it does not exist name The name of the container to be created path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 running : False * If ``True``, ensure that the container is running * If ``False``, ensure that the container is stopped * If ``None``, do nothing with regards to the running state of the container .. versionadded:: 2015.8.0 clone_from Create named container as a clone of the specified container snapshot : False Use Copy On Write snapshots (LVM). Only supported with ``clone_from``. profile Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. network_profile Network Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. .. versionadded:: 2015.5.2 **Container Creation Arguments** template The template to use. For example, ``ubuntu`` or ``fedora``. For a full list of available templates, check out the :mod:`lxc.templates <salt.modules.lxc.templates>` function. Conflicts with the ``image`` argument. .. note:: The ``download`` template requires the following three parameters to be defined in ``options``: * **dist** - The name of the distribution * **release** - Release name/version * **arch** - Architecture of the container The available images can be listed using the :mod:`lxc.images <salt.modules.lxc.images>` function. options .. versionadded:: 2015.5.0 Template-specific options to pass to the lxc-create command. These correspond to the long options (ones beginning with two dashes) that the template script accepts. For example: .. code-block:: yaml web01: lxc.present: - template: download - options: dist: centos release: 6 arch: amd64 Remember to double-indent the options, due to :ref:`how PyYAML works <nested-dict-indentation>`. For available template options, refer to the lxc template scripts which are ususally located under ``/usr/share/lxc/templates``, or run ``lxc-create -t <template> -h``. image A tar archive to use as the rootfs for the container. Conflicts with the ``template`` argument. backing The type of storage to use. Set to ``lvm`` to use an LVM group. Defaults to filesystem within /var/lib/lxc. fstype Filesystem type to use on LVM logical volume size Size of the volume to create. Only applicable if ``backing`` is set to ``lvm``. vgname : lxc Name of the LVM volume group in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. lvname Name of the LVM logical volume in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. thinpool Name of a pool volume that will be used for thin-provisioning this container. Only applicable if ``backing`` is set to ``lvm``. ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' already exists'.format(name), 'changes': {}} if not any((template, image, clone_from)): # Take a peek into the profile to see if there is a clone source there. # Otherwise, we're assuming this is a template/image creation. Also # check to see if none of the create types are in the profile. If this # is the case, then bail out early. c_profile = __salt__['lxc.get_container_profile'](profile) if not any(x for x in c_profile if x in ('template', 'image', 'clone_from')): ret['result'] = False ret['comment'] = ('No template, image, or clone_from parameter ' 'was found in either the state\'s arguments or ' 'the LXC profile') else: try: # Assign the profile's clone_from param to the state, so that # we know to invoke lxc.clone to create the container. clone_from = c_profile['clone_from'] except KeyError: pass # Sanity check(s) if clone_from and not __salt__['lxc.exists'](clone_from, path=path): ret['result'] = False ret['comment'] = ('Clone source \'{0}\' does not exist' .format(clone_from)) if not ret['result']: return ret action = 'cloned from {0}'.format(clone_from) if clone_from else 'created' state = {'old': __salt__['lxc.state'](name, path=path)} if __opts__['test']: if state['old'] is None: ret['comment'] = ( 'Container \'{0}\' will be {1}'.format( name, 'cloned from {0}'.format(clone_from) if clone_from else 'created') ) ret['result'] = None return ret else: if running is None: # Container exists and we're not managing whether or not it's # running. Set the result back to True and return return ret elif running: if state['old'] in ('frozen', 'stopped'): ret['comment'] = ( 'Container \'{0}\' would be {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) ret['result'] = None return ret else: ret['comment'] += ' and is running' return ret else: if state['old'] in ('frozen', 'running'): ret['comment'] = ( 'Container \'{0}\' would be stopped'.format(name) ) ret['result'] = None return ret else: ret['comment'] += ' and is stopped' return ret if state['old'] is None: # Container does not exist try: if clone_from: result = __salt__['lxc.clone'](name, clone_from, profile=profile, network_profile=network_profile, snapshot=snapshot, size=size, path=path, backing=backing) else: result = __salt__['lxc.create']( name, profile=profile, network_profile=network_profile, template=template, options=options, image=image, config=config, fstype=fstype, size=size, backing=backing, vgname=vgname, path=path, lvname=lvname, thinpool=thinpool) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror else: if clone_from: ret['comment'] = ('Cloned container \'{0}\' as \'{1}\'' .format(clone_from, name)) else: ret['comment'] = 'Created container \'{0}\''.format(name) state['new'] = result['state']['new'] if ret['result'] is True: # Enforce the "running" parameter if running is None: # Don't do anything pass elif running: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'running': ret['comment'] += ' and is running' else: error = ', but it could not be started' try: start_func = 'lxc.unfreeze' if c_state == 'frozen' \ else 'lxc.start' state['new'] = __salt__[start_func]( name, path=path )['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was started' else: ret['comment'] = ( 'Container \'{0}\' was {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) else: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'stopped': if state['old'] is not None: ret['comment'] += ' and is stopped' else: error = ', but it could not be stopped' try: state['new'] = __salt__['lxc.stop']( name, path=path )['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was stopped' else: ret['comment'] = ('Container \'{0}\' was stopped' .format(name)) if 'new' not in state: # Make sure we know the final state of the container before we return state['new'] = __salt__['lxc.state'](name, path=path) if state['old'] != state['new']: ret['changes']['state'] = state return ret # Container state (running/frozen/stopped) def running(name, restart=False, path=None): ''' .. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named container, it just starts the container if it is not running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 restart : False Restart container if it is already running .. code-block:: yaml web01: lxc.running web02: lxc.running: - restart: True ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already running'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'running' and not restart: return ret elif state['old'] == 'stopped' and restart: # No need to restart since container is not running restart = False if restart: if state['old'] != 'stopped': action = ('restart', 'restarted') else: action = ('start', 'started') else: if state['old'] == 'frozen': action = ('unfreeze', 'unfrozen') else: action = ('start', 'started') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: if state['old'] == 'frozen' and not restart: result = __salt__['lxc.unfreeze'](name, path=path) else: if restart: result = __salt__['lxc.restart'](name, path=path) else: result = __salt__['lxc.start'](name, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['restarted'] = result['restarted'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def frozen(name, start=True, path=None): ''' .. versionadded:: 2015.5.0 Ensure that a container is frozen .. note:: This state does not enforce the existence of the named container, it just freezes the container if it is running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 start : True Start container first, if necessary. If ``False``, then this state will fail if the container is not running. .. code-block:: yaml web01: lxc.frozen web02: lxc.frozen: - start: False ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already frozen'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) elif state['old'] == 'stopped' and not start: ret['result'] = False ret['comment'] = 'Container \'{0}\' is stopped'.format(name) if ret['result'] is False or state['old'] == 'frozen': return ret if state['old'] == 'stopped': action = ('start and freeze', 'started and frozen') else: action = ('freeze', 'frozen') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.freeze'](name, start=start, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'frozen': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['started'] = result['started'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def stopped(name, kill=False, path=None): ''' Ensure that a container is stopped .. note:: This state does not enforce the existence of the named container, it just stops the container if it running or frozen. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`, or use the :mod:`lxc.absent <salt.states.lxc.absent>` state to ensure that the container does not exist. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 kill : False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespective of this argument. .. versionadded:: 2015.5.0 .. code-block:: yaml web01: lxc.stopped ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already stopped'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'stopped': return ret if kill: action = ('force-stop', 'force-stopped') else: action = ('stop', 'stopped') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.stop'](name, kill=kill, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) if state['old'] != state['new']: ret['changes']['state'] = state return ret def set_pass(name, **kwargs): # pylint: disable=W0613 ''' .. deprecated:: 2015.5.0 This state function has been disabled, as it did not conform to design guidelines. Specifically, due to the fact that :mod:`lxc.set_password <salt.modules.lxc.set_password>` uses ``chpasswd(8)`` to set the password, there was no method to make this action idempotent (in other words, the password would be changed every time). This makes this state redundant, since the following state will do the same thing: .. code-block:: yaml setpass: module.run: - name: set_pass - m_name: root - password: secret ''' return {'name': name, 'comment': 'The lxc.set_pass state is no longer supported. Please ' 'see the LXC states documentation for further ' 'information.', 'result': False, 'changes': {}} def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): ''' .. warning:: This state is unsuitable for setting parameters that appear more than once in an LXC config file, or parameters which must appear in a certain order (such as when configuring more than one network interface). `Issue #35523`_ was opened to track the addition of a suitable replacement or fix. Edit LXC configuration options .. deprecated:: 2015.5.0 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash setconf: lxc.edited_conf: - name: ubuntu - lxc_conf: - network.ipv4.ip: 10.0.3.6 - lxc_conf_unset: - lxc.utsname .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523 ''' if __opts__['test']: return {'name': name, 'comment': '{0} lxc.conf will be edited'.format(name), 'result': True, 'changes': {}} if not lxc_conf_unset: lxc_conf_unset = {} if not lxc_conf: lxc_conf = {} cret = __salt__['lxc.update_lxc_conf'](name, lxc_conf=lxc_conf, lxc_conf_unset=lxc_conf_unset) cret['name'] = name return cret
saltstack/salt
salt/states/lxc.py
running
python
def running(name, restart=False, path=None): ''' .. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named container, it just starts the container if it is not running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 restart : False Restart container if it is already running .. code-block:: yaml web01: lxc.running web02: lxc.running: - restart: True ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already running'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'running' and not restart: return ret elif state['old'] == 'stopped' and restart: # No need to restart since container is not running restart = False if restart: if state['old'] != 'stopped': action = ('restart', 'restarted') else: action = ('start', 'started') else: if state['old'] == 'frozen': action = ('unfreeze', 'unfrozen') else: action = ('start', 'started') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: if state['old'] == 'frozen' and not restart: result = __salt__['lxc.unfreeze'](name, path=path) else: if restart: result = __salt__['lxc.restart'](name, path=path) else: result = __salt__['lxc.start'](name, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['restarted'] = result['restarted'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret
.. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named container, it just starts the container if it is not running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 restart : False Restart container if it is already running .. code-block:: yaml web01: lxc.running web02: lxc.running: - restart: True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxc.py#L383-L480
null
# -*- coding: utf-8 -*- ''' Manage Linux Containers ======================= ''' from __future__ import absolute_import, print_function, unicode_literals __docformat__ = 'restructuredtext en' # Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError # Container existence/non-existence def present(name, running=None, clone_from=None, snapshot=False, profile=None, network_profile=None, template=None, options=None, image=None, config=None, fstype=None, size=None, backing=None, vgname=None, lvname=None, thinpool=None, path=None): ''' .. versionchanged:: 2015.8.0 The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>` state has been merged into this state. Create the named container if it does not exist name The name of the container to be created path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 running : False * If ``True``, ensure that the container is running * If ``False``, ensure that the container is stopped * If ``None``, do nothing with regards to the running state of the container .. versionadded:: 2015.8.0 clone_from Create named container as a clone of the specified container snapshot : False Use Copy On Write snapshots (LVM). Only supported with ``clone_from``. profile Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. network_profile Network Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. .. versionadded:: 2015.5.2 **Container Creation Arguments** template The template to use. For example, ``ubuntu`` or ``fedora``. For a full list of available templates, check out the :mod:`lxc.templates <salt.modules.lxc.templates>` function. Conflicts with the ``image`` argument. .. note:: The ``download`` template requires the following three parameters to be defined in ``options``: * **dist** - The name of the distribution * **release** - Release name/version * **arch** - Architecture of the container The available images can be listed using the :mod:`lxc.images <salt.modules.lxc.images>` function. options .. versionadded:: 2015.5.0 Template-specific options to pass to the lxc-create command. These correspond to the long options (ones beginning with two dashes) that the template script accepts. For example: .. code-block:: yaml web01: lxc.present: - template: download - options: dist: centos release: 6 arch: amd64 Remember to double-indent the options, due to :ref:`how PyYAML works <nested-dict-indentation>`. For available template options, refer to the lxc template scripts which are ususally located under ``/usr/share/lxc/templates``, or run ``lxc-create -t <template> -h``. image A tar archive to use as the rootfs for the container. Conflicts with the ``template`` argument. backing The type of storage to use. Set to ``lvm`` to use an LVM group. Defaults to filesystem within /var/lib/lxc. fstype Filesystem type to use on LVM logical volume size Size of the volume to create. Only applicable if ``backing`` is set to ``lvm``. vgname : lxc Name of the LVM volume group in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. lvname Name of the LVM logical volume in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. thinpool Name of a pool volume that will be used for thin-provisioning this container. Only applicable if ``backing`` is set to ``lvm``. ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' already exists'.format(name), 'changes': {}} if not any((template, image, clone_from)): # Take a peek into the profile to see if there is a clone source there. # Otherwise, we're assuming this is a template/image creation. Also # check to see if none of the create types are in the profile. If this # is the case, then bail out early. c_profile = __salt__['lxc.get_container_profile'](profile) if not any(x for x in c_profile if x in ('template', 'image', 'clone_from')): ret['result'] = False ret['comment'] = ('No template, image, or clone_from parameter ' 'was found in either the state\'s arguments or ' 'the LXC profile') else: try: # Assign the profile's clone_from param to the state, so that # we know to invoke lxc.clone to create the container. clone_from = c_profile['clone_from'] except KeyError: pass # Sanity check(s) if clone_from and not __salt__['lxc.exists'](clone_from, path=path): ret['result'] = False ret['comment'] = ('Clone source \'{0}\' does not exist' .format(clone_from)) if not ret['result']: return ret action = 'cloned from {0}'.format(clone_from) if clone_from else 'created' state = {'old': __salt__['lxc.state'](name, path=path)} if __opts__['test']: if state['old'] is None: ret['comment'] = ( 'Container \'{0}\' will be {1}'.format( name, 'cloned from {0}'.format(clone_from) if clone_from else 'created') ) ret['result'] = None return ret else: if running is None: # Container exists and we're not managing whether or not it's # running. Set the result back to True and return return ret elif running: if state['old'] in ('frozen', 'stopped'): ret['comment'] = ( 'Container \'{0}\' would be {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) ret['result'] = None return ret else: ret['comment'] += ' and is running' return ret else: if state['old'] in ('frozen', 'running'): ret['comment'] = ( 'Container \'{0}\' would be stopped'.format(name) ) ret['result'] = None return ret else: ret['comment'] += ' and is stopped' return ret if state['old'] is None: # Container does not exist try: if clone_from: result = __salt__['lxc.clone'](name, clone_from, profile=profile, network_profile=network_profile, snapshot=snapshot, size=size, path=path, backing=backing) else: result = __salt__['lxc.create']( name, profile=profile, network_profile=network_profile, template=template, options=options, image=image, config=config, fstype=fstype, size=size, backing=backing, vgname=vgname, path=path, lvname=lvname, thinpool=thinpool) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror else: if clone_from: ret['comment'] = ('Cloned container \'{0}\' as \'{1}\'' .format(clone_from, name)) else: ret['comment'] = 'Created container \'{0}\''.format(name) state['new'] = result['state']['new'] if ret['result'] is True: # Enforce the "running" parameter if running is None: # Don't do anything pass elif running: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'running': ret['comment'] += ' and is running' else: error = ', but it could not be started' try: start_func = 'lxc.unfreeze' if c_state == 'frozen' \ else 'lxc.start' state['new'] = __salt__[start_func]( name, path=path )['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was started' else: ret['comment'] = ( 'Container \'{0}\' was {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) else: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'stopped': if state['old'] is not None: ret['comment'] += ' and is stopped' else: error = ', but it could not be stopped' try: state['new'] = __salt__['lxc.stop']( name, path=path )['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was stopped' else: ret['comment'] = ('Container \'{0}\' was stopped' .format(name)) if 'new' not in state: # Make sure we know the final state of the container before we return state['new'] = __salt__['lxc.state'](name, path=path) if state['old'] != state['new']: ret['changes']['state'] = state return ret def absent(name, stop=False, path=None): ''' Ensure a container is not present, destroying it if present name Name of the container to destroy stop stop before destroying default: false .. versionadded:: 2015.5.2 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: yaml web01: lxc.absent ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Container \'{0}\' does not exist'.format(name)} if not __salt__['lxc.exists'](name, path=path): return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Container \'{0}\' would be destroyed'.format(name) return ret try: result = __salt__['lxc.destroy'](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] = 'Failed to destroy container: {0}'.format(exc) else: ret['changes']['state'] = result['state'] ret['comment'] = 'Container \'{0}\' was destroyed'.format(name) return ret # Container state (running/frozen/stopped) def frozen(name, start=True, path=None): ''' .. versionadded:: 2015.5.0 Ensure that a container is frozen .. note:: This state does not enforce the existence of the named container, it just freezes the container if it is running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 start : True Start container first, if necessary. If ``False``, then this state will fail if the container is not running. .. code-block:: yaml web01: lxc.frozen web02: lxc.frozen: - start: False ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already frozen'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) elif state['old'] == 'stopped' and not start: ret['result'] = False ret['comment'] = 'Container \'{0}\' is stopped'.format(name) if ret['result'] is False or state['old'] == 'frozen': return ret if state['old'] == 'stopped': action = ('start and freeze', 'started and frozen') else: action = ('freeze', 'frozen') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.freeze'](name, start=start, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'frozen': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['started'] = result['started'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def stopped(name, kill=False, path=None): ''' Ensure that a container is stopped .. note:: This state does not enforce the existence of the named container, it just stops the container if it running or frozen. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`, or use the :mod:`lxc.absent <salt.states.lxc.absent>` state to ensure that the container does not exist. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 kill : False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespective of this argument. .. versionadded:: 2015.5.0 .. code-block:: yaml web01: lxc.stopped ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already stopped'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'stopped': return ret if kill: action = ('force-stop', 'force-stopped') else: action = ('stop', 'stopped') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.stop'](name, kill=kill, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) if state['old'] != state['new']: ret['changes']['state'] = state return ret def set_pass(name, **kwargs): # pylint: disable=W0613 ''' .. deprecated:: 2015.5.0 This state function has been disabled, as it did not conform to design guidelines. Specifically, due to the fact that :mod:`lxc.set_password <salt.modules.lxc.set_password>` uses ``chpasswd(8)`` to set the password, there was no method to make this action idempotent (in other words, the password would be changed every time). This makes this state redundant, since the following state will do the same thing: .. code-block:: yaml setpass: module.run: - name: set_pass - m_name: root - password: secret ''' return {'name': name, 'comment': 'The lxc.set_pass state is no longer supported. Please ' 'see the LXC states documentation for further ' 'information.', 'result': False, 'changes': {}} def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): ''' .. warning:: This state is unsuitable for setting parameters that appear more than once in an LXC config file, or parameters which must appear in a certain order (such as when configuring more than one network interface). `Issue #35523`_ was opened to track the addition of a suitable replacement or fix. Edit LXC configuration options .. deprecated:: 2015.5.0 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash setconf: lxc.edited_conf: - name: ubuntu - lxc_conf: - network.ipv4.ip: 10.0.3.6 - lxc_conf_unset: - lxc.utsname .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523 ''' if __opts__['test']: return {'name': name, 'comment': '{0} lxc.conf will be edited'.format(name), 'result': True, 'changes': {}} if not lxc_conf_unset: lxc_conf_unset = {} if not lxc_conf: lxc_conf = {} cret = __salt__['lxc.update_lxc_conf'](name, lxc_conf=lxc_conf, lxc_conf_unset=lxc_conf_unset) cret['name'] = name return cret
saltstack/salt
salt/states/lxc.py
stopped
python
def stopped(name, kill=False, path=None): ''' Ensure that a container is stopped .. note:: This state does not enforce the existence of the named container, it just stops the container if it running or frozen. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`, or use the :mod:`lxc.absent <salt.states.lxc.absent>` state to ensure that the container does not exist. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 kill : False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespective of this argument. .. versionadded:: 2015.5.0 .. code-block:: yaml web01: lxc.stopped ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already stopped'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'stopped': return ret if kill: action = ('force-stop', 'force-stopped') else: action = ('stop', 'stopped') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.stop'](name, kill=kill, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) if state['old'] != state['new']: ret['changes']['state'] = state return ret
Ensure that a container is stopped .. note:: This state does not enforce the existence of the named container, it just stops the container if it running or frozen. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`, or use the :mod:`lxc.absent <salt.states.lxc.absent>` state to ensure that the container does not exist. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 kill : False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespective of this argument. .. versionadded:: 2015.5.0 .. code-block:: yaml web01: lxc.stopped
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxc.py#L570-L646
null
# -*- coding: utf-8 -*- ''' Manage Linux Containers ======================= ''' from __future__ import absolute_import, print_function, unicode_literals __docformat__ = 'restructuredtext en' # Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError # Container existence/non-existence def present(name, running=None, clone_from=None, snapshot=False, profile=None, network_profile=None, template=None, options=None, image=None, config=None, fstype=None, size=None, backing=None, vgname=None, lvname=None, thinpool=None, path=None): ''' .. versionchanged:: 2015.8.0 The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>` state has been merged into this state. Create the named container if it does not exist name The name of the container to be created path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 running : False * If ``True``, ensure that the container is running * If ``False``, ensure that the container is stopped * If ``None``, do nothing with regards to the running state of the container .. versionadded:: 2015.8.0 clone_from Create named container as a clone of the specified container snapshot : False Use Copy On Write snapshots (LVM). Only supported with ``clone_from``. profile Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. network_profile Network Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. .. versionadded:: 2015.5.2 **Container Creation Arguments** template The template to use. For example, ``ubuntu`` or ``fedora``. For a full list of available templates, check out the :mod:`lxc.templates <salt.modules.lxc.templates>` function. Conflicts with the ``image`` argument. .. note:: The ``download`` template requires the following three parameters to be defined in ``options``: * **dist** - The name of the distribution * **release** - Release name/version * **arch** - Architecture of the container The available images can be listed using the :mod:`lxc.images <salt.modules.lxc.images>` function. options .. versionadded:: 2015.5.0 Template-specific options to pass to the lxc-create command. These correspond to the long options (ones beginning with two dashes) that the template script accepts. For example: .. code-block:: yaml web01: lxc.present: - template: download - options: dist: centos release: 6 arch: amd64 Remember to double-indent the options, due to :ref:`how PyYAML works <nested-dict-indentation>`. For available template options, refer to the lxc template scripts which are ususally located under ``/usr/share/lxc/templates``, or run ``lxc-create -t <template> -h``. image A tar archive to use as the rootfs for the container. Conflicts with the ``template`` argument. backing The type of storage to use. Set to ``lvm`` to use an LVM group. Defaults to filesystem within /var/lib/lxc. fstype Filesystem type to use on LVM logical volume size Size of the volume to create. Only applicable if ``backing`` is set to ``lvm``. vgname : lxc Name of the LVM volume group in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. lvname Name of the LVM logical volume in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. thinpool Name of a pool volume that will be used for thin-provisioning this container. Only applicable if ``backing`` is set to ``lvm``. ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' already exists'.format(name), 'changes': {}} if not any((template, image, clone_from)): # Take a peek into the profile to see if there is a clone source there. # Otherwise, we're assuming this is a template/image creation. Also # check to see if none of the create types are in the profile. If this # is the case, then bail out early. c_profile = __salt__['lxc.get_container_profile'](profile) if not any(x for x in c_profile if x in ('template', 'image', 'clone_from')): ret['result'] = False ret['comment'] = ('No template, image, or clone_from parameter ' 'was found in either the state\'s arguments or ' 'the LXC profile') else: try: # Assign the profile's clone_from param to the state, so that # we know to invoke lxc.clone to create the container. clone_from = c_profile['clone_from'] except KeyError: pass # Sanity check(s) if clone_from and not __salt__['lxc.exists'](clone_from, path=path): ret['result'] = False ret['comment'] = ('Clone source \'{0}\' does not exist' .format(clone_from)) if not ret['result']: return ret action = 'cloned from {0}'.format(clone_from) if clone_from else 'created' state = {'old': __salt__['lxc.state'](name, path=path)} if __opts__['test']: if state['old'] is None: ret['comment'] = ( 'Container \'{0}\' will be {1}'.format( name, 'cloned from {0}'.format(clone_from) if clone_from else 'created') ) ret['result'] = None return ret else: if running is None: # Container exists and we're not managing whether or not it's # running. Set the result back to True and return return ret elif running: if state['old'] in ('frozen', 'stopped'): ret['comment'] = ( 'Container \'{0}\' would be {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) ret['result'] = None return ret else: ret['comment'] += ' and is running' return ret else: if state['old'] in ('frozen', 'running'): ret['comment'] = ( 'Container \'{0}\' would be stopped'.format(name) ) ret['result'] = None return ret else: ret['comment'] += ' and is stopped' return ret if state['old'] is None: # Container does not exist try: if clone_from: result = __salt__['lxc.clone'](name, clone_from, profile=profile, network_profile=network_profile, snapshot=snapshot, size=size, path=path, backing=backing) else: result = __salt__['lxc.create']( name, profile=profile, network_profile=network_profile, template=template, options=options, image=image, config=config, fstype=fstype, size=size, backing=backing, vgname=vgname, path=path, lvname=lvname, thinpool=thinpool) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror else: if clone_from: ret['comment'] = ('Cloned container \'{0}\' as \'{1}\'' .format(clone_from, name)) else: ret['comment'] = 'Created container \'{0}\''.format(name) state['new'] = result['state']['new'] if ret['result'] is True: # Enforce the "running" parameter if running is None: # Don't do anything pass elif running: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'running': ret['comment'] += ' and is running' else: error = ', but it could not be started' try: start_func = 'lxc.unfreeze' if c_state == 'frozen' \ else 'lxc.start' state['new'] = __salt__[start_func]( name, path=path )['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was started' else: ret['comment'] = ( 'Container \'{0}\' was {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) else: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'stopped': if state['old'] is not None: ret['comment'] += ' and is stopped' else: error = ', but it could not be stopped' try: state['new'] = __salt__['lxc.stop']( name, path=path )['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was stopped' else: ret['comment'] = ('Container \'{0}\' was stopped' .format(name)) if 'new' not in state: # Make sure we know the final state of the container before we return state['new'] = __salt__['lxc.state'](name, path=path) if state['old'] != state['new']: ret['changes']['state'] = state return ret def absent(name, stop=False, path=None): ''' Ensure a container is not present, destroying it if present name Name of the container to destroy stop stop before destroying default: false .. versionadded:: 2015.5.2 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: yaml web01: lxc.absent ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Container \'{0}\' does not exist'.format(name)} if not __salt__['lxc.exists'](name, path=path): return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Container \'{0}\' would be destroyed'.format(name) return ret try: result = __salt__['lxc.destroy'](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] = 'Failed to destroy container: {0}'.format(exc) else: ret['changes']['state'] = result['state'] ret['comment'] = 'Container \'{0}\' was destroyed'.format(name) return ret # Container state (running/frozen/stopped) def running(name, restart=False, path=None): ''' .. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named container, it just starts the container if it is not running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 restart : False Restart container if it is already running .. code-block:: yaml web01: lxc.running web02: lxc.running: - restart: True ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already running'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'running' and not restart: return ret elif state['old'] == 'stopped' and restart: # No need to restart since container is not running restart = False if restart: if state['old'] != 'stopped': action = ('restart', 'restarted') else: action = ('start', 'started') else: if state['old'] == 'frozen': action = ('unfreeze', 'unfrozen') else: action = ('start', 'started') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: if state['old'] == 'frozen' and not restart: result = __salt__['lxc.unfreeze'](name, path=path) else: if restart: result = __salt__['lxc.restart'](name, path=path) else: result = __salt__['lxc.start'](name, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['restarted'] = result['restarted'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def frozen(name, start=True, path=None): ''' .. versionadded:: 2015.5.0 Ensure that a container is frozen .. note:: This state does not enforce the existence of the named container, it just freezes the container if it is running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 start : True Start container first, if necessary. If ``False``, then this state will fail if the container is not running. .. code-block:: yaml web01: lxc.frozen web02: lxc.frozen: - start: False ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already frozen'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) elif state['old'] == 'stopped' and not start: ret['result'] = False ret['comment'] = 'Container \'{0}\' is stopped'.format(name) if ret['result'] is False or state['old'] == 'frozen': return ret if state['old'] == 'stopped': action = ('start and freeze', 'started and frozen') else: action = ('freeze', 'frozen') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.freeze'](name, start=start, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'frozen': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['started'] = result['started'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def set_pass(name, **kwargs): # pylint: disable=W0613 ''' .. deprecated:: 2015.5.0 This state function has been disabled, as it did not conform to design guidelines. Specifically, due to the fact that :mod:`lxc.set_password <salt.modules.lxc.set_password>` uses ``chpasswd(8)`` to set the password, there was no method to make this action idempotent (in other words, the password would be changed every time). This makes this state redundant, since the following state will do the same thing: .. code-block:: yaml setpass: module.run: - name: set_pass - m_name: root - password: secret ''' return {'name': name, 'comment': 'The lxc.set_pass state is no longer supported. Please ' 'see the LXC states documentation for further ' 'information.', 'result': False, 'changes': {}} def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): ''' .. warning:: This state is unsuitable for setting parameters that appear more than once in an LXC config file, or parameters which must appear in a certain order (such as when configuring more than one network interface). `Issue #35523`_ was opened to track the addition of a suitable replacement or fix. Edit LXC configuration options .. deprecated:: 2015.5.0 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash setconf: lxc.edited_conf: - name: ubuntu - lxc_conf: - network.ipv4.ip: 10.0.3.6 - lxc_conf_unset: - lxc.utsname .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523 ''' if __opts__['test']: return {'name': name, 'comment': '{0} lxc.conf will be edited'.format(name), 'result': True, 'changes': {}} if not lxc_conf_unset: lxc_conf_unset = {} if not lxc_conf: lxc_conf = {} cret = __salt__['lxc.update_lxc_conf'](name, lxc_conf=lxc_conf, lxc_conf_unset=lxc_conf_unset) cret['name'] = name return cret
saltstack/salt
salt/states/lxc.py
edited_conf
python
def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): ''' .. warning:: This state is unsuitable for setting parameters that appear more than once in an LXC config file, or parameters which must appear in a certain order (such as when configuring more than one network interface). `Issue #35523`_ was opened to track the addition of a suitable replacement or fix. Edit LXC configuration options .. deprecated:: 2015.5.0 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash setconf: lxc.edited_conf: - name: ubuntu - lxc_conf: - network.ipv4.ip: 10.0.3.6 - lxc_conf_unset: - lxc.utsname .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523 ''' if __opts__['test']: return {'name': name, 'comment': '{0} lxc.conf will be edited'.format(name), 'result': True, 'changes': {}} if not lxc_conf_unset: lxc_conf_unset = {} if not lxc_conf: lxc_conf = {} cret = __salt__['lxc.update_lxc_conf'](name, lxc_conf=lxc_conf, lxc_conf_unset=lxc_conf_unset) cret['name'] = name return cret
.. warning:: This state is unsuitable for setting parameters that appear more than once in an LXC config file, or parameters which must appear in a certain order (such as when configuring more than one network interface). `Issue #35523`_ was opened to track the addition of a suitable replacement or fix. Edit LXC configuration options .. deprecated:: 2015.5.0 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: bash setconf: lxc.edited_conf: - name: ubuntu - lxc_conf: - network.ipv4.ip: 10.0.3.6 - lxc_conf_unset: - lxc.utsname .. _`Issue #35523`: https://github.com/saltstack/salt/issues/35523
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lxc.py#L676-L725
null
# -*- coding: utf-8 -*- ''' Manage Linux Containers ======================= ''' from __future__ import absolute_import, print_function, unicode_literals __docformat__ = 'restructuredtext en' # Import salt libs from salt.exceptions import CommandExecutionError, SaltInvocationError # Container existence/non-existence def present(name, running=None, clone_from=None, snapshot=False, profile=None, network_profile=None, template=None, options=None, image=None, config=None, fstype=None, size=None, backing=None, vgname=None, lvname=None, thinpool=None, path=None): ''' .. versionchanged:: 2015.8.0 The :mod:`lxc.created <salt.states.lxc.created>` state has been renamed to ``lxc.present``, and the :mod:`lxc.cloned <salt.states.lxc.cloned>` state has been merged into this state. Create the named container if it does not exist name The name of the container to be created path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 running : False * If ``True``, ensure that the container is running * If ``False``, ensure that the container is stopped * If ``None``, do nothing with regards to the running state of the container .. versionadded:: 2015.8.0 clone_from Create named container as a clone of the specified container snapshot : False Use Copy On Write snapshots (LVM). Only supported with ``clone_from``. profile Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. network_profile Network Profile to use in container creation (see the :ref:`LXC Tutorial <tutorial-lxc-profiles-container>` for more information). Values in a profile will be overridden by the parameters listed below. .. versionadded:: 2015.5.2 **Container Creation Arguments** template The template to use. For example, ``ubuntu`` or ``fedora``. For a full list of available templates, check out the :mod:`lxc.templates <salt.modules.lxc.templates>` function. Conflicts with the ``image`` argument. .. note:: The ``download`` template requires the following three parameters to be defined in ``options``: * **dist** - The name of the distribution * **release** - Release name/version * **arch** - Architecture of the container The available images can be listed using the :mod:`lxc.images <salt.modules.lxc.images>` function. options .. versionadded:: 2015.5.0 Template-specific options to pass to the lxc-create command. These correspond to the long options (ones beginning with two dashes) that the template script accepts. For example: .. code-block:: yaml web01: lxc.present: - template: download - options: dist: centos release: 6 arch: amd64 Remember to double-indent the options, due to :ref:`how PyYAML works <nested-dict-indentation>`. For available template options, refer to the lxc template scripts which are ususally located under ``/usr/share/lxc/templates``, or run ``lxc-create -t <template> -h``. image A tar archive to use as the rootfs for the container. Conflicts with the ``template`` argument. backing The type of storage to use. Set to ``lvm`` to use an LVM group. Defaults to filesystem within /var/lib/lxc. fstype Filesystem type to use on LVM logical volume size Size of the volume to create. Only applicable if ``backing`` is set to ``lvm``. vgname : lxc Name of the LVM volume group in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. lvname Name of the LVM logical volume in which to create the volume for this container. Only applicable if ``backing`` is set to ``lvm``. thinpool Name of a pool volume that will be used for thin-provisioning this container. Only applicable if ``backing`` is set to ``lvm``. ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' already exists'.format(name), 'changes': {}} if not any((template, image, clone_from)): # Take a peek into the profile to see if there is a clone source there. # Otherwise, we're assuming this is a template/image creation. Also # check to see if none of the create types are in the profile. If this # is the case, then bail out early. c_profile = __salt__['lxc.get_container_profile'](profile) if not any(x for x in c_profile if x in ('template', 'image', 'clone_from')): ret['result'] = False ret['comment'] = ('No template, image, or clone_from parameter ' 'was found in either the state\'s arguments or ' 'the LXC profile') else: try: # Assign the profile's clone_from param to the state, so that # we know to invoke lxc.clone to create the container. clone_from = c_profile['clone_from'] except KeyError: pass # Sanity check(s) if clone_from and not __salt__['lxc.exists'](clone_from, path=path): ret['result'] = False ret['comment'] = ('Clone source \'{0}\' does not exist' .format(clone_from)) if not ret['result']: return ret action = 'cloned from {0}'.format(clone_from) if clone_from else 'created' state = {'old': __salt__['lxc.state'](name, path=path)} if __opts__['test']: if state['old'] is None: ret['comment'] = ( 'Container \'{0}\' will be {1}'.format( name, 'cloned from {0}'.format(clone_from) if clone_from else 'created') ) ret['result'] = None return ret else: if running is None: # Container exists and we're not managing whether or not it's # running. Set the result back to True and return return ret elif running: if state['old'] in ('frozen', 'stopped'): ret['comment'] = ( 'Container \'{0}\' would be {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) ret['result'] = None return ret else: ret['comment'] += ' and is running' return ret else: if state['old'] in ('frozen', 'running'): ret['comment'] = ( 'Container \'{0}\' would be stopped'.format(name) ) ret['result'] = None return ret else: ret['comment'] += ' and is stopped' return ret if state['old'] is None: # Container does not exist try: if clone_from: result = __salt__['lxc.clone'](name, clone_from, profile=profile, network_profile=network_profile, snapshot=snapshot, size=size, path=path, backing=backing) else: result = __salt__['lxc.create']( name, profile=profile, network_profile=network_profile, template=template, options=options, image=image, config=config, fstype=fstype, size=size, backing=backing, vgname=vgname, path=path, lvname=lvname, thinpool=thinpool) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror else: if clone_from: ret['comment'] = ('Cloned container \'{0}\' as \'{1}\'' .format(clone_from, name)) else: ret['comment'] = 'Created container \'{0}\''.format(name) state['new'] = result['state']['new'] if ret['result'] is True: # Enforce the "running" parameter if running is None: # Don't do anything pass elif running: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'running': ret['comment'] += ' and is running' else: error = ', but it could not be started' try: start_func = 'lxc.unfreeze' if c_state == 'frozen' \ else 'lxc.start' state['new'] = __salt__[start_func]( name, path=path )['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was started' else: ret['comment'] = ( 'Container \'{0}\' was {1}'.format( name, 'unfrozen' if state['old'] == 'frozen' else 'started' ) ) else: c_state = __salt__['lxc.state'](name, path=path) if c_state == 'stopped': if state['old'] is not None: ret['comment'] += ' and is stopped' else: error = ', but it could not be stopped' try: state['new'] = __salt__['lxc.stop']( name, path=path )['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] += error except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] += '{0}: {1}'.format(error, exc) else: if state['old'] is None: ret['comment'] += ', and the container was stopped' else: ret['comment'] = ('Container \'{0}\' was stopped' .format(name)) if 'new' not in state: # Make sure we know the final state of the container before we return state['new'] = __salt__['lxc.state'](name, path=path) if state['old'] != state['new']: ret['changes']['state'] = state return ret def absent(name, stop=False, path=None): ''' Ensure a container is not present, destroying it if present name Name of the container to destroy stop stop before destroying default: false .. versionadded:: 2015.5.2 path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 .. code-block:: yaml web01: lxc.absent ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'Container \'{0}\' does not exist'.format(name)} if not __salt__['lxc.exists'](name, path=path): return ret if __opts__['test']: ret['result'] = None ret['comment'] = 'Container \'{0}\' would be destroyed'.format(name) return ret try: result = __salt__['lxc.destroy'](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret['result'] = False ret['comment'] = 'Failed to destroy container: {0}'.format(exc) else: ret['changes']['state'] = result['state'] ret['comment'] = 'Container \'{0}\' was destroyed'.format(name) return ret # Container state (running/frozen/stopped) def running(name, restart=False, path=None): ''' .. versionchanged:: 2015.5.0 The :mod:`lxc.started <salt.states.lxc.started>` state has been renamed to ``lxc.running`` Ensure that a container is running .. note:: This state does not enforce the existence of the named container, it just starts the container if it is not running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 restart : False Restart container if it is already running .. code-block:: yaml web01: lxc.running web02: lxc.running: - restart: True ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already running'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'running' and not restart: return ret elif state['old'] == 'stopped' and restart: # No need to restart since container is not running restart = False if restart: if state['old'] != 'stopped': action = ('restart', 'restarted') else: action = ('start', 'started') else: if state['old'] == 'frozen': action = ('unfreeze', 'unfrozen') else: action = ('start', 'started') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: if state['old'] == 'frozen' and not restart: result = __salt__['lxc.unfreeze'](name, path=path) else: if restart: result = __salt__['lxc.restart'](name, path=path) else: result = __salt__['lxc.start'](name, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'running': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['restarted'] = result['restarted'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def frozen(name, start=True, path=None): ''' .. versionadded:: 2015.5.0 Ensure that a container is frozen .. note:: This state does not enforce the existence of the named container, it just freezes the container if it is running. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 start : True Start container first, if necessary. If ``False``, then this state will fail if the container is not running. .. code-block:: yaml web01: lxc.frozen web02: lxc.frozen: - start: False ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already frozen'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) elif state['old'] == 'stopped' and not start: ret['result'] = False ret['comment'] = 'Container \'{0}\' is stopped'.format(name) if ret['result'] is False or state['old'] == 'frozen': return ret if state['old'] == 'stopped': action = ('start and freeze', 'started and frozen') else: action = ('freeze', 'frozen') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.freeze'](name, start=start, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'frozen': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) try: ret['changes']['started'] = result['started'] except KeyError: pass if state['old'] != state['new']: ret['changes']['state'] = state return ret def stopped(name, kill=False, path=None): ''' Ensure that a container is stopped .. note:: This state does not enforce the existence of the named container, it just stops the container if it running or frozen. To ensure that the named container exists, use :mod:`lxc.present <salt.states.lxc.present>`, or use the :mod:`lxc.absent <salt.states.lxc.absent>` state to ensure that the container does not exist. name The name of the container path path to the container parent default: /var/lib/lxc (system default) .. versionadded:: 2015.8.0 kill : False Do not wait for the container to stop, kill all tasks in the container. Older LXC versions will stop containers like this irrespective of this argument. .. versionadded:: 2015.5.0 .. code-block:: yaml web01: lxc.stopped ''' ret = {'name': name, 'result': True, 'comment': 'Container \'{0}\' is already stopped'.format(name), 'changes': {}} state = {'old': __salt__['lxc.state'](name, path=path)} if state['old'] is None: ret['result'] = False ret['comment'] = 'Container \'{0}\' does not exist'.format(name) return ret elif state['old'] == 'stopped': return ret if kill: action = ('force-stop', 'force-stopped') else: action = ('stop', 'stopped') if __opts__['test']: ret['result'] = None ret['comment'] = ('Container \'{0}\' would be {1}' .format(name, action[1])) return ret try: result = __salt__['lxc.stop'](name, kill=kill, path=path) except (CommandExecutionError, SaltInvocationError) as exc: ret['result'] = False ret['comment'] = exc.strerror state['new'] = __salt__['lxc.state'](name, path=path) else: state['new'] = result['state']['new'] if state['new'] != 'stopped': ret['result'] = False ret['comment'] = ('Unable to {0} container \'{1}\'' .format(action[0], name)) else: ret['comment'] = ('Container \'{0}\' was successfully {1}' .format(name, action[1])) if state['old'] != state['new']: ret['changes']['state'] = state return ret def set_pass(name, **kwargs): # pylint: disable=W0613 ''' .. deprecated:: 2015.5.0 This state function has been disabled, as it did not conform to design guidelines. Specifically, due to the fact that :mod:`lxc.set_password <salt.modules.lxc.set_password>` uses ``chpasswd(8)`` to set the password, there was no method to make this action idempotent (in other words, the password would be changed every time). This makes this state redundant, since the following state will do the same thing: .. code-block:: yaml setpass: module.run: - name: set_pass - m_name: root - password: secret ''' return {'name': name, 'comment': 'The lxc.set_pass state is no longer supported. Please ' 'see the LXC states documentation for further ' 'information.', 'result': False, 'changes': {}}
saltstack/salt
salt/runners/thin.py
generate
python
def generate(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3', absonly=True, compress='gzip'): ''' Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate salt-run thin.generate mako salt-run thin.generate mako,wempy 1 salt-run thin.generate overwrite=1 ''' conf_mods = __opts__.get('thin_extra_mods') if conf_mods: extra_mods = ','.join([conf_mods, extra_mods]) return salt.utils.thin.gen_thin(__opts__['cachedir'], extra_mods, overwrite, so_mods, python2_bin, python3_bin, absonly, compress)
Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate salt-run thin.generate mako salt-run thin.generate mako,wempy 1 salt-run thin.generate overwrite=1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/thin.py#L17-L45
[ "def gen_thin(cachedir, extra_mods='', overwrite=False, so_mods='',\n python2_bin='python2', python3_bin='python3', absonly=True,\n compress='gzip', extended_cfg=None):\n '''\n Generate the salt-thin tarball and print the location of the tarball\n Optional additional mods to include (e.g. mako) can be supplied as a comma\n delimited string. Permits forcing an overwrite of the output file as well.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run thin.generate\n salt-run thin.generate mako\n salt-run thin.generate mako,wempy 1\n salt-run thin.generate overwrite=1\n '''\n if sys.version_info < (2, 6):\n raise salt.exceptions.SaltSystemExit('The minimum required python version to run salt-ssh is \"2.6\".')\n if compress not in ['gzip', 'zip']:\n log.warning('Unknown compression type: \"%s\". Falling back to \"gzip\" compression.', compress)\n compress = 'gzip'\n\n thindir = os.path.join(cachedir, 'thin')\n if not os.path.isdir(thindir):\n os.makedirs(thindir)\n thintar = os.path.join(thindir, 'thin.' + (compress == 'gzip' and 'tgz' or 'zip'))\n thinver = os.path.join(thindir, 'version')\n pythinver = os.path.join(thindir, '.thin-gen-py-version')\n salt_call = os.path.join(thindir, 'salt-call')\n pymap_cfg = os.path.join(thindir, 'supported-versions')\n code_checksum = os.path.join(thindir, 'code-checksum')\n digest_collector = salt.utils.hashutils.DigestCollector()\n\n with salt.utils.files.fopen(salt_call, 'wb') as fp_:\n fp_.write(_get_salt_call('pyall', **_get_ext_namespaces(extended_cfg)))\n\n if os.path.isfile(thintar):\n if not overwrite:\n if os.path.isfile(thinver):\n with salt.utils.files.fopen(thinver) as fh_:\n overwrite = fh_.read() != salt.version.__version__\n if overwrite is False and os.path.isfile(pythinver):\n with salt.utils.files.fopen(pythinver) as fh_:\n overwrite = fh_.read() != str(sys.version_info[0]) # future lint: disable=blacklisted-function\n else:\n overwrite = True\n\n if overwrite:\n try:\n log.debug('Removing %s archive file', thintar)\n os.remove(thintar)\n except OSError as exc:\n log.error('Error while removing %s file: %s', thintar, exc)\n if os.path.exists(thintar):\n raise salt.exceptions.SaltSystemExit(\n 'Unable to remove {0}. See logs for details.'.format(thintar)\n )\n else:\n return thintar\n if _six.PY3:\n # Let's check for the minimum python 2 version requirement, 2.6\n py_shell_cmd = \"{} -c 'import sys;sys.stdout.write(\\\"%s.%s\\\\n\\\" % sys.version_info[:2]);'\".format(python2_bin)\n cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, shell=True)\n stdout, _ = cmd.communicate()\n if cmd.returncode == 0:\n py2_version = tuple(int(n) for n in stdout.decode('utf-8').strip().split('.'))\n if py2_version < (2, 6):\n raise salt.exceptions.SaltSystemExit(\n 'The minimum required python version to run salt-ssh is \"2.6\".'\n 'The version reported by \"{0}\" is \"{1}\". Please try \"salt-ssh '\n '--python2-bin=<path-to-python-2.6-binary-or-higher>\".'.format(python2_bin, stdout.strip()))\n else:\n log.error('Unable to detect Python-2 version')\n log.debug(stdout)\n\n tops_failure_msg = 'Failed %s tops for Python binary %s.'\n tops_py_version_mapping = {}\n tops = get_tops(extra_mods=extra_mods, so_mods=so_mods)\n tops_py_version_mapping[sys.version_info.major] = tops\n\n # Collect tops, alternative to 2.x version\n if _six.PY2 and sys.version_info.major == 2:\n # Get python 3 tops\n py_shell_cmd = \"{0} -c 'import salt.utils.thin as t;print(t.gte())' '{1}'\".format(\n python3_bin, salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))\n cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n stdout, stderr = cmd.communicate()\n if cmd.returncode == 0:\n try:\n tops = salt.utils.json.loads(stdout)\n tops_py_version_mapping['3'] = tops\n except ValueError as err:\n log.error(tops_failure_msg, 'parsing', python3_bin)\n log.exception(err)\n else:\n log.error(tops_failure_msg, 'collecting', python3_bin)\n log.debug(stderr)\n\n # Collect tops, alternative to 3.x version\n if _six.PY3 and sys.version_info.major == 3:\n # Get python 2 tops\n py_shell_cmd = \"{0} -c 'import salt.utils.thin as t;print(t.gte())' '{1}'\".format(\n python2_bin, salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))\n cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n stdout, stderr = cmd.communicate()\n if cmd.returncode == 0:\n try:\n tops = salt.utils.json.loads(stdout.decode('utf-8'))\n tops_py_version_mapping['2'] = tops\n except ValueError as err:\n log.error(tops_failure_msg, 'parsing', python2_bin)\n log.exception(err)\n else:\n log.error(tops_failure_msg, 'collecting', python2_bin)\n log.debug(stderr)\n\n with salt.utils.files.fopen(pymap_cfg, 'wb') as fp_:\n fp_.write(_get_supported_py_config(tops=tops_py_version_mapping, extended_cfg=extended_cfg))\n\n tmp_thintar = _get_thintar_prefix(thintar)\n if compress == 'gzip':\n tfp = tarfile.open(tmp_thintar, 'w:gz', dereference=True)\n elif compress == 'zip':\n tfp = zipfile.ZipFile(tmp_thintar, 'w', compression=zlib and zipfile.ZIP_DEFLATED or zipfile.ZIP_STORED)\n tfp.add = tfp.write\n\n try: # cwd may not exist if it was removed but salt was run from it\n start_dir = os.getcwd()\n except OSError:\n start_dir = None\n tempdir = None\n\n # Pack default data\n log.debug('Packing default libraries based on current Salt version')\n for py_ver, tops in _six.iteritems(tops_py_version_mapping):\n for top in tops:\n if absonly and not os.path.isabs(top):\n continue\n base = os.path.basename(top)\n top_dirname = os.path.dirname(top)\n if os.path.isdir(top_dirname):\n os.chdir(top_dirname)\n else:\n # This is likely a compressed python .egg\n tempdir = tempfile.mkdtemp()\n egg = zipfile.ZipFile(top_dirname)\n egg.extractall(tempdir)\n top = os.path.join(tempdir, base)\n os.chdir(tempdir)\n\n site_pkg_dir = _is_shareable(base) and 'pyall' or 'py{}'.format(py_ver)\n\n log.debug('Packing \"%s\" to \"%s\" destination', base, site_pkg_dir)\n if not os.path.isdir(top):\n # top is a single file module\n if os.path.exists(os.path.join(top_dirname, base)):\n tfp.add(base, arcname=os.path.join(site_pkg_dir, base))\n continue\n for root, dirs, files in salt.utils.path.os_walk(base, followlinks=True):\n for name in files:\n if not name.endswith(('.pyc', '.pyo')):\n digest_collector.add(os.path.join(root, name))\n arcname = os.path.join(site_pkg_dir, root, name)\n if hasattr(tfp, 'getinfo'):\n try:\n # This is a little slow but there's no clear way to detect duplicates\n tfp.getinfo(os.path.join(site_pkg_dir, root, name))\n arcname = None\n except KeyError:\n log.debug('ZIP: Unable to add \"%s\" with \"getinfo\"', arcname)\n if arcname:\n tfp.add(os.path.join(root, name), arcname=arcname)\n\n if tempdir is not None:\n shutil.rmtree(tempdir)\n tempdir = None\n\n # Pack alternative data\n if extended_cfg:\n log.debug('Packing libraries based on alternative Salt versions')\n for ns, cfg in _six.iteritems(get_ext_tops(extended_cfg)):\n tops = [cfg.get('path')] + cfg.get('dependencies')\n py_ver_major, py_ver_minor = cfg.get('py-version')\n for top in tops:\n base, top_dirname = os.path.basename(top), os.path.dirname(top)\n os.chdir(top_dirname)\n site_pkg_dir = _is_shareable(base) and 'pyall' or 'py{0}'.format(py_ver_major)\n log.debug('Packing alternative \"%s\" to \"%s/%s\" destination', base, ns, site_pkg_dir)\n if not os.path.isdir(top):\n # top is a single file module\n if os.path.exists(os.path.join(top_dirname, base)):\n tfp.add(base, arcname=os.path.join(ns, site_pkg_dir, base))\n continue\n for root, dirs, files in salt.utils.path.os_walk(base, followlinks=True):\n for name in files:\n if not name.endswith(('.pyc', '.pyo')):\n digest_collector.add(os.path.join(root, name))\n arcname = os.path.join(ns, site_pkg_dir, root, name)\n if hasattr(tfp, 'getinfo'):\n try:\n tfp.getinfo(os.path.join(site_pkg_dir, root, name))\n arcname = None\n except KeyError:\n log.debug('ZIP: Unable to add \"%s\" with \"getinfo\"', arcname)\n if arcname:\n tfp.add(os.path.join(root, name), arcname=arcname)\n\n os.chdir(thindir)\n with salt.utils.files.fopen(thinver, 'w+') as fp_:\n fp_.write(salt.version.__version__)\n with salt.utils.files.fopen(pythinver, 'w+') as fp_:\n fp_.write(str(sys.version_info.major)) # future lint: disable=blacklisted-function\n with salt.utils.files.fopen(code_checksum, 'w+') as fp_:\n fp_.write(digest_collector.digest())\n os.chdir(os.path.dirname(thinver))\n\n for fname in ['version', '.thin-gen-py-version', 'salt-call', 'supported-versions', 'code-checksum']:\n tfp.add(fname)\n\n if start_dir:\n os.chdir(start_dir)\n tfp.close()\n\n shutil.move(tmp_thintar, thintar)\n\n return thintar\n" ]
# -*- coding: utf-8 -*- ''' The thin runner is used to manage the salt thin systems. Salt Thin is a transport-less version of Salt that can be used to run routines in a standalone way. This runner has tools which generate the standalone salt system for easy consumption. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.thin def generate_min(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3'): ''' Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate_min ''' conf_mods = __opts__.get('min_extra_mods') if conf_mods: extra_mods = ','.join([conf_mods, extra_mods]) return salt.utils.thin.gen_min(__opts__['cachedir'], extra_mods, overwrite, so_mods, python2_bin, python3_bin)
saltstack/salt
salt/runners/thin.py
generate_min
python
def generate_min(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3'): ''' Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate_min ''' conf_mods = __opts__.get('min_extra_mods') if conf_mods: extra_mods = ','.join([conf_mods, extra_mods]) return salt.utils.thin.gen_min(__opts__['cachedir'], extra_mods, overwrite, so_mods, python2_bin, python3_bin)
Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate_min
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/thin.py#L48-L70
[ "def gen_min(cachedir, extra_mods='', overwrite=False, so_mods='',\n python2_bin='python2', python3_bin='python3'):\n '''\n Generate the salt-min tarball and print the location of the tarball\n Optional additional mods to include (e.g. mako) can be supplied as a comma\n delimited string. Permits forcing an overwrite of the output file as well.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run min.generate\n salt-run min.generate mako\n salt-run min.generate mako,wempy 1\n salt-run min.generate overwrite=1\n '''\n mindir = os.path.join(cachedir, 'min')\n if not os.path.isdir(mindir):\n os.makedirs(mindir)\n mintar = os.path.join(mindir, 'min.tgz')\n minver = os.path.join(mindir, 'version')\n pyminver = os.path.join(mindir, '.min-gen-py-version')\n salt_call = os.path.join(mindir, 'salt-call')\n with salt.utils.files.fopen(salt_call, 'wb') as fp_:\n fp_.write(_get_salt_call())\n if os.path.isfile(mintar):\n if not overwrite:\n if os.path.isfile(minver):\n with salt.utils.files.fopen(minver) as fh_:\n overwrite = fh_.read() != salt.version.__version__\n if overwrite is False and os.path.isfile(pyminver):\n with salt.utils.files.fopen(pyminver) as fh_:\n overwrite = fh_.read() != str(sys.version_info[0]) # future lint: disable=blacklisted-function\n else:\n overwrite = True\n\n if overwrite:\n try:\n os.remove(mintar)\n except OSError:\n pass\n else:\n return mintar\n if _six.PY3:\n # Let's check for the minimum python 2 version requirement, 2.6\n py_shell_cmd = (\n python2_bin + ' -c \\'from __future__ import print_function; import sys; '\n 'print(\"{0}.{1}\".format(*(sys.version_info[:2])));\\''\n )\n cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, shell=True)\n stdout, _ = cmd.communicate()\n if cmd.returncode == 0:\n py2_version = tuple(int(n) for n in stdout.decode('utf-8').strip().split('.'))\n if py2_version < (2, 6):\n # Bail!\n raise salt.exceptions.SaltSystemExit(\n 'The minimum required python version to run salt-ssh is \"2.6\".'\n 'The version reported by \"{0}\" is \"{1}\". Please try \"salt-ssh '\n '--python2-bin=<path-to-python-2.6-binary-or-higher>\".'.format(python2_bin,\n stdout.strip())\n )\n elif sys.version_info < (2, 6):\n # Bail! Though, how did we reached this far in the first place.\n raise salt.exceptions.SaltSystemExit(\n 'The minimum required python version to run salt-ssh is \"2.6\".'\n )\n\n tops_py_version_mapping = {}\n tops = get_tops(extra_mods=extra_mods, so_mods=so_mods)\n if _six.PY2:\n tops_py_version_mapping['2'] = tops\n else:\n tops_py_version_mapping['3'] = tops\n\n # TODO: Consider putting known py2 and py3 compatible libs in it's own sharable directory.\n # This would reduce the min size.\n if _six.PY2 and sys.version_info[0] == 2:\n # Get python 3 tops\n py_shell_cmd = (\n python3_bin + ' -c \\'import sys; import json; import salt.utils.thin; '\n 'print(json.dumps(salt.utils.thin.get_tops(**(json.loads(sys.argv[1]))), ensure_ascii=False)); exit(0);\\' '\n '\\'{0}\\''.format(salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))\n )\n cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n stdout, stderr = cmd.communicate()\n if cmd.returncode == 0:\n try:\n tops = salt.utils.json.loads(stdout)\n tops_py_version_mapping['3'] = tops\n except ValueError:\n pass\n if _six.PY3 and sys.version_info[0] == 3:\n # Get python 2 tops\n py_shell_cmd = (\n python2_bin + ' -c \\'from __future__ import print_function; '\n 'import sys; import json; import salt.utils.thin; '\n 'print(json.dumps(salt.utils.thin.get_tops(**(json.loads(sys.argv[1]))), ensure_ascii=False)); exit(0);\\' '\n '\\'{0}\\''.format(salt.utils.json.dumps({'extra_mods': extra_mods, 'so_mods': so_mods}))\n )\n cmd = subprocess.Popen(py_shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n stdout, stderr = cmd.communicate()\n if cmd.returncode == 0:\n try:\n tops = salt.utils.json.loads(stdout.decode('utf-8'))\n tops_py_version_mapping['2'] = tops\n except ValueError:\n pass\n\n tfp = tarfile.open(mintar, 'w:gz', dereference=True)\n try: # cwd may not exist if it was removed but salt was run from it\n start_dir = os.getcwd()\n except OSError:\n start_dir = None\n tempdir = None\n\n # This is the absolute minimum set of files required to run salt-call\n min_files = (\n 'salt/__init__.py',\n 'salt/utils',\n 'salt/utils/__init__.py',\n 'salt/utils/atomicfile.py',\n 'salt/utils/validate',\n 'salt/utils/validate/__init__.py',\n 'salt/utils/validate/path.py',\n 'salt/utils/decorators',\n 'salt/utils/decorators/__init__.py',\n 'salt/utils/cache.py',\n 'salt/utils/xdg.py',\n 'salt/utils/odict.py',\n 'salt/utils/minions.py',\n 'salt/utils/dicttrim.py',\n 'salt/utils/sdb.py',\n 'salt/utils/migrations.py',\n 'salt/utils/files.py',\n 'salt/utils/parsers.py',\n 'salt/utils/locales.py',\n 'salt/utils/lazy.py',\n 'salt/utils/s3.py',\n 'salt/utils/dictupdate.py',\n 'salt/utils/verify.py',\n 'salt/utils/args.py',\n 'salt/utils/kinds.py',\n 'salt/utils/xmlutil.py',\n 'salt/utils/debug.py',\n 'salt/utils/jid.py',\n 'salt/utils/openstack',\n 'salt/utils/openstack/__init__.py',\n 'salt/utils/openstack/swift.py',\n 'salt/utils/asynchronous.py',\n 'salt/utils/process.py',\n 'salt/utils/jinja.py',\n 'salt/utils/rsax931.py',\n 'salt/utils/context.py',\n 'salt/utils/minion.py',\n 'salt/utils/error.py',\n 'salt/utils/aws.py',\n 'salt/utils/timed_subprocess.py',\n 'salt/utils/zeromq.py',\n 'salt/utils/schedule.py',\n 'salt/utils/url.py',\n 'salt/utils/yamlencoding.py',\n 'salt/utils/network.py',\n 'salt/utils/http.py',\n 'salt/utils/gzip_util.py',\n 'salt/utils/vt.py',\n 'salt/utils/templates.py',\n 'salt/utils/aggregation.py',\n 'salt/utils/yaml.py',\n 'salt/utils/yamldumper.py',\n 'salt/utils/yamlloader.py',\n 'salt/utils/event.py',\n 'salt/utils/state.py',\n 'salt/serializers',\n 'salt/serializers/__init__.py',\n 'salt/serializers/yamlex.py',\n 'salt/template.py',\n 'salt/_compat.py',\n 'salt/loader.py',\n 'salt/client',\n 'salt/client/__init__.py',\n 'salt/ext',\n 'salt/ext/__init__.py',\n 'salt/ext/six.py',\n 'salt/ext/ipaddress.py',\n 'salt/version.py',\n 'salt/syspaths.py',\n 'salt/defaults',\n 'salt/defaults/__init__.py',\n 'salt/defaults/exitcodes.py',\n 'salt/renderers',\n 'salt/renderers/__init__.py',\n 'salt/renderers/jinja.py',\n 'salt/renderers/yaml.py',\n 'salt/modules',\n 'salt/modules/__init__.py',\n 'salt/modules/test.py',\n 'salt/modules/selinux.py',\n 'salt/modules/cmdmod.py',\n 'salt/modules/saltutil.py',\n 'salt/minion.py',\n 'salt/pillar',\n 'salt/pillar/__init__.py',\n 'salt/textformat.py',\n 'salt/log',\n 'salt/log/__init__.py',\n 'salt/log/handlers',\n 'salt/log/handlers/__init__.py',\n 'salt/log/mixins.py',\n 'salt/log/setup.py',\n 'salt/cli',\n 'salt/cli/__init__.py',\n 'salt/cli/caller.py',\n 'salt/cli/daemons.py',\n 'salt/cli/salt.py',\n 'salt/cli/call.py',\n 'salt/fileserver',\n 'salt/fileserver/__init__.py',\n 'salt/transport',\n 'salt/transport/__init__.py',\n 'salt/transport/client.py',\n 'salt/exceptions.py',\n 'salt/grains',\n 'salt/grains/__init__.py',\n 'salt/grains/extra.py',\n 'salt/scripts.py',\n 'salt/state.py',\n 'salt/fileclient.py',\n 'salt/crypt.py',\n 'salt/config.py',\n 'salt/beacons',\n 'salt/beacons/__init__.py',\n 'salt/payload.py',\n 'salt/output',\n 'salt/output/__init__.py',\n 'salt/output/nested.py',\n )\n\n for py_ver, tops in _six.iteritems(tops_py_version_mapping):\n for top in tops:\n base = os.path.basename(top)\n top_dirname = os.path.dirname(top)\n if os.path.isdir(top_dirname):\n os.chdir(top_dirname)\n else:\n # This is likely a compressed python .egg\n tempdir = tempfile.mkdtemp()\n egg = zipfile.ZipFile(top_dirname)\n egg.extractall(tempdir)\n top = os.path.join(tempdir, base)\n os.chdir(tempdir)\n if not os.path.isdir(top):\n # top is a single file module\n tfp.add(base, arcname=os.path.join('py{0}'.format(py_ver), base))\n continue\n for root, dirs, files in salt.utils.path.os_walk(base, followlinks=True):\n for name in files:\n if name.endswith(('.pyc', '.pyo')):\n continue\n if root.startswith('salt') and os.path.join(root, name) not in min_files:\n continue\n tfp.add(os.path.join(root, name),\n arcname=os.path.join('py{0}'.format(py_ver), root, name))\n if tempdir is not None:\n shutil.rmtree(tempdir)\n tempdir = None\n\n os.chdir(mindir)\n tfp.add('salt-call')\n with salt.utils.files.fopen(minver, 'w+') as fp_:\n fp_.write(salt.version.__version__)\n with salt.utils.files.fopen(pyminver, 'w+') as fp_:\n fp_.write(str(sys.version_info[0])) # future lint: disable=blacklisted-function\n os.chdir(os.path.dirname(minver))\n tfp.add('version')\n tfp.add('.min-gen-py-version')\n if start_dir:\n os.chdir(start_dir)\n tfp.close()\n return mintar\n" ]
# -*- coding: utf-8 -*- ''' The thin runner is used to manage the salt thin systems. Salt Thin is a transport-less version of Salt that can be used to run routines in a standalone way. This runner has tools which generate the standalone salt system for easy consumption. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # Import Salt libs import salt.utils.thin def generate(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3', absonly=True, compress='gzip'): ''' Generate the salt-thin tarball and print the location of the tarball Optional additional mods to include (e.g. mako) can be supplied as a comma delimited string. Permits forcing an overwrite of the output file as well. CLI Example: .. code-block:: bash salt-run thin.generate salt-run thin.generate mako salt-run thin.generate mako,wempy 1 salt-run thin.generate overwrite=1 ''' conf_mods = __opts__.get('thin_extra_mods') if conf_mods: extra_mods = ','.join([conf_mods, extra_mods]) return salt.utils.thin.gen_thin(__opts__['cachedir'], extra_mods, overwrite, so_mods, python2_bin, python3_bin, absonly, compress)
saltstack/salt
salt/auth/rest.py
auth
python
def auth(username, password): ''' REST authentication ''' url = rest_auth_setup() data = {'username': username, 'password': password} # Post to the API endpoint. If 200 is returned then the result will be the ACLs # for this user result = salt.utils.http.query(url, method='POST', data=data, status=True, decode=True) if result['status'] == 200: log.debug('eauth REST call returned 200: %s', result) if result['dict'] is not None: return result['dict'] return True else: log.debug('eauth REST call failed: %s', result) return False
REST authentication
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/rest.py#L50-L70
[ "def rest_auth_setup():\n\n if '^url' in __opts__['external_auth']['rest']:\n return __opts__['external_auth']['rest']['^url']\n else:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Provide authentication using a REST call REST auth can be defined like any other eauth module: .. code-block:: yaml external_auth: rest: ^url: https://url/for/rest/call fred: - .* - '@runner' If there are entries underneath the ^url entry then they are merged with any responses from the REST call. In the above example, assuming the REST call does not return any additional ACLs, this will authenticate Fred via a REST call and allow him to run any execution module and all runners. The REST call should return a JSON object that maps to a regular eauth YAML structure as above. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import salt libs import salt.utils.http log = logging.getLogger(__name__) __virtualname__ = 'rest' def __virtual__(): return __virtualname__ def rest_auth_setup(): if '^url' in __opts__['external_auth']['rest']: return __opts__['external_auth']['rest']['^url'] else: return False
saltstack/salt
salt/states/github.py
present
python
def present(name, profile="github", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure user test is present in github: github.present: - name: 'gitexample' The following parameters are required: name This is the github handle of the user in the organization ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_user'](name, profile=profile, **kwargs) # If the user has a valid github handle and is not in the org already if not target: ret['result'] = False ret['comment'] = 'Couldnt find user {0}'.format(name) elif isinstance(target, bool) and target: ret['comment'] = 'User {0} is already in the org '.format(name) ret['result'] = True elif not target.get('in_org', False) and target.get('membership_state') != 'pending': if __opts__['test']: ret['comment'] = 'User {0} will be added to the org'.format(name) return ret # add the user result = __salt__['github.add_user']( name, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists in the org now'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to add user {0} to the org'.format(name) else: ret['comment'] = 'User {0} has already been invited.'.format(name) ret['result'] = True return ret
Ensure a user is present .. code-block:: yaml ensure user test is present in github: github.present: - name: 'gitexample' The following parameters are required: name This is the github handle of the user in the organization
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/github.py#L40-L93
null
# -*- coding: utf-8 -*- ''' Github User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in the Organization. .. code-block:: yaml ensure user test is present in github: github.present: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import time import datetime import logging # Import Salt Libs from salt.ext import six from salt.exceptions import CommandExecutionError from salt.ext.six.moves import range log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the github module is available in __salt__ ''' return 'github' if 'github.list_users' in __salt__ else False def absent(name, profile="github", **kwargs): ''' Ensure a github user is absent .. code-block:: yaml ensure user test is absent in github: github.absent: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' The following parameters are required: name Github handle of the user in organization ''' email = kwargs.get('email') full_name = kwargs.get('fullname') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(name) } target = __salt__['github.get_user'](name, profile=profile, **kwargs) if target: if isinstance(target, bool) or target.get('in_org', False): if __opts__['test']: ret['comment'] = "User {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_user'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted user {0}'.format(name) ret['changes'].setdefault('old', 'User {0} exists'.format(name)) ret['changes'].setdefault('new', 'User {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False else: ret['comment'] = "User {0} has already been deleted!".format(name) ret['result'] = True else: ret['comment'] = 'User {0} does not exist'.format(name) ret['result'] = True return ret return ret def team_present( name, description=None, repo_names=None, privacy='secret', permission='pull', members=None, enforce_mfa=False, no_mfa_grace_seconds=0, profile="github", **kwargs): ''' Ensure a team is present name This is the name of the team in the organization. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. Defaults to secret. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. Defaults to pull. members The members belonging to the team, specified as a dict of member name to optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'. enforce_mfa Whether to enforce MFA requirements on members of the team. If True then all members without `mfa_exempt: True` configured will be removed from the team. Note that `no_mfa_grace_seconds` may be set to allow members a grace period. no_mfa_grace_seconds The number of seconds of grace time that a member will have to enable MFA before being removed from the team. The grace period will begin from `enforce_mfa_from` on the member configuration, which defaults to 1970/01/01. Example: .. code-block:: yaml Ensure team test is present in github: github.team_present: - name: 'test' - members: user1: {} user2: {} Ensure team test_mfa is present in github: github.team_present: - name: 'test_mfa' - members: user1: enforce_mfa_from: 2016/06/15 - enforce_mfa: True .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) test_comments = [] if target: # Team already exists parameters = {} if description is not None and target['description'] != description: parameters['description'] = description if permission is not None and target['permission'] != permission: parameters['permission'] = permission if privacy is not None and target['privacy'] != privacy: parameters['privacy'] = privacy if parameters: if __opts__['test']: test_comments.append('Team properties are set to be edited: {0}' .format(parameters)) ret['result'] = None else: result = __salt__['github.edit_team'](name, profile=profile, **parameters) if result: ret['changes']['team'] = { 'old': 'Team properties were {0}'.format(target), 'new': 'Team properties (that changed) are {0}'.format(parameters) } else: ret['result'] = False ret['comment'] = 'Failed to update team properties.' return ret manage_repos = repo_names is not None current_repos = set(__salt__['github.list_team_repos'](name, profile=profile) .keys()) repo_names = set(repo_names or []) repos_to_add = repo_names - current_repos repos_to_remove = current_repos - repo_names if repo_names else [] if repos_to_add: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'added: {1}.'.format(name, list(repos_to_add))) ret['result'] = None else: for repo_name in repos_to_add: result = (__salt__['github.add_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is not in team {1}'.format(repo_name, name), 'new': 'Repo {0} is in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to add repo {0} to team {1}.' .format(repo_name, name)) return ret if repos_to_remove: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'removed: {1}.'.format(name, list(repos_to_remove))) ret['result'] = None else: for repo_name in repos_to_remove: result = (__salt__['github.remove_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is in team {1}'.format(repo_name, name), 'new': 'Repo {0} is not in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(repo_name, name)) return ret else: # Team does not exist - it will be created. if __opts__['test']: ret['comment'] = 'Team {0} is set to be created.'.format(name) ret['result'] = None return ret result = __salt__['github.add_team']( name, description=description, repo_names=repo_names, permission=permission, privacy=privacy, profile=profile, **kwargs ) if result: ret['changes']['team'] = {} ret['changes']['team']['old'] = None ret['changes']['team']['new'] = 'Team {0} has been created'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to create team {0}.'.format(name) return ret manage_members = members is not None mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(seconds=no_mfa_grace_seconds) members_no_mfa = __salt__['github.list_members_without_mfa'](profile=profile) members_lower = {} for member_name, info in six.iteritems(members or {}): members_lower[member_name.lower()] = info member_change = False current_members = __salt__['github.list_team_members'](name, profile=profile) for member, member_info in six.iteritems(members or {}): log.info('Checking member %s in team %s', member, name) if member.lower() not in current_members: if (enforce_mfa and _member_violates_mfa(member, member_info, mfa_deadline, members_no_mfa)): if __opts__['test']: test_comments.append('User {0} will not be added to the ' 'team because they do not have MFA.' ''.format(member)) else: # Add to team member_change = True if __opts__['test']: test_comments.append('User {0} set to be added to the ' 'team.'.format(member)) ret['result'] = None else: result = (__salt__['github.add_team_member'] (member, name, profile=profile, **kwargs)) if result: ret['changes'][member] = {} ret['changes'][member]['old'] = ( 'User {0} is not in team {1}'.format(member, name)) ret['changes'][member]['new'] = ( 'User {0} is in team {1}'.format(member, name)) else: ret['result'] = False ret['comment'] = ('Failed to add user {0} to team ' '{1}.'.format(member, name)) return ret for member in current_members: mfa_violation = False if member in members_lower: mfa_violation = _member_violates_mfa(member, members_lower[member], mfa_deadline, members_no_mfa) if (manage_members and member not in members_lower or (enforce_mfa and mfa_violation)): # Remove from team member_change = True if __opts__['test']: if mfa_violation: test_comments.append('User {0} set to be removed from the ' 'team because they do not have MFA.' .format(member)) else: test_comments.append('User {0} set to be removed from ' 'the team.'.format(member)) ret['result'] = None else: result = (__salt__['github.remove_team_member'] (member, name, profile=profile, **kwargs)) if result: extra_changes = ' due to MFA violation' if mfa_violation else '' ret['changes'][member] = { 'old': 'User {0} is in team {1}'.format(member, name), 'new': 'User {0} is not in team {1}{2}'.format(member, name, extra_changes) } else: ret['result'] = False ret['comment'] = ('Failed to remove user {0} from team {1}.' .format(member, name)) return ret if member_change: # Refresh team cache __salt__['github.list_team_members'](name, profile=profile, ignore_cache=False, **kwargs) if test_comments: ret['comment'] = '\n'.join(test_comments) return ret def _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa): if member_info.get('mfa_exempt', False): return False enforce_mfa_from = datetime.datetime.strptime( member_info.get('enforce_mfa_from', '1970/01/01'), '%Y/%m/%d') return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from) def team_absent(name, profile="github", **kwargs): ''' Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) if not target: ret['comment'] = 'Team {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Team {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_team'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted team {0}'.format(name) ret['changes'].setdefault('old', 'Team {0} exists'.format(name)) ret['changes'].setdefault('new', 'Team {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False return ret def repo_present( name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=False, gitignore_template=None, license_template=None, teams=None, profile="github", **kwargs): ''' Ensure a repository is present name This is the name of the repository. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". teams The teams for which this repo should belong to, specified as a dict of team name to permission ('pull', 'push' or 'admin'). .. versionadded:: 2017.7.0 Example: .. code-block:: yaml Ensure repo my-repo is present in github: github.repo_present: - name: 'my-repo' - description: 'My very important repository' .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } # This is an optimization to cache all repos in the organization up front. # The first use of this state will collect all of the repos and save a bunch # of API calls for future use. __salt__['github.list_repos'](profile=profile) try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } # Keep track of current_teams if we've fetched them after creating a new repo current_teams = None if target: # Repo already exists # Some params are only valid on repo creation ignore_params = ['auto_init', 'gitignore_template', 'license_template'] parameters = {} old_parameters = {} for param_name, param_value in six.iteritems(given_params): if (param_value is not None and param_name not in ignore_params and target[param_name] is not param_value and target[param_name] != param_value): parameters[param_name] = param_value old_parameters[param_name] = target[param_name] if parameters: repo_change = { 'old': 'Repo properties were {0}'.format(old_parameters), 'new': 'Repo properties (that changed) are {0}'.format(parameters) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: result = __salt__['github.edit_repo'](name, profile=profile, **parameters) if result: ret['changes']['repo'] = repo_change else: ret['result'] = False ret['comment'] = 'Failed to update repo properties.' return ret else: # Repo does not exist - it will be created. repo_change = { 'old': None, 'new': 'Repo {0} has been created'.format(name) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: add_params = dict(given_params) add_params.update(kwargs) result = __salt__['github.add_repo']( name, **add_params ) if not result: ret['result'] = False ret['comment'] = 'Failed to create repo {0}.'.format(name) return ret # Turns out that trying to fetch teams for a new repo can 404 immediately # after repo creation, so this waits until we can fetch teams successfully # before continuing. for attempt in range(3): time.sleep(1) try: current_teams = __salt__['github.get_repo_teams']( name, profile=profile, **kwargs) break except CommandExecutionError as e: log.info("Attempt %s to fetch new repo %s failed", attempt, name) if current_teams is None: ret['result'] = False ret['comment'] = 'Failed to verify repo {0} after creation.'.format(name) return ret ret['changes']['repo'] = repo_change if teams is not None: if __opts__['test'] and not target: # Assume no teams if we're in test mode and the repo doesn't exist current_teams = [] elif current_teams is None: current_teams = __salt__['github.get_repo_teams'](name, profile=profile) current_team_names = set([t['name'] for t in current_teams]) # First remove any teams that aren't present for team_name in current_team_names: if team_name not in teams: team_change = { 'old': 'Repo {0} is in team {1}'.format(name, team_name), 'new': 'Repo {0} is not in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.remove_team_repo'](name, team_name, profile=profile) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret # Next add or modify any necessary teams for team_name, permission in six.iteritems(teams): if team_name not in current_team_names: # Need to add repo to team team_change = { 'old': 'Repo {0} is not in team {1}'.format(name, team_name), 'new': 'Repo {0} is in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret else: current_permission = (__salt__['github.list_team_repos'] (team_name, profile=profile) .get(name.lower(), {}) .get('permission')) if not current_permission: ret['result'] = False ret['comment'] = ('Failed to determine current permission for team ' '{0} in repo {1}'.format(team_name, name)) return ret elif current_permission != permission: team_change = { 'old': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, current_permission)), 'new': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, permission)) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to set permission on repo {0} from ' 'team {1} to {2}.' .format(name, team_name, permission)) return ret return ret def repo_absent(name, profile="github", **kwargs): ''' Ensure a repo is absent. Example: .. code-block:: yaml ensure repo test is absent in github: github.repo_absent: - name: 'test' The following parameters are required: name This is the name of the repository in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None if not target: ret['comment'] = 'Repo {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Repo {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_repo'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted repo {0}'.format(name) ret['changes'].setdefault('old', 'Repo {0} exists'.format(name)) ret['changes'].setdefault('new', 'Repo {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = ('Failed to delete repo {0}. Ensure the delete_repo ' 'scope is enabled if using OAuth.'.format(name)) ret['result'] = False return ret
saltstack/salt
salt/states/github.py
absent
python
def absent(name, profile="github", **kwargs): ''' Ensure a github user is absent .. code-block:: yaml ensure user test is absent in github: github.absent: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' The following parameters are required: name Github handle of the user in organization ''' email = kwargs.get('email') full_name = kwargs.get('fullname') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(name) } target = __salt__['github.get_user'](name, profile=profile, **kwargs) if target: if isinstance(target, bool) or target.get('in_org', False): if __opts__['test']: ret['comment'] = "User {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_user'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted user {0}'.format(name) ret['changes'].setdefault('old', 'User {0} exists'.format(name)) ret['changes'].setdefault('new', 'User {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False else: ret['comment'] = "User {0} has already been deleted!".format(name) ret['result'] = True else: ret['comment'] = 'User {0} does not exist'.format(name) ret['result'] = True return ret return ret
Ensure a github user is absent .. code-block:: yaml ensure user test is absent in github: github.absent: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' The following parameters are required: name Github handle of the user in organization
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/github.py#L96-L151
null
# -*- coding: utf-8 -*- ''' Github User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in the Organization. .. code-block:: yaml ensure user test is present in github: github.present: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import time import datetime import logging # Import Salt Libs from salt.ext import six from salt.exceptions import CommandExecutionError from salt.ext.six.moves import range log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the github module is available in __salt__ ''' return 'github' if 'github.list_users' in __salt__ else False def present(name, profile="github", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure user test is present in github: github.present: - name: 'gitexample' The following parameters are required: name This is the github handle of the user in the organization ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_user'](name, profile=profile, **kwargs) # If the user has a valid github handle and is not in the org already if not target: ret['result'] = False ret['comment'] = 'Couldnt find user {0}'.format(name) elif isinstance(target, bool) and target: ret['comment'] = 'User {0} is already in the org '.format(name) ret['result'] = True elif not target.get('in_org', False) and target.get('membership_state') != 'pending': if __opts__['test']: ret['comment'] = 'User {0} will be added to the org'.format(name) return ret # add the user result = __salt__['github.add_user']( name, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists in the org now'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to add user {0} to the org'.format(name) else: ret['comment'] = 'User {0} has already been invited.'.format(name) ret['result'] = True return ret def team_present( name, description=None, repo_names=None, privacy='secret', permission='pull', members=None, enforce_mfa=False, no_mfa_grace_seconds=0, profile="github", **kwargs): ''' Ensure a team is present name This is the name of the team in the organization. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. Defaults to secret. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. Defaults to pull. members The members belonging to the team, specified as a dict of member name to optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'. enforce_mfa Whether to enforce MFA requirements on members of the team. If True then all members without `mfa_exempt: True` configured will be removed from the team. Note that `no_mfa_grace_seconds` may be set to allow members a grace period. no_mfa_grace_seconds The number of seconds of grace time that a member will have to enable MFA before being removed from the team. The grace period will begin from `enforce_mfa_from` on the member configuration, which defaults to 1970/01/01. Example: .. code-block:: yaml Ensure team test is present in github: github.team_present: - name: 'test' - members: user1: {} user2: {} Ensure team test_mfa is present in github: github.team_present: - name: 'test_mfa' - members: user1: enforce_mfa_from: 2016/06/15 - enforce_mfa: True .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) test_comments = [] if target: # Team already exists parameters = {} if description is not None and target['description'] != description: parameters['description'] = description if permission is not None and target['permission'] != permission: parameters['permission'] = permission if privacy is not None and target['privacy'] != privacy: parameters['privacy'] = privacy if parameters: if __opts__['test']: test_comments.append('Team properties are set to be edited: {0}' .format(parameters)) ret['result'] = None else: result = __salt__['github.edit_team'](name, profile=profile, **parameters) if result: ret['changes']['team'] = { 'old': 'Team properties were {0}'.format(target), 'new': 'Team properties (that changed) are {0}'.format(parameters) } else: ret['result'] = False ret['comment'] = 'Failed to update team properties.' return ret manage_repos = repo_names is not None current_repos = set(__salt__['github.list_team_repos'](name, profile=profile) .keys()) repo_names = set(repo_names or []) repos_to_add = repo_names - current_repos repos_to_remove = current_repos - repo_names if repo_names else [] if repos_to_add: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'added: {1}.'.format(name, list(repos_to_add))) ret['result'] = None else: for repo_name in repos_to_add: result = (__salt__['github.add_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is not in team {1}'.format(repo_name, name), 'new': 'Repo {0} is in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to add repo {0} to team {1}.' .format(repo_name, name)) return ret if repos_to_remove: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'removed: {1}.'.format(name, list(repos_to_remove))) ret['result'] = None else: for repo_name in repos_to_remove: result = (__salt__['github.remove_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is in team {1}'.format(repo_name, name), 'new': 'Repo {0} is not in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(repo_name, name)) return ret else: # Team does not exist - it will be created. if __opts__['test']: ret['comment'] = 'Team {0} is set to be created.'.format(name) ret['result'] = None return ret result = __salt__['github.add_team']( name, description=description, repo_names=repo_names, permission=permission, privacy=privacy, profile=profile, **kwargs ) if result: ret['changes']['team'] = {} ret['changes']['team']['old'] = None ret['changes']['team']['new'] = 'Team {0} has been created'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to create team {0}.'.format(name) return ret manage_members = members is not None mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(seconds=no_mfa_grace_seconds) members_no_mfa = __salt__['github.list_members_without_mfa'](profile=profile) members_lower = {} for member_name, info in six.iteritems(members or {}): members_lower[member_name.lower()] = info member_change = False current_members = __salt__['github.list_team_members'](name, profile=profile) for member, member_info in six.iteritems(members or {}): log.info('Checking member %s in team %s', member, name) if member.lower() not in current_members: if (enforce_mfa and _member_violates_mfa(member, member_info, mfa_deadline, members_no_mfa)): if __opts__['test']: test_comments.append('User {0} will not be added to the ' 'team because they do not have MFA.' ''.format(member)) else: # Add to team member_change = True if __opts__['test']: test_comments.append('User {0} set to be added to the ' 'team.'.format(member)) ret['result'] = None else: result = (__salt__['github.add_team_member'] (member, name, profile=profile, **kwargs)) if result: ret['changes'][member] = {} ret['changes'][member]['old'] = ( 'User {0} is not in team {1}'.format(member, name)) ret['changes'][member]['new'] = ( 'User {0} is in team {1}'.format(member, name)) else: ret['result'] = False ret['comment'] = ('Failed to add user {0} to team ' '{1}.'.format(member, name)) return ret for member in current_members: mfa_violation = False if member in members_lower: mfa_violation = _member_violates_mfa(member, members_lower[member], mfa_deadline, members_no_mfa) if (manage_members and member not in members_lower or (enforce_mfa and mfa_violation)): # Remove from team member_change = True if __opts__['test']: if mfa_violation: test_comments.append('User {0} set to be removed from the ' 'team because they do not have MFA.' .format(member)) else: test_comments.append('User {0} set to be removed from ' 'the team.'.format(member)) ret['result'] = None else: result = (__salt__['github.remove_team_member'] (member, name, profile=profile, **kwargs)) if result: extra_changes = ' due to MFA violation' if mfa_violation else '' ret['changes'][member] = { 'old': 'User {0} is in team {1}'.format(member, name), 'new': 'User {0} is not in team {1}{2}'.format(member, name, extra_changes) } else: ret['result'] = False ret['comment'] = ('Failed to remove user {0} from team {1}.' .format(member, name)) return ret if member_change: # Refresh team cache __salt__['github.list_team_members'](name, profile=profile, ignore_cache=False, **kwargs) if test_comments: ret['comment'] = '\n'.join(test_comments) return ret def _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa): if member_info.get('mfa_exempt', False): return False enforce_mfa_from = datetime.datetime.strptime( member_info.get('enforce_mfa_from', '1970/01/01'), '%Y/%m/%d') return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from) def team_absent(name, profile="github", **kwargs): ''' Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) if not target: ret['comment'] = 'Team {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Team {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_team'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted team {0}'.format(name) ret['changes'].setdefault('old', 'Team {0} exists'.format(name)) ret['changes'].setdefault('new', 'Team {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False return ret def repo_present( name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=False, gitignore_template=None, license_template=None, teams=None, profile="github", **kwargs): ''' Ensure a repository is present name This is the name of the repository. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". teams The teams for which this repo should belong to, specified as a dict of team name to permission ('pull', 'push' or 'admin'). .. versionadded:: 2017.7.0 Example: .. code-block:: yaml Ensure repo my-repo is present in github: github.repo_present: - name: 'my-repo' - description: 'My very important repository' .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } # This is an optimization to cache all repos in the organization up front. # The first use of this state will collect all of the repos and save a bunch # of API calls for future use. __salt__['github.list_repos'](profile=profile) try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } # Keep track of current_teams if we've fetched them after creating a new repo current_teams = None if target: # Repo already exists # Some params are only valid on repo creation ignore_params = ['auto_init', 'gitignore_template', 'license_template'] parameters = {} old_parameters = {} for param_name, param_value in six.iteritems(given_params): if (param_value is not None and param_name not in ignore_params and target[param_name] is not param_value and target[param_name] != param_value): parameters[param_name] = param_value old_parameters[param_name] = target[param_name] if parameters: repo_change = { 'old': 'Repo properties were {0}'.format(old_parameters), 'new': 'Repo properties (that changed) are {0}'.format(parameters) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: result = __salt__['github.edit_repo'](name, profile=profile, **parameters) if result: ret['changes']['repo'] = repo_change else: ret['result'] = False ret['comment'] = 'Failed to update repo properties.' return ret else: # Repo does not exist - it will be created. repo_change = { 'old': None, 'new': 'Repo {0} has been created'.format(name) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: add_params = dict(given_params) add_params.update(kwargs) result = __salt__['github.add_repo']( name, **add_params ) if not result: ret['result'] = False ret['comment'] = 'Failed to create repo {0}.'.format(name) return ret # Turns out that trying to fetch teams for a new repo can 404 immediately # after repo creation, so this waits until we can fetch teams successfully # before continuing. for attempt in range(3): time.sleep(1) try: current_teams = __salt__['github.get_repo_teams']( name, profile=profile, **kwargs) break except CommandExecutionError as e: log.info("Attempt %s to fetch new repo %s failed", attempt, name) if current_teams is None: ret['result'] = False ret['comment'] = 'Failed to verify repo {0} after creation.'.format(name) return ret ret['changes']['repo'] = repo_change if teams is not None: if __opts__['test'] and not target: # Assume no teams if we're in test mode and the repo doesn't exist current_teams = [] elif current_teams is None: current_teams = __salt__['github.get_repo_teams'](name, profile=profile) current_team_names = set([t['name'] for t in current_teams]) # First remove any teams that aren't present for team_name in current_team_names: if team_name not in teams: team_change = { 'old': 'Repo {0} is in team {1}'.format(name, team_name), 'new': 'Repo {0} is not in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.remove_team_repo'](name, team_name, profile=profile) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret # Next add or modify any necessary teams for team_name, permission in six.iteritems(teams): if team_name not in current_team_names: # Need to add repo to team team_change = { 'old': 'Repo {0} is not in team {1}'.format(name, team_name), 'new': 'Repo {0} is in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret else: current_permission = (__salt__['github.list_team_repos'] (team_name, profile=profile) .get(name.lower(), {}) .get('permission')) if not current_permission: ret['result'] = False ret['comment'] = ('Failed to determine current permission for team ' '{0} in repo {1}'.format(team_name, name)) return ret elif current_permission != permission: team_change = { 'old': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, current_permission)), 'new': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, permission)) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to set permission on repo {0} from ' 'team {1} to {2}.' .format(name, team_name, permission)) return ret return ret def repo_absent(name, profile="github", **kwargs): ''' Ensure a repo is absent. Example: .. code-block:: yaml ensure repo test is absent in github: github.repo_absent: - name: 'test' The following parameters are required: name This is the name of the repository in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None if not target: ret['comment'] = 'Repo {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Repo {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_repo'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted repo {0}'.format(name) ret['changes'].setdefault('old', 'Repo {0} exists'.format(name)) ret['changes'].setdefault('new', 'Repo {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = ('Failed to delete repo {0}. Ensure the delete_repo ' 'scope is enabled if using OAuth.'.format(name)) ret['result'] = False return ret
saltstack/salt
salt/states/github.py
team_present
python
def team_present( name, description=None, repo_names=None, privacy='secret', permission='pull', members=None, enforce_mfa=False, no_mfa_grace_seconds=0, profile="github", **kwargs): ''' Ensure a team is present name This is the name of the team in the organization. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. Defaults to secret. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. Defaults to pull. members The members belonging to the team, specified as a dict of member name to optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'. enforce_mfa Whether to enforce MFA requirements on members of the team. If True then all members without `mfa_exempt: True` configured will be removed from the team. Note that `no_mfa_grace_seconds` may be set to allow members a grace period. no_mfa_grace_seconds The number of seconds of grace time that a member will have to enable MFA before being removed from the team. The grace period will begin from `enforce_mfa_from` on the member configuration, which defaults to 1970/01/01. Example: .. code-block:: yaml Ensure team test is present in github: github.team_present: - name: 'test' - members: user1: {} user2: {} Ensure team test_mfa is present in github: github.team_present: - name: 'test_mfa' - members: user1: enforce_mfa_from: 2016/06/15 - enforce_mfa: True .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) test_comments = [] if target: # Team already exists parameters = {} if description is not None and target['description'] != description: parameters['description'] = description if permission is not None and target['permission'] != permission: parameters['permission'] = permission if privacy is not None and target['privacy'] != privacy: parameters['privacy'] = privacy if parameters: if __opts__['test']: test_comments.append('Team properties are set to be edited: {0}' .format(parameters)) ret['result'] = None else: result = __salt__['github.edit_team'](name, profile=profile, **parameters) if result: ret['changes']['team'] = { 'old': 'Team properties were {0}'.format(target), 'new': 'Team properties (that changed) are {0}'.format(parameters) } else: ret['result'] = False ret['comment'] = 'Failed to update team properties.' return ret manage_repos = repo_names is not None current_repos = set(__salt__['github.list_team_repos'](name, profile=profile) .keys()) repo_names = set(repo_names or []) repos_to_add = repo_names - current_repos repos_to_remove = current_repos - repo_names if repo_names else [] if repos_to_add: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'added: {1}.'.format(name, list(repos_to_add))) ret['result'] = None else: for repo_name in repos_to_add: result = (__salt__['github.add_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is not in team {1}'.format(repo_name, name), 'new': 'Repo {0} is in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to add repo {0} to team {1}.' .format(repo_name, name)) return ret if repos_to_remove: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'removed: {1}.'.format(name, list(repos_to_remove))) ret['result'] = None else: for repo_name in repos_to_remove: result = (__salt__['github.remove_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is in team {1}'.format(repo_name, name), 'new': 'Repo {0} is not in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(repo_name, name)) return ret else: # Team does not exist - it will be created. if __opts__['test']: ret['comment'] = 'Team {0} is set to be created.'.format(name) ret['result'] = None return ret result = __salt__['github.add_team']( name, description=description, repo_names=repo_names, permission=permission, privacy=privacy, profile=profile, **kwargs ) if result: ret['changes']['team'] = {} ret['changes']['team']['old'] = None ret['changes']['team']['new'] = 'Team {0} has been created'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to create team {0}.'.format(name) return ret manage_members = members is not None mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(seconds=no_mfa_grace_seconds) members_no_mfa = __salt__['github.list_members_without_mfa'](profile=profile) members_lower = {} for member_name, info in six.iteritems(members or {}): members_lower[member_name.lower()] = info member_change = False current_members = __salt__['github.list_team_members'](name, profile=profile) for member, member_info in six.iteritems(members or {}): log.info('Checking member %s in team %s', member, name) if member.lower() not in current_members: if (enforce_mfa and _member_violates_mfa(member, member_info, mfa_deadline, members_no_mfa)): if __opts__['test']: test_comments.append('User {0} will not be added to the ' 'team because they do not have MFA.' ''.format(member)) else: # Add to team member_change = True if __opts__['test']: test_comments.append('User {0} set to be added to the ' 'team.'.format(member)) ret['result'] = None else: result = (__salt__['github.add_team_member'] (member, name, profile=profile, **kwargs)) if result: ret['changes'][member] = {} ret['changes'][member]['old'] = ( 'User {0} is not in team {1}'.format(member, name)) ret['changes'][member]['new'] = ( 'User {0} is in team {1}'.format(member, name)) else: ret['result'] = False ret['comment'] = ('Failed to add user {0} to team ' '{1}.'.format(member, name)) return ret for member in current_members: mfa_violation = False if member in members_lower: mfa_violation = _member_violates_mfa(member, members_lower[member], mfa_deadline, members_no_mfa) if (manage_members and member not in members_lower or (enforce_mfa and mfa_violation)): # Remove from team member_change = True if __opts__['test']: if mfa_violation: test_comments.append('User {0} set to be removed from the ' 'team because they do not have MFA.' .format(member)) else: test_comments.append('User {0} set to be removed from ' 'the team.'.format(member)) ret['result'] = None else: result = (__salt__['github.remove_team_member'] (member, name, profile=profile, **kwargs)) if result: extra_changes = ' due to MFA violation' if mfa_violation else '' ret['changes'][member] = { 'old': 'User {0} is in team {1}'.format(member, name), 'new': 'User {0} is not in team {1}{2}'.format(member, name, extra_changes) } else: ret['result'] = False ret['comment'] = ('Failed to remove user {0} from team {1}.' .format(member, name)) return ret if member_change: # Refresh team cache __salt__['github.list_team_members'](name, profile=profile, ignore_cache=False, **kwargs) if test_comments: ret['comment'] = '\n'.join(test_comments) return ret
Ensure a team is present name This is the name of the team in the organization. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. Defaults to secret. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. Defaults to pull. members The members belonging to the team, specified as a dict of member name to optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'. enforce_mfa Whether to enforce MFA requirements on members of the team. If True then all members without `mfa_exempt: True` configured will be removed from the team. Note that `no_mfa_grace_seconds` may be set to allow members a grace period. no_mfa_grace_seconds The number of seconds of grace time that a member will have to enable MFA before being removed from the team. The grace period will begin from `enforce_mfa_from` on the member configuration, which defaults to 1970/01/01. Example: .. code-block:: yaml Ensure team test is present in github: github.team_present: - name: 'test' - members: user1: {} user2: {} Ensure team test_mfa is present in github: github.team_present: - name: 'test_mfa' - members: user1: enforce_mfa_from: 2016/06/15 - enforce_mfa: True .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/github.py#L154-L413
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa):\n if member_info.get('mfa_exempt', False):\n return False\n enforce_mfa_from = datetime.datetime.strptime(\n member_info.get('enforce_mfa_from', '1970/01/01'), '%Y/%m/%d')\n return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from)\n" ]
# -*- coding: utf-8 -*- ''' Github User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in the Organization. .. code-block:: yaml ensure user test is present in github: github.present: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import time import datetime import logging # Import Salt Libs from salt.ext import six from salt.exceptions import CommandExecutionError from salt.ext.six.moves import range log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the github module is available in __salt__ ''' return 'github' if 'github.list_users' in __salt__ else False def present(name, profile="github", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure user test is present in github: github.present: - name: 'gitexample' The following parameters are required: name This is the github handle of the user in the organization ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_user'](name, profile=profile, **kwargs) # If the user has a valid github handle and is not in the org already if not target: ret['result'] = False ret['comment'] = 'Couldnt find user {0}'.format(name) elif isinstance(target, bool) and target: ret['comment'] = 'User {0} is already in the org '.format(name) ret['result'] = True elif not target.get('in_org', False) and target.get('membership_state') != 'pending': if __opts__['test']: ret['comment'] = 'User {0} will be added to the org'.format(name) return ret # add the user result = __salt__['github.add_user']( name, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists in the org now'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to add user {0} to the org'.format(name) else: ret['comment'] = 'User {0} has already been invited.'.format(name) ret['result'] = True return ret def absent(name, profile="github", **kwargs): ''' Ensure a github user is absent .. code-block:: yaml ensure user test is absent in github: github.absent: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' The following parameters are required: name Github handle of the user in organization ''' email = kwargs.get('email') full_name = kwargs.get('fullname') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(name) } target = __salt__['github.get_user'](name, profile=profile, **kwargs) if target: if isinstance(target, bool) or target.get('in_org', False): if __opts__['test']: ret['comment'] = "User {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_user'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted user {0}'.format(name) ret['changes'].setdefault('old', 'User {0} exists'.format(name)) ret['changes'].setdefault('new', 'User {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False else: ret['comment'] = "User {0} has already been deleted!".format(name) ret['result'] = True else: ret['comment'] = 'User {0} does not exist'.format(name) ret['result'] = True return ret return ret def _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa): if member_info.get('mfa_exempt', False): return False enforce_mfa_from = datetime.datetime.strptime( member_info.get('enforce_mfa_from', '1970/01/01'), '%Y/%m/%d') return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from) def team_absent(name, profile="github", **kwargs): ''' Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) if not target: ret['comment'] = 'Team {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Team {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_team'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted team {0}'.format(name) ret['changes'].setdefault('old', 'Team {0} exists'.format(name)) ret['changes'].setdefault('new', 'Team {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False return ret def repo_present( name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=False, gitignore_template=None, license_template=None, teams=None, profile="github", **kwargs): ''' Ensure a repository is present name This is the name of the repository. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". teams The teams for which this repo should belong to, specified as a dict of team name to permission ('pull', 'push' or 'admin'). .. versionadded:: 2017.7.0 Example: .. code-block:: yaml Ensure repo my-repo is present in github: github.repo_present: - name: 'my-repo' - description: 'My very important repository' .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } # This is an optimization to cache all repos in the organization up front. # The first use of this state will collect all of the repos and save a bunch # of API calls for future use. __salt__['github.list_repos'](profile=profile) try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } # Keep track of current_teams if we've fetched them after creating a new repo current_teams = None if target: # Repo already exists # Some params are only valid on repo creation ignore_params = ['auto_init', 'gitignore_template', 'license_template'] parameters = {} old_parameters = {} for param_name, param_value in six.iteritems(given_params): if (param_value is not None and param_name not in ignore_params and target[param_name] is not param_value and target[param_name] != param_value): parameters[param_name] = param_value old_parameters[param_name] = target[param_name] if parameters: repo_change = { 'old': 'Repo properties were {0}'.format(old_parameters), 'new': 'Repo properties (that changed) are {0}'.format(parameters) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: result = __salt__['github.edit_repo'](name, profile=profile, **parameters) if result: ret['changes']['repo'] = repo_change else: ret['result'] = False ret['comment'] = 'Failed to update repo properties.' return ret else: # Repo does not exist - it will be created. repo_change = { 'old': None, 'new': 'Repo {0} has been created'.format(name) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: add_params = dict(given_params) add_params.update(kwargs) result = __salt__['github.add_repo']( name, **add_params ) if not result: ret['result'] = False ret['comment'] = 'Failed to create repo {0}.'.format(name) return ret # Turns out that trying to fetch teams for a new repo can 404 immediately # after repo creation, so this waits until we can fetch teams successfully # before continuing. for attempt in range(3): time.sleep(1) try: current_teams = __salt__['github.get_repo_teams']( name, profile=profile, **kwargs) break except CommandExecutionError as e: log.info("Attempt %s to fetch new repo %s failed", attempt, name) if current_teams is None: ret['result'] = False ret['comment'] = 'Failed to verify repo {0} after creation.'.format(name) return ret ret['changes']['repo'] = repo_change if teams is not None: if __opts__['test'] and not target: # Assume no teams if we're in test mode and the repo doesn't exist current_teams = [] elif current_teams is None: current_teams = __salt__['github.get_repo_teams'](name, profile=profile) current_team_names = set([t['name'] for t in current_teams]) # First remove any teams that aren't present for team_name in current_team_names: if team_name not in teams: team_change = { 'old': 'Repo {0} is in team {1}'.format(name, team_name), 'new': 'Repo {0} is not in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.remove_team_repo'](name, team_name, profile=profile) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret # Next add or modify any necessary teams for team_name, permission in six.iteritems(teams): if team_name not in current_team_names: # Need to add repo to team team_change = { 'old': 'Repo {0} is not in team {1}'.format(name, team_name), 'new': 'Repo {0} is in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret else: current_permission = (__salt__['github.list_team_repos'] (team_name, profile=profile) .get(name.lower(), {}) .get('permission')) if not current_permission: ret['result'] = False ret['comment'] = ('Failed to determine current permission for team ' '{0} in repo {1}'.format(team_name, name)) return ret elif current_permission != permission: team_change = { 'old': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, current_permission)), 'new': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, permission)) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to set permission on repo {0} from ' 'team {1} to {2}.' .format(name, team_name, permission)) return ret return ret def repo_absent(name, profile="github", **kwargs): ''' Ensure a repo is absent. Example: .. code-block:: yaml ensure repo test is absent in github: github.repo_absent: - name: 'test' The following parameters are required: name This is the name of the repository in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None if not target: ret['comment'] = 'Repo {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Repo {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_repo'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted repo {0}'.format(name) ret['changes'].setdefault('old', 'Repo {0} exists'.format(name)) ret['changes'].setdefault('new', 'Repo {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = ('Failed to delete repo {0}. Ensure the delete_repo ' 'scope is enabled if using OAuth.'.format(name)) ret['result'] = False return ret
saltstack/salt
salt/states/github.py
team_absent
python
def team_absent(name, profile="github", **kwargs): ''' Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) if not target: ret['comment'] = 'Team {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Team {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_team'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted team {0}'.format(name) ret['changes'].setdefault('old', 'Team {0} exists'.format(name)) ret['changes'].setdefault('new', 'Team {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False return ret
Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/github.py#L424-L473
null
# -*- coding: utf-8 -*- ''' Github User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in the Organization. .. code-block:: yaml ensure user test is present in github: github.present: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import time import datetime import logging # Import Salt Libs from salt.ext import six from salt.exceptions import CommandExecutionError from salt.ext.six.moves import range log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the github module is available in __salt__ ''' return 'github' if 'github.list_users' in __salt__ else False def present(name, profile="github", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure user test is present in github: github.present: - name: 'gitexample' The following parameters are required: name This is the github handle of the user in the organization ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_user'](name, profile=profile, **kwargs) # If the user has a valid github handle and is not in the org already if not target: ret['result'] = False ret['comment'] = 'Couldnt find user {0}'.format(name) elif isinstance(target, bool) and target: ret['comment'] = 'User {0} is already in the org '.format(name) ret['result'] = True elif not target.get('in_org', False) and target.get('membership_state') != 'pending': if __opts__['test']: ret['comment'] = 'User {0} will be added to the org'.format(name) return ret # add the user result = __salt__['github.add_user']( name, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists in the org now'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to add user {0} to the org'.format(name) else: ret['comment'] = 'User {0} has already been invited.'.format(name) ret['result'] = True return ret def absent(name, profile="github", **kwargs): ''' Ensure a github user is absent .. code-block:: yaml ensure user test is absent in github: github.absent: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' The following parameters are required: name Github handle of the user in organization ''' email = kwargs.get('email') full_name = kwargs.get('fullname') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(name) } target = __salt__['github.get_user'](name, profile=profile, **kwargs) if target: if isinstance(target, bool) or target.get('in_org', False): if __opts__['test']: ret['comment'] = "User {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_user'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted user {0}'.format(name) ret['changes'].setdefault('old', 'User {0} exists'.format(name)) ret['changes'].setdefault('new', 'User {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False else: ret['comment'] = "User {0} has already been deleted!".format(name) ret['result'] = True else: ret['comment'] = 'User {0} does not exist'.format(name) ret['result'] = True return ret return ret def team_present( name, description=None, repo_names=None, privacy='secret', permission='pull', members=None, enforce_mfa=False, no_mfa_grace_seconds=0, profile="github", **kwargs): ''' Ensure a team is present name This is the name of the team in the organization. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. Defaults to secret. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. Defaults to pull. members The members belonging to the team, specified as a dict of member name to optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'. enforce_mfa Whether to enforce MFA requirements on members of the team. If True then all members without `mfa_exempt: True` configured will be removed from the team. Note that `no_mfa_grace_seconds` may be set to allow members a grace period. no_mfa_grace_seconds The number of seconds of grace time that a member will have to enable MFA before being removed from the team. The grace period will begin from `enforce_mfa_from` on the member configuration, which defaults to 1970/01/01. Example: .. code-block:: yaml Ensure team test is present in github: github.team_present: - name: 'test' - members: user1: {} user2: {} Ensure team test_mfa is present in github: github.team_present: - name: 'test_mfa' - members: user1: enforce_mfa_from: 2016/06/15 - enforce_mfa: True .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) test_comments = [] if target: # Team already exists parameters = {} if description is not None and target['description'] != description: parameters['description'] = description if permission is not None and target['permission'] != permission: parameters['permission'] = permission if privacy is not None and target['privacy'] != privacy: parameters['privacy'] = privacy if parameters: if __opts__['test']: test_comments.append('Team properties are set to be edited: {0}' .format(parameters)) ret['result'] = None else: result = __salt__['github.edit_team'](name, profile=profile, **parameters) if result: ret['changes']['team'] = { 'old': 'Team properties were {0}'.format(target), 'new': 'Team properties (that changed) are {0}'.format(parameters) } else: ret['result'] = False ret['comment'] = 'Failed to update team properties.' return ret manage_repos = repo_names is not None current_repos = set(__salt__['github.list_team_repos'](name, profile=profile) .keys()) repo_names = set(repo_names or []) repos_to_add = repo_names - current_repos repos_to_remove = current_repos - repo_names if repo_names else [] if repos_to_add: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'added: {1}.'.format(name, list(repos_to_add))) ret['result'] = None else: for repo_name in repos_to_add: result = (__salt__['github.add_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is not in team {1}'.format(repo_name, name), 'new': 'Repo {0} is in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to add repo {0} to team {1}.' .format(repo_name, name)) return ret if repos_to_remove: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'removed: {1}.'.format(name, list(repos_to_remove))) ret['result'] = None else: for repo_name in repos_to_remove: result = (__salt__['github.remove_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is in team {1}'.format(repo_name, name), 'new': 'Repo {0} is not in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(repo_name, name)) return ret else: # Team does not exist - it will be created. if __opts__['test']: ret['comment'] = 'Team {0} is set to be created.'.format(name) ret['result'] = None return ret result = __salt__['github.add_team']( name, description=description, repo_names=repo_names, permission=permission, privacy=privacy, profile=profile, **kwargs ) if result: ret['changes']['team'] = {} ret['changes']['team']['old'] = None ret['changes']['team']['new'] = 'Team {0} has been created'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to create team {0}.'.format(name) return ret manage_members = members is not None mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(seconds=no_mfa_grace_seconds) members_no_mfa = __salt__['github.list_members_without_mfa'](profile=profile) members_lower = {} for member_name, info in six.iteritems(members or {}): members_lower[member_name.lower()] = info member_change = False current_members = __salt__['github.list_team_members'](name, profile=profile) for member, member_info in six.iteritems(members or {}): log.info('Checking member %s in team %s', member, name) if member.lower() not in current_members: if (enforce_mfa and _member_violates_mfa(member, member_info, mfa_deadline, members_no_mfa)): if __opts__['test']: test_comments.append('User {0} will not be added to the ' 'team because they do not have MFA.' ''.format(member)) else: # Add to team member_change = True if __opts__['test']: test_comments.append('User {0} set to be added to the ' 'team.'.format(member)) ret['result'] = None else: result = (__salt__['github.add_team_member'] (member, name, profile=profile, **kwargs)) if result: ret['changes'][member] = {} ret['changes'][member]['old'] = ( 'User {0} is not in team {1}'.format(member, name)) ret['changes'][member]['new'] = ( 'User {0} is in team {1}'.format(member, name)) else: ret['result'] = False ret['comment'] = ('Failed to add user {0} to team ' '{1}.'.format(member, name)) return ret for member in current_members: mfa_violation = False if member in members_lower: mfa_violation = _member_violates_mfa(member, members_lower[member], mfa_deadline, members_no_mfa) if (manage_members and member not in members_lower or (enforce_mfa and mfa_violation)): # Remove from team member_change = True if __opts__['test']: if mfa_violation: test_comments.append('User {0} set to be removed from the ' 'team because they do not have MFA.' .format(member)) else: test_comments.append('User {0} set to be removed from ' 'the team.'.format(member)) ret['result'] = None else: result = (__salt__['github.remove_team_member'] (member, name, profile=profile, **kwargs)) if result: extra_changes = ' due to MFA violation' if mfa_violation else '' ret['changes'][member] = { 'old': 'User {0} is in team {1}'.format(member, name), 'new': 'User {0} is not in team {1}{2}'.format(member, name, extra_changes) } else: ret['result'] = False ret['comment'] = ('Failed to remove user {0} from team {1}.' .format(member, name)) return ret if member_change: # Refresh team cache __salt__['github.list_team_members'](name, profile=profile, ignore_cache=False, **kwargs) if test_comments: ret['comment'] = '\n'.join(test_comments) return ret def _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa): if member_info.get('mfa_exempt', False): return False enforce_mfa_from = datetime.datetime.strptime( member_info.get('enforce_mfa_from', '1970/01/01'), '%Y/%m/%d') return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from) def repo_present( name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=False, gitignore_template=None, license_template=None, teams=None, profile="github", **kwargs): ''' Ensure a repository is present name This is the name of the repository. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". teams The teams for which this repo should belong to, specified as a dict of team name to permission ('pull', 'push' or 'admin'). .. versionadded:: 2017.7.0 Example: .. code-block:: yaml Ensure repo my-repo is present in github: github.repo_present: - name: 'my-repo' - description: 'My very important repository' .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } # This is an optimization to cache all repos in the organization up front. # The first use of this state will collect all of the repos and save a bunch # of API calls for future use. __salt__['github.list_repos'](profile=profile) try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } # Keep track of current_teams if we've fetched them after creating a new repo current_teams = None if target: # Repo already exists # Some params are only valid on repo creation ignore_params = ['auto_init', 'gitignore_template', 'license_template'] parameters = {} old_parameters = {} for param_name, param_value in six.iteritems(given_params): if (param_value is not None and param_name not in ignore_params and target[param_name] is not param_value and target[param_name] != param_value): parameters[param_name] = param_value old_parameters[param_name] = target[param_name] if parameters: repo_change = { 'old': 'Repo properties were {0}'.format(old_parameters), 'new': 'Repo properties (that changed) are {0}'.format(parameters) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: result = __salt__['github.edit_repo'](name, profile=profile, **parameters) if result: ret['changes']['repo'] = repo_change else: ret['result'] = False ret['comment'] = 'Failed to update repo properties.' return ret else: # Repo does not exist - it will be created. repo_change = { 'old': None, 'new': 'Repo {0} has been created'.format(name) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: add_params = dict(given_params) add_params.update(kwargs) result = __salt__['github.add_repo']( name, **add_params ) if not result: ret['result'] = False ret['comment'] = 'Failed to create repo {0}.'.format(name) return ret # Turns out that trying to fetch teams for a new repo can 404 immediately # after repo creation, so this waits until we can fetch teams successfully # before continuing. for attempt in range(3): time.sleep(1) try: current_teams = __salt__['github.get_repo_teams']( name, profile=profile, **kwargs) break except CommandExecutionError as e: log.info("Attempt %s to fetch new repo %s failed", attempt, name) if current_teams is None: ret['result'] = False ret['comment'] = 'Failed to verify repo {0} after creation.'.format(name) return ret ret['changes']['repo'] = repo_change if teams is not None: if __opts__['test'] and not target: # Assume no teams if we're in test mode and the repo doesn't exist current_teams = [] elif current_teams is None: current_teams = __salt__['github.get_repo_teams'](name, profile=profile) current_team_names = set([t['name'] for t in current_teams]) # First remove any teams that aren't present for team_name in current_team_names: if team_name not in teams: team_change = { 'old': 'Repo {0} is in team {1}'.format(name, team_name), 'new': 'Repo {0} is not in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.remove_team_repo'](name, team_name, profile=profile) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret # Next add or modify any necessary teams for team_name, permission in six.iteritems(teams): if team_name not in current_team_names: # Need to add repo to team team_change = { 'old': 'Repo {0} is not in team {1}'.format(name, team_name), 'new': 'Repo {0} is in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret else: current_permission = (__salt__['github.list_team_repos'] (team_name, profile=profile) .get(name.lower(), {}) .get('permission')) if not current_permission: ret['result'] = False ret['comment'] = ('Failed to determine current permission for team ' '{0} in repo {1}'.format(team_name, name)) return ret elif current_permission != permission: team_change = { 'old': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, current_permission)), 'new': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, permission)) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to set permission on repo {0} from ' 'team {1} to {2}.' .format(name, team_name, permission)) return ret return ret def repo_absent(name, profile="github", **kwargs): ''' Ensure a repo is absent. Example: .. code-block:: yaml ensure repo test is absent in github: github.repo_absent: - name: 'test' The following parameters are required: name This is the name of the repository in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None if not target: ret['comment'] = 'Repo {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Repo {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_repo'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted repo {0}'.format(name) ret['changes'].setdefault('old', 'Repo {0} exists'.format(name)) ret['changes'].setdefault('new', 'Repo {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = ('Failed to delete repo {0}. Ensure the delete_repo ' 'scope is enabled if using OAuth.'.format(name)) ret['result'] = False return ret
saltstack/salt
salt/states/github.py
repo_present
python
def repo_present( name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=False, gitignore_template=None, license_template=None, teams=None, profile="github", **kwargs): ''' Ensure a repository is present name This is the name of the repository. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". teams The teams for which this repo should belong to, specified as a dict of team name to permission ('pull', 'push' or 'admin'). .. versionadded:: 2017.7.0 Example: .. code-block:: yaml Ensure repo my-repo is present in github: github.repo_present: - name: 'my-repo' - description: 'My very important repository' .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } # This is an optimization to cache all repos in the organization up front. # The first use of this state will collect all of the repos and save a bunch # of API calls for future use. __salt__['github.list_repos'](profile=profile) try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } # Keep track of current_teams if we've fetched them after creating a new repo current_teams = None if target: # Repo already exists # Some params are only valid on repo creation ignore_params = ['auto_init', 'gitignore_template', 'license_template'] parameters = {} old_parameters = {} for param_name, param_value in six.iteritems(given_params): if (param_value is not None and param_name not in ignore_params and target[param_name] is not param_value and target[param_name] != param_value): parameters[param_name] = param_value old_parameters[param_name] = target[param_name] if parameters: repo_change = { 'old': 'Repo properties were {0}'.format(old_parameters), 'new': 'Repo properties (that changed) are {0}'.format(parameters) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: result = __salt__['github.edit_repo'](name, profile=profile, **parameters) if result: ret['changes']['repo'] = repo_change else: ret['result'] = False ret['comment'] = 'Failed to update repo properties.' return ret else: # Repo does not exist - it will be created. repo_change = { 'old': None, 'new': 'Repo {0} has been created'.format(name) } if __opts__['test']: ret['changes']['repo'] = repo_change ret['result'] = None else: add_params = dict(given_params) add_params.update(kwargs) result = __salt__['github.add_repo']( name, **add_params ) if not result: ret['result'] = False ret['comment'] = 'Failed to create repo {0}.'.format(name) return ret # Turns out that trying to fetch teams for a new repo can 404 immediately # after repo creation, so this waits until we can fetch teams successfully # before continuing. for attempt in range(3): time.sleep(1) try: current_teams = __salt__['github.get_repo_teams']( name, profile=profile, **kwargs) break except CommandExecutionError as e: log.info("Attempt %s to fetch new repo %s failed", attempt, name) if current_teams is None: ret['result'] = False ret['comment'] = 'Failed to verify repo {0} after creation.'.format(name) return ret ret['changes']['repo'] = repo_change if teams is not None: if __opts__['test'] and not target: # Assume no teams if we're in test mode and the repo doesn't exist current_teams = [] elif current_teams is None: current_teams = __salt__['github.get_repo_teams'](name, profile=profile) current_team_names = set([t['name'] for t in current_teams]) # First remove any teams that aren't present for team_name in current_team_names: if team_name not in teams: team_change = { 'old': 'Repo {0} is in team {1}'.format(name, team_name), 'new': 'Repo {0} is not in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.remove_team_repo'](name, team_name, profile=profile) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret # Next add or modify any necessary teams for team_name, permission in six.iteritems(teams): if team_name not in current_team_names: # Need to add repo to team team_change = { 'old': 'Repo {0} is not in team {1}'.format(name, team_name), 'new': 'Repo {0} is in team {1}'.format(name, team_name) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(name, team_name)) return ret else: current_permission = (__salt__['github.list_team_repos'] (team_name, profile=profile) .get(name.lower(), {}) .get('permission')) if not current_permission: ret['result'] = False ret['comment'] = ('Failed to determine current permission for team ' '{0} in repo {1}'.format(team_name, name)) return ret elif current_permission != permission: team_change = { 'old': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, current_permission)), 'new': ('Repo {0} in team {1} has permission {2}' .format(name, team_name, permission)) } if __opts__['test']: ret['changes'][team_name] = team_change ret['result'] = None else: result = __salt__['github.add_team_repo'](name, team_name, profile=profile, permission=permission) if result: ret['changes'][team_name] = team_change else: ret['result'] = False ret['comment'] = ('Failed to set permission on repo {0} from ' 'team {1} to {2}.' .format(name, team_name, permission)) return ret return ret
Ensure a repository is present name This is the name of the repository. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". teams The teams for which this repo should belong to, specified as a dict of team name to permission ('pull', 'push' or 'admin'). .. versionadded:: 2017.7.0 Example: .. code-block:: yaml Ensure repo my-repo is present in github: github.repo_present: - name: 'my-repo' - description: 'My very important repository' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/github.py#L476-L728
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' Github User State Module .. versionadded:: 2016.3.0. This state is used to ensure presence of users in the Organization. .. code-block:: yaml ensure user test is present in github: github.present: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import time import datetime import logging # Import Salt Libs from salt.ext import six from salt.exceptions import CommandExecutionError from salt.ext.six.moves import range log = logging.getLogger(__name__) def __virtual__(): ''' Only load if the github module is available in __salt__ ''' return 'github' if 'github.list_users' in __salt__ else False def present(name, profile="github", **kwargs): ''' Ensure a user is present .. code-block:: yaml ensure user test is present in github: github.present: - name: 'gitexample' The following parameters are required: name This is the github handle of the user in the organization ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_user'](name, profile=profile, **kwargs) # If the user has a valid github handle and is not in the org already if not target: ret['result'] = False ret['comment'] = 'Couldnt find user {0}'.format(name) elif isinstance(target, bool) and target: ret['comment'] = 'User {0} is already in the org '.format(name) ret['result'] = True elif not target.get('in_org', False) and target.get('membership_state') != 'pending': if __opts__['test']: ret['comment'] = 'User {0} will be added to the org'.format(name) return ret # add the user result = __salt__['github.add_user']( name, profile=profile, **kwargs ) if result: ret['changes'].setdefault('old', None) ret['changes'].setdefault('new', 'User {0} exists in the org now'.format(name)) ret['result'] = True else: ret['result'] = False ret['comment'] = 'Failed to add user {0} to the org'.format(name) else: ret['comment'] = 'User {0} has already been invited.'.format(name) ret['result'] = True return ret def absent(name, profile="github", **kwargs): ''' Ensure a github user is absent .. code-block:: yaml ensure user test is absent in github: github.absent: - name: 'Example TestUser1' - email: example@domain.com - username: 'gitexample' The following parameters are required: name Github handle of the user in organization ''' email = kwargs.get('email') full_name = kwargs.get('fullname') ret = { 'name': name, 'changes': {}, 'result': None, 'comment': 'User {0} is absent.'.format(name) } target = __salt__['github.get_user'](name, profile=profile, **kwargs) if target: if isinstance(target, bool) or target.get('in_org', False): if __opts__['test']: ret['comment'] = "User {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_user'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted user {0}'.format(name) ret['changes'].setdefault('old', 'User {0} exists'.format(name)) ret['changes'].setdefault('new', 'User {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False else: ret['comment'] = "User {0} has already been deleted!".format(name) ret['result'] = True else: ret['comment'] = 'User {0} does not exist'.format(name) ret['result'] = True return ret return ret def team_present( name, description=None, repo_names=None, privacy='secret', permission='pull', members=None, enforce_mfa=False, no_mfa_grace_seconds=0, profile="github", **kwargs): ''' Ensure a team is present name This is the name of the team in the organization. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. Defaults to secret. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. Defaults to pull. members The members belonging to the team, specified as a dict of member name to optional configuration. Options include 'enforce_mfa_from' and 'mfa_exempt'. enforce_mfa Whether to enforce MFA requirements on members of the team. If True then all members without `mfa_exempt: True` configured will be removed from the team. Note that `no_mfa_grace_seconds` may be set to allow members a grace period. no_mfa_grace_seconds The number of seconds of grace time that a member will have to enable MFA before being removed from the team. The grace period will begin from `enforce_mfa_from` on the member configuration, which defaults to 1970/01/01. Example: .. code-block:: yaml Ensure team test is present in github: github.team_present: - name: 'test' - members: user1: {} user2: {} Ensure team test_mfa is present in github: github.team_present: - name: 'test_mfa' - members: user1: enforce_mfa_from: 2016/06/15 - enforce_mfa: True .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': True, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) test_comments = [] if target: # Team already exists parameters = {} if description is not None and target['description'] != description: parameters['description'] = description if permission is not None and target['permission'] != permission: parameters['permission'] = permission if privacy is not None and target['privacy'] != privacy: parameters['privacy'] = privacy if parameters: if __opts__['test']: test_comments.append('Team properties are set to be edited: {0}' .format(parameters)) ret['result'] = None else: result = __salt__['github.edit_team'](name, profile=profile, **parameters) if result: ret['changes']['team'] = { 'old': 'Team properties were {0}'.format(target), 'new': 'Team properties (that changed) are {0}'.format(parameters) } else: ret['result'] = False ret['comment'] = 'Failed to update team properties.' return ret manage_repos = repo_names is not None current_repos = set(__salt__['github.list_team_repos'](name, profile=profile) .keys()) repo_names = set(repo_names or []) repos_to_add = repo_names - current_repos repos_to_remove = current_repos - repo_names if repo_names else [] if repos_to_add: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'added: {1}.'.format(name, list(repos_to_add))) ret['result'] = None else: for repo_name in repos_to_add: result = (__salt__['github.add_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is not in team {1}'.format(repo_name, name), 'new': 'Repo {0} is in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to add repo {0} to team {1}.' .format(repo_name, name)) return ret if repos_to_remove: if __opts__['test']: test_comments.append('Team {0} will have the following repos ' 'removed: {1}.'.format(name, list(repos_to_remove))) ret['result'] = None else: for repo_name in repos_to_remove: result = (__salt__['github.remove_team_repo'] (repo_name, name, profile=profile, **kwargs)) if result: ret['changes'][repo_name] = { 'old': 'Repo {0} is in team {1}'.format(repo_name, name), 'new': 'Repo {0} is not in team {1}'.format(repo_name, name) } else: ret['result'] = False ret['comment'] = ('Failed to remove repo {0} from team {1}.' .format(repo_name, name)) return ret else: # Team does not exist - it will be created. if __opts__['test']: ret['comment'] = 'Team {0} is set to be created.'.format(name) ret['result'] = None return ret result = __salt__['github.add_team']( name, description=description, repo_names=repo_names, permission=permission, privacy=privacy, profile=profile, **kwargs ) if result: ret['changes']['team'] = {} ret['changes']['team']['old'] = None ret['changes']['team']['new'] = 'Team {0} has been created'.format(name) else: ret['result'] = False ret['comment'] = 'Failed to create team {0}.'.format(name) return ret manage_members = members is not None mfa_deadline = datetime.datetime.utcnow() - datetime.timedelta(seconds=no_mfa_grace_seconds) members_no_mfa = __salt__['github.list_members_without_mfa'](profile=profile) members_lower = {} for member_name, info in six.iteritems(members or {}): members_lower[member_name.lower()] = info member_change = False current_members = __salt__['github.list_team_members'](name, profile=profile) for member, member_info in six.iteritems(members or {}): log.info('Checking member %s in team %s', member, name) if member.lower() not in current_members: if (enforce_mfa and _member_violates_mfa(member, member_info, mfa_deadline, members_no_mfa)): if __opts__['test']: test_comments.append('User {0} will not be added to the ' 'team because they do not have MFA.' ''.format(member)) else: # Add to team member_change = True if __opts__['test']: test_comments.append('User {0} set to be added to the ' 'team.'.format(member)) ret['result'] = None else: result = (__salt__['github.add_team_member'] (member, name, profile=profile, **kwargs)) if result: ret['changes'][member] = {} ret['changes'][member]['old'] = ( 'User {0} is not in team {1}'.format(member, name)) ret['changes'][member]['new'] = ( 'User {0} is in team {1}'.format(member, name)) else: ret['result'] = False ret['comment'] = ('Failed to add user {0} to team ' '{1}.'.format(member, name)) return ret for member in current_members: mfa_violation = False if member in members_lower: mfa_violation = _member_violates_mfa(member, members_lower[member], mfa_deadline, members_no_mfa) if (manage_members and member not in members_lower or (enforce_mfa and mfa_violation)): # Remove from team member_change = True if __opts__['test']: if mfa_violation: test_comments.append('User {0} set to be removed from the ' 'team because they do not have MFA.' .format(member)) else: test_comments.append('User {0} set to be removed from ' 'the team.'.format(member)) ret['result'] = None else: result = (__salt__['github.remove_team_member'] (member, name, profile=profile, **kwargs)) if result: extra_changes = ' due to MFA violation' if mfa_violation else '' ret['changes'][member] = { 'old': 'User {0} is in team {1}'.format(member, name), 'new': 'User {0} is not in team {1}{2}'.format(member, name, extra_changes) } else: ret['result'] = False ret['comment'] = ('Failed to remove user {0} from team {1}.' .format(member, name)) return ret if member_change: # Refresh team cache __salt__['github.list_team_members'](name, profile=profile, ignore_cache=False, **kwargs) if test_comments: ret['comment'] = '\n'.join(test_comments) return ret def _member_violates_mfa(member, member_info, mfa_deadline, members_without_mfa): if member_info.get('mfa_exempt', False): return False enforce_mfa_from = datetime.datetime.strptime( member_info.get('enforce_mfa_from', '1970/01/01'), '%Y/%m/%d') return member.lower() in members_without_mfa and (mfa_deadline > enforce_mfa_from) def team_absent(name, profile="github", **kwargs): ''' Ensure a team is absent. Example: .. code-block:: yaml ensure team test is present in github: github.team_absent: - name: 'test' The following parameters are required: name This is the name of the team in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } target = __salt__['github.get_team'](name, profile=profile, **kwargs) if not target: ret['comment'] = 'Team {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Team {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_team'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted team {0}'.format(name) ret['changes'].setdefault('old', 'Team {0} exists'.format(name)) ret['changes'].setdefault('new', 'Team {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = 'Failed to delete {0}'.format(name) ret['result'] = False return ret def repo_absent(name, profile="github", **kwargs): ''' Ensure a repo is absent. Example: .. code-block:: yaml ensure repo test is absent in github: github.repo_absent: - name: 'test' The following parameters are required: name This is the name of the repository in the organization. .. versionadded:: 2016.11.0 ''' ret = { 'name': name, 'changes': {}, 'result': None, 'comment': '' } try: target = __salt__['github.get_repo_info'](name, profile=profile, **kwargs) except CommandExecutionError: target = None if not target: ret['comment'] = 'Repo {0} does not exist'.format(name) ret['result'] = True return ret else: if __opts__['test']: ret['comment'] = "Repo {0} will be deleted".format(name) ret['result'] = None return ret result = __salt__['github.remove_repo'](name, profile=profile, **kwargs) if result: ret['comment'] = 'Deleted repo {0}'.format(name) ret['changes'].setdefault('old', 'Repo {0} exists'.format(name)) ret['changes'].setdefault('new', 'Repo {0} deleted'.format(name)) ret['result'] = True else: ret['comment'] = ('Failed to delete repo {0}. Ensure the delete_repo ' 'scope is enabled if using OAuth.'.format(name)) ret['result'] = False return ret
saltstack/salt
salt/roster/dir.py
targets
python
def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the directory of flat yaml files, checks opts for location. ''' roster_dir = __opts__.get('roster_dir', '/etc/salt/roster.d') # Match the targets before rendering to avoid opening files unnecessarily. raw = dict.fromkeys(os.listdir(roster_dir), '') log.debug('Filtering %d minions in %s', len(raw), roster_dir) matched_raw = __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4') rendered = {minion_id: _render(os.path.join(roster_dir, minion_id), **kwargs) for minion_id in matched_raw} pruned_rendered = {id_: data for id_, data in rendered.items() if data} log.debug('Matched %d minions with tgt=%s and tgt_type=%s.' ' Discarded %d matching filenames because they had rendering errors.', len(rendered), tgt, tgt_type, len(rendered) - len(pruned_rendered)) return pruned_rendered
Return the targets from the directory of flat yaml files, checks opts for location.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/dir.py#L63-L79
null
# -*- coding: utf-8 -*- ''' Create a salt roster out of a flat directory of files. Each filename in the directory is a minion id. The contents of each file is rendered using the salt renderer system. Consider the following configuration for example: config/master: ... roster: dir roster_dir: config/roster.d ... Where the directory config/roster.d contains two files: config/roster.d/minion-x: host: minion-x.example.com port: 22 sudo: true user: ubuntu config/roster.d/minion-y: host: minion-y.example.com port: 22 sudo: true user: gentoo The roster would find two minions: minion-x and minion-y, with the given host, port, sudo and user settings. The directory roster also extends the concept of roster defaults by supporting a roster_domain value in config: ... roster_domain: example.org ... If that option is set, then any roster without a 'host' setting will have an implicit host of its minion id + '.' + the roster_domain. (The default roster_domain is the empty string, so you can also name the files the fully qualified name of each host. However, if you do that, then the fully qualified name of each host is also the minion id.) This makes it possible to avoid having to specify the hostnames when you always want them to match their minion id plus some domain. ''' from __future__ import absolute_import, unicode_literals # Import python libs import logging import os # Import Salt libs import salt.loader import salt.template log = logging.getLogger(__name__) def _render(roster_file, **kwargs): """ Render the roster file """ renderers = salt.loader.render(__opts__, {}) domain = __opts__.get('roster_domain', '') try: result = salt.template.compile_template(roster_file, renderers, __opts__['renderer'], __opts__['renderer_blacklist'], __opts__['renderer_whitelist'], mask_value='passw*', **kwargs) result.setdefault('host', '{}.{}'.format(os.path.basename(roster_file), domain)) return result except: # pylint: disable=W0702 log.warning('Unable to render roster file "%s".', roster_file, exc_info=True) return {}
saltstack/salt
salt/roster/dir.py
_render
python
def _render(roster_file, **kwargs): renderers = salt.loader.render(__opts__, {}) domain = __opts__.get('roster_domain', '') try: result = salt.template.compile_template(roster_file, renderers, __opts__['renderer'], __opts__['renderer_blacklist'], __opts__['renderer_whitelist'], mask_value='passw*', **kwargs) result.setdefault('host', '{}.{}'.format(os.path.basename(roster_file), domain)) return result except: # pylint: disable=W0702 log.warning('Unable to render roster file "%s".', roster_file, exc_info=True) return {}
Render the roster file
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/dir.py#L82-L100
[ "def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Create a salt roster out of a flat directory of files. Each filename in the directory is a minion id. The contents of each file is rendered using the salt renderer system. Consider the following configuration for example: config/master: ... roster: dir roster_dir: config/roster.d ... Where the directory config/roster.d contains two files: config/roster.d/minion-x: host: minion-x.example.com port: 22 sudo: true user: ubuntu config/roster.d/minion-y: host: minion-y.example.com port: 22 sudo: true user: gentoo The roster would find two minions: minion-x and minion-y, with the given host, port, sudo and user settings. The directory roster also extends the concept of roster defaults by supporting a roster_domain value in config: ... roster_domain: example.org ... If that option is set, then any roster without a 'host' setting will have an implicit host of its minion id + '.' + the roster_domain. (The default roster_domain is the empty string, so you can also name the files the fully qualified name of each host. However, if you do that, then the fully qualified name of each host is also the minion id.) This makes it possible to avoid having to specify the hostnames when you always want them to match their minion id plus some domain. ''' from __future__ import absolute_import, unicode_literals # Import python libs import logging import os # Import Salt libs import salt.loader import salt.template log = logging.getLogger(__name__) def targets(tgt, tgt_type='glob', **kwargs): ''' Return the targets from the directory of flat yaml files, checks opts for location. ''' roster_dir = __opts__.get('roster_dir', '/etc/salt/roster.d') # Match the targets before rendering to avoid opening files unnecessarily. raw = dict.fromkeys(os.listdir(roster_dir), '') log.debug('Filtering %d minions in %s', len(raw), roster_dir) matched_raw = __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4') rendered = {minion_id: _render(os.path.join(roster_dir, minion_id), **kwargs) for minion_id in matched_raw} pruned_rendered = {id_: data for id_, data in rendered.items() if data} log.debug('Matched %d minions with tgt=%s and tgt_type=%s.' ' Discarded %d matching filenames because they had rendering errors.', len(rendered), tgt, tgt_type, len(rendered) - len(pruned_rendered)) return pruned_rendered
saltstack/salt
salt/modules/disk.py
_parse_numbers
python
def _parse_numbers(text): ''' Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return decimal.Decimal(text) try: postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'} if text[-1] in postPrefixes.keys(): v = decimal.Decimal(text[:-1]) v = v * decimal.Decimal(postPrefixes[text[-1]]) return v else: return decimal.Decimal(text) except ValueError: return text
Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L45-L63
null
# -*- coding: utf-8 -*- ''' Module for managing disks and blockdevices ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os import subprocess import re import collections import decimal # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # Import salt libs import salt.utils.decorators import salt.utils.decorators.path import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError __func_alias__ = { 'format_': 'format' } log = logging.getLogger(__name__) HAS_HDPARM = salt.utils.path.which('hdparm') is not None HAS_IOSTAT = salt.utils.path.which('iostat') is not None def __virtual__(): ''' Only work on POSIX-like systems ''' if salt.utils.platform.is_windows(): return False, 'This module doesn\'t work on Windows.' return True def _clean_flags(args, caller): ''' Sanitize flags passed into df ''' flags = '' if args is None: return flags allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: raise CommandExecutionError( 'Invalid flag passed to {0}'.format(caller) ) return flags def usage(args=None): ''' Return usage information for volumes mounted on this minion .. versionchanged:: 2019.2.0 Default for SunOS changed to 1 kilobyte blocks CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = _clean_flags(args, 'disk.usage') if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux': log.error('df cannot run without /etc/mtab') if __grains__.get('virtual_subtype') == 'LXC': log.error('df command failed and LXC detected. If you are running ' 'a Docker container, consider linking /proc/mounts to ' '/etc/mtab or consider running Docker with -privileged') return {} if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' elif __grains__['kernel'] == 'SunOS': cmd = 'df -k' else: cmd = 'df' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() oldline = None for line in out: if not line: continue if line.startswith('Filesystem'): continue if oldline: line = oldline + " " + line comps = line.split() if len(comps) == 1: oldline = line continue else: oldline = None while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.error('Problem parsing disk usage information') ret = {} return ret def inodeusage(args=None): ''' Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage ''' flags = _clean_flags(args, 'disk.inodeusage') if __grains__['kernel'] == 'AIX': cmd = 'df -i' else: cmd = 'df -iP' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if line.startswith('Filesystem'): continue comps = line.split() # Don't choke on empty lines if not comps: continue try: if __grains__['kernel'] == 'OpenBSD': ret[comps[8]] = { 'inodes': int(comps[5]) + int(comps[6]), 'used': comps[5], 'free': comps[6], 'use': comps[7], 'filesystem': comps[0], } elif __grains__['kernel'] == 'AIX': ret[comps[6]] = { 'inodes': comps[4], 'used': comps[5], 'free': comps[2], 'use': comps[5], 'filesystem': comps[0], } else: ret[comps[5]] = { 'inodes': comps[1], 'used': comps[2], 'free': comps[3], 'use': comps[4], 'filesystem': comps[0], } except (IndexError, ValueError): log.error('Problem parsing inode usage information') ret = {} return ret def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' else: cmd = 'df' ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = comps[4] else: ret[comps[5]] = comps[4] except IndexError: log.error('Problem parsing disk usage information') ret = {} if args and args not in ret: log.error( 'Problem parsing disk usage information: Partition \'%s\' ' 'does not exist!', args ) ret = {} elif args: return ret[args] return ret @salt.utils.decorators.path.which('blkid') def blkid(device=None, token=None): ''' Return block device attributes: UUID, LABEL, etc. This function only works on systems where blkid is available. device Device name from the system token Any valid token used for the search CLI Example: .. code-block:: bash salt '*' disk.blkid salt '*' disk.blkid /dev/sda salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d' salt '*' disk.blkid token='TYPE=ext4' ''' cmd = ['blkid'] if device: cmd.append(device) elif token: cmd.extend(['-t', token]) ret = {} blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False) if blkid_result['retcode'] > 0: return ret for line in blkid_result['stdout'].splitlines(): if not line: continue comps = line.split() device = comps[0][:-1] info = {} device_attributes = re.split(('\"*\"'), line.partition(' ')[2]) for key, value in zip(*[iter(device_attributes)]*2): key = key.strip('=').strip(' ') info[key] = value.strip('"') ret[device] = info return ret def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(8)`` manpage for a more complete description of these options. ''' kwarg_map = {'read-ahead': 'setra', 'filesystem-read-ahead': 'setfra', 'read-only': 'setro', 'read-write': 'setrw'} opts = '' args = [] for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if key != 'read-write': args.append(switch.replace('set', 'get')) else: args.append('getro') if kwargs[key] == 'True' or kwargs[key] is True: opts += '--{0} '.format(key) else: opts += '--{0} {1} '.format(switch, kwargs[key]) cmd = 'blockdev {0}{1}'.format(opts, device) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() return dump(device, args) def wipe(device): ''' Remove the filesystem information CLI Example: .. code-block:: bash salt '*' disk.wipe /dev/sda1 ''' cmd = 'wipefs -a {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True else: log.error('Error wiping device %s: %s', device, out['stderr']) return False def dump(device, args=None): ''' Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' disk.dump /dev/sda1 ''' cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \ '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device) ret = {} opts = [c[2:] for c in cmd.split() if c.startswith('--')] out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode'] == 0: lines = [line for line in out['stdout'].splitlines() if line] count = 0 for line in lines: ret[opts[count]] = line count = count+1 if args: temp_ret = {} for arg in args: temp_ret[arg] = ret[arg] return temp_ret else: return ret else: return False def resize2fs(device): ''' Resizes the filesystem. CLI Example: .. code-block:: bash salt '*' disk.resize2fs /dev/sda1 ''' cmd = 'resize2fs {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True @salt.utils.decorators.path.which('sync') @salt.utils.decorators.path.which('mkfs') def format_(device, fs_type='ext4', inode_size=None, lazy_itable_init=None, fat=None, force=False): ''' Format a filesystem onto a device .. versionadded:: 2016.11.0 device The device in which to create the new filesystem fs_type The type of filesystem to create inode_size Size of the inodes This option is only enabled for ext and xfs filesystems lazy_itable_init If enabled and the uninit_bg feature is enabled, the inode table will not be fully initialized by mke2fs. This speeds up filesystem initialization noticeably, but it requires the kernel to finish initializing the filesystem in the background when the filesystem is first mounted. If the option value is omitted, it defaults to 1 to enable lazy inode table zeroing. This option is only enabled for ext filesystems fat FAT size option. Can be 12, 16 or 32, and can only be used on fat or vfat filesystems. force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. CLI Example: .. code-block:: bash salt '*' disk.format /dev/sdX1 ''' cmd = ['mkfs', '-t', six.text_type(fs_type)] if inode_size is not None: if fs_type[:3] == 'ext': cmd.extend(['-i', six.text_type(inode_size)]) elif fs_type == 'xfs': cmd.extend(['-i', 'size={0}'.format(inode_size)]) if lazy_itable_init is not None: if fs_type[:3] == 'ext': cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)]) if fat is not None and fat in (12, 16, 32): if fs_type[-3:] == 'fat': cmd.extend(['-F', fat]) if force: if fs_type[:3] == 'ext': cmd.append('-F') elif fs_type == 'xfs': cmd.append('-f') cmd.append(six.text_type(device)) mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0 sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0 return all([mkfs_success, sync_success]) @salt.utils.decorators.path.which_bin(['lsblk', 'df']) def fstype(device): ''' Return the filesystem name of the specified device .. versionadded:: 2016.11.0 device The name of the device CLI Example: .. code-block:: bash salt '*' disk.fstype /dev/sdX1 ''' if salt.utils.path.which('lsblk'): lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines() if len(lsblk_out) > 1: fs_type = lsblk_out[1].strip() if fs_type: return fs_type if salt.utils.path.which('df'): # the fstype was not set on the block device, so inspect the filesystem # itself for its type if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'): df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split() if len(df_out) > 2: fs_type = df_out[2] if fs_type: return fs_type else: df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines() if len(df_out) > 1: fs_type = df_out[1] if fs_type: return fs_type return '' @salt.utils.decorators.depends(HAS_HDPARM) def _hdparm(args, failhard=True): ''' Execute hdparm Fail hard when required return output when possible ''' cmd = 'hdparm {0}'.format(args) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: msg = '{0}: {1}'.format(cmd, result['stderr']) if failhard: raise CommandExecutionError(msg) else: log.warning(msg) return result['stdout'] @salt.utils.decorators.depends(HAS_HDPARM) def hdparms(disks, args=None): ''' Retrieve all info's for all disks parse 'em into a nice dict (which, considering hdparms output, is quite a hassle) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hdparms /dev/sda ''' all_parms = 'aAbBcCdgHiJkMmNnQrRuW' if args is None: args = all_parms elif isinstance(args, (list, tuple)): args = ''.join(args) if not isinstance(disks, (list, tuple)): disks = [disks] out = {} for disk in disks: if not disk.startswith('/dev'): disk = '/dev/{0}'.format(disk) disk_data = {} for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines(): line = line.strip() if not line or line == disk + ':': continue if ':' in line: key, vals = line.split(':', 1) key = re.sub(r' is$', '', key) elif '=' in line: key, vals = line.split('=', 1) else: continue key = key.strip().lower().replace(' ', '_') vals = vals.strip() rvals = [] if re.match(r'[0-9]+ \(.*\)', vals): vals = vals.split(' ') rvals.append(int(vals[0])) rvals.append(vals[1].strip('()')) else: valdict = {} for val in re.split(r'[/,]', vals.strip()): val = val.strip() try: val = int(val) rvals.append(val) except Exception: if '=' in val: deep_key, val = val.split('=', 1) deep_key = deep_key.strip() val = val.strip() if val: valdict[deep_key] = val elif val: rvals.append(val) if valdict: rvals.append(valdict) if not rvals: continue elif len(rvals) == 1: rvals = rvals[0] disk_data[key] = rvals out[disk] = disk_data return out @salt.utils.decorators.depends(HAS_HDPARM) def hpa(disks, size=None): ''' Get/set Host Protected Area settings T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record) and PARTIES (Protected Area Run Time Interface Extension Services), allowing for a Host Protected Area on a disk. It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's .. warning:: Setting the HPA might clobber your data, be very careful with this on active disks! .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hpa /dev/sda salt '*' disk.hpa /dev/sda 5% salt '*' disk.hpa /dev/sda 10543256 ''' hpa_data = {} for disk, data in hdparms(disks, 'N').items(): visible, total, status = data.values()[0] if visible == total or 'disabled' in status: hpa_data[disk] = { 'total': total } else: hpa_data[disk] = { 'total': total, 'visible': visible, 'hidden': total - visible } if size is None: return hpa_data for disk, data in hpa_data.items(): try: size = data['total'] - int(size) except Exception: if '%' in size: size = int(size.strip('%')) size = (100 - size) * data['total'] size /= 100 if size <= 0: size = data['total'] _hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk)) def smart_attributes(dev, attributes=None, values=None): ''' Fetch SMART attributes Providing attributes will deliver only requested attributes Providing values will deliver only requested values for attributes Default is the Backblaze recommended set (https://www.backblaze.com/blog/hard-drive-smart-stats/): (5,187,188,197,198) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.smart_attributes /dev/sda salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198) ''' if not dev.startswith('/dev/'): dev = '/dev/' + dev cmd = 'smartctl --attributes {0}'.format(dev) smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet') if smart_result['retcode'] != 0: raise CommandExecutionError(smart_result['stderr']) smart_result = iter(smart_result['stdout'].splitlines()) fields = [] for line in smart_result: if line.startswith('ID#'): fields = re.split(r'\s+', line.strip()) fields = [key.lower() for key in fields[1:]] break if values is not None: fields = [field if field in values else '_' for field in fields] smart_attr = {} for line in smart_result: if not re.match(r'[\s]*\d', line): break line = re.split(r'\s+', line.strip(), maxsplit=len(fields)) attr = int(line[0]) if attributes is not None and attr not in attributes: continue data = dict(zip(fields, line[1:])) try: del data['_'] except Exception: pass for field in data: val = data[field] try: val = int(val) except Exception: try: val = [int(value) for value in val.split(' ')] except Exception: pass data[field] = val smart_attr[attr] = data return smart_attr @salt.utils.decorators.depends(HAS_IOSTAT) def iostat(interval=1, count=5, disks=None): ''' Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda ''' if salt.utils.platform.is_linux(): return _iostat_linux(interval, count, disks) elif salt.utils.platform.is_freebsd(): return _iostat_fbsd(interval, count, disks) elif salt.utils.platform.is_aix(): return _iostat_aix(interval, count, disks) def _iostats_dict(header, stats): ''' Transpose collected data, average it, stomp it in dict using header Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq ''' stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)] stats = dict(zip(header, stats)) return stats def _iostat_fbsd(interval, count, disks): ''' Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax ''' if disks is None: iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] h_len = 1000 # randomly absurdly high ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if not line.startswith('device'): continue elif not dev_header: dev_header = line.split()[1:] while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] # h_len will become smallest number of fields in stat lines if len(stats) < h_len: h_len = len(stats) dev_stats[disk].append(stats) iostats = {} # The header was longer than the smallest number of fields # Therefore the sys stats are hidden in there if h_len < len(dev_header): sys_header = dev_header[h_len:] dev_header = dev_header[0:h_len] for disk, stats in dev_stats.items(): if len(stats[0]) > h_len: sys_stats = [stat[h_len:] for stat in stats] dev_stats[disk] = [stat[0:h_len] for stat in stats] iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_linux(interval, count, disks): if disks is None: iostat_cmd = 'iostat -x {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if line.startswith('avg-cpu:'): if not sys_header: sys_header = tuple(line.split()[1:]) line = [decimal.Decimal(x) for x in next(ret).split()] sys_stats.append(line) elif line.startswith('Device:'): if not dev_header: dev_header = tuple(line.split()[1:]) while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] dev_stats[disk].append(stats) iostats = {} if sys_header: iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_aix(interval, count, disks): ''' AIX support to gather and return (averaged) IO stats. ''' log.debug('DGM disk iostat entry') if disks is None: iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count) else: iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count) ret = {} procn = None fields = [] disk_name = '' disk_mode = '' dev_stats = collections.defaultdict(list) for line in __salt__['cmd.run'](iostat_cmd).splitlines(): # Note: iostat -dD is per-system # #root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3 # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 9.6 16.4K 4.0 16.4K 0.0 # read: rps avgserv minserv maxserv timeouts fails # 4.0 4.9 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #seen disk name dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() if disk_name not in dev_stats.keys(): dev_stats[disk_name] = [] procn = len(dev_stats[disk_name]) dev_stats[disk_name].append({}) dev_stats[disk_name][procn][disk_mode] = {} dev_stats[disk_name][procn][disk_mode]['fields'] = fields dev_stats[disk_name][procn][disk_mode]['stats'] = [] continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() if disk_mode not in dev_stats[disk_name][0].keys(): dev_stats[disk_name][0][disk_mode] = {} dev_stats[disk_name][0][disk_mode]['fields'] = fields dev_stats[disk_name][0][disk_mode]['stats'] = [] else: line = line.split() stats = [_parse_numbers(x) for x in line[:]] dev_stats[disk_name][0][disk_mode]['stats'].append(stats) iostats = {} for disk, list_modes in dev_stats.items(): iostats[disk] = {} for modes in list_modes: for disk_mode in modes.keys(): fields = modes[disk_mode]['fields'] stats = modes[disk_mode]['stats'] iostats[disk][disk_mode] = _iostats_dict(fields, stats) return iostats
saltstack/salt
salt/modules/disk.py
_clean_flags
python
def _clean_flags(args, caller): ''' Sanitize flags passed into df ''' flags = '' if args is None: return flags allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: raise CommandExecutionError( 'Invalid flag passed to {0}'.format(caller) ) return flags
Sanitize flags passed into df
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L66-L81
null
# -*- coding: utf-8 -*- ''' Module for managing disks and blockdevices ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os import subprocess import re import collections import decimal # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # Import salt libs import salt.utils.decorators import salt.utils.decorators.path import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError __func_alias__ = { 'format_': 'format' } log = logging.getLogger(__name__) HAS_HDPARM = salt.utils.path.which('hdparm') is not None HAS_IOSTAT = salt.utils.path.which('iostat') is not None def __virtual__(): ''' Only work on POSIX-like systems ''' if salt.utils.platform.is_windows(): return False, 'This module doesn\'t work on Windows.' return True def _parse_numbers(text): ''' Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return decimal.Decimal(text) try: postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'} if text[-1] in postPrefixes.keys(): v = decimal.Decimal(text[:-1]) v = v * decimal.Decimal(postPrefixes[text[-1]]) return v else: return decimal.Decimal(text) except ValueError: return text def usage(args=None): ''' Return usage information for volumes mounted on this minion .. versionchanged:: 2019.2.0 Default for SunOS changed to 1 kilobyte blocks CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = _clean_flags(args, 'disk.usage') if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux': log.error('df cannot run without /etc/mtab') if __grains__.get('virtual_subtype') == 'LXC': log.error('df command failed and LXC detected. If you are running ' 'a Docker container, consider linking /proc/mounts to ' '/etc/mtab or consider running Docker with -privileged') return {} if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' elif __grains__['kernel'] == 'SunOS': cmd = 'df -k' else: cmd = 'df' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() oldline = None for line in out: if not line: continue if line.startswith('Filesystem'): continue if oldline: line = oldline + " " + line comps = line.split() if len(comps) == 1: oldline = line continue else: oldline = None while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.error('Problem parsing disk usage information') ret = {} return ret def inodeusage(args=None): ''' Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage ''' flags = _clean_flags(args, 'disk.inodeusage') if __grains__['kernel'] == 'AIX': cmd = 'df -i' else: cmd = 'df -iP' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if line.startswith('Filesystem'): continue comps = line.split() # Don't choke on empty lines if not comps: continue try: if __grains__['kernel'] == 'OpenBSD': ret[comps[8]] = { 'inodes': int(comps[5]) + int(comps[6]), 'used': comps[5], 'free': comps[6], 'use': comps[7], 'filesystem': comps[0], } elif __grains__['kernel'] == 'AIX': ret[comps[6]] = { 'inodes': comps[4], 'used': comps[5], 'free': comps[2], 'use': comps[5], 'filesystem': comps[0], } else: ret[comps[5]] = { 'inodes': comps[1], 'used': comps[2], 'free': comps[3], 'use': comps[4], 'filesystem': comps[0], } except (IndexError, ValueError): log.error('Problem parsing inode usage information') ret = {} return ret def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' else: cmd = 'df' ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = comps[4] else: ret[comps[5]] = comps[4] except IndexError: log.error('Problem parsing disk usage information') ret = {} if args and args not in ret: log.error( 'Problem parsing disk usage information: Partition \'%s\' ' 'does not exist!', args ) ret = {} elif args: return ret[args] return ret @salt.utils.decorators.path.which('blkid') def blkid(device=None, token=None): ''' Return block device attributes: UUID, LABEL, etc. This function only works on systems where blkid is available. device Device name from the system token Any valid token used for the search CLI Example: .. code-block:: bash salt '*' disk.blkid salt '*' disk.blkid /dev/sda salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d' salt '*' disk.blkid token='TYPE=ext4' ''' cmd = ['blkid'] if device: cmd.append(device) elif token: cmd.extend(['-t', token]) ret = {} blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False) if blkid_result['retcode'] > 0: return ret for line in blkid_result['stdout'].splitlines(): if not line: continue comps = line.split() device = comps[0][:-1] info = {} device_attributes = re.split(('\"*\"'), line.partition(' ')[2]) for key, value in zip(*[iter(device_attributes)]*2): key = key.strip('=').strip(' ') info[key] = value.strip('"') ret[device] = info return ret def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(8)`` manpage for a more complete description of these options. ''' kwarg_map = {'read-ahead': 'setra', 'filesystem-read-ahead': 'setfra', 'read-only': 'setro', 'read-write': 'setrw'} opts = '' args = [] for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if key != 'read-write': args.append(switch.replace('set', 'get')) else: args.append('getro') if kwargs[key] == 'True' or kwargs[key] is True: opts += '--{0} '.format(key) else: opts += '--{0} {1} '.format(switch, kwargs[key]) cmd = 'blockdev {0}{1}'.format(opts, device) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() return dump(device, args) def wipe(device): ''' Remove the filesystem information CLI Example: .. code-block:: bash salt '*' disk.wipe /dev/sda1 ''' cmd = 'wipefs -a {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True else: log.error('Error wiping device %s: %s', device, out['stderr']) return False def dump(device, args=None): ''' Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' disk.dump /dev/sda1 ''' cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \ '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device) ret = {} opts = [c[2:] for c in cmd.split() if c.startswith('--')] out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode'] == 0: lines = [line for line in out['stdout'].splitlines() if line] count = 0 for line in lines: ret[opts[count]] = line count = count+1 if args: temp_ret = {} for arg in args: temp_ret[arg] = ret[arg] return temp_ret else: return ret else: return False def resize2fs(device): ''' Resizes the filesystem. CLI Example: .. code-block:: bash salt '*' disk.resize2fs /dev/sda1 ''' cmd = 'resize2fs {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True @salt.utils.decorators.path.which('sync') @salt.utils.decorators.path.which('mkfs') def format_(device, fs_type='ext4', inode_size=None, lazy_itable_init=None, fat=None, force=False): ''' Format a filesystem onto a device .. versionadded:: 2016.11.0 device The device in which to create the new filesystem fs_type The type of filesystem to create inode_size Size of the inodes This option is only enabled for ext and xfs filesystems lazy_itable_init If enabled and the uninit_bg feature is enabled, the inode table will not be fully initialized by mke2fs. This speeds up filesystem initialization noticeably, but it requires the kernel to finish initializing the filesystem in the background when the filesystem is first mounted. If the option value is omitted, it defaults to 1 to enable lazy inode table zeroing. This option is only enabled for ext filesystems fat FAT size option. Can be 12, 16 or 32, and can only be used on fat or vfat filesystems. force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. CLI Example: .. code-block:: bash salt '*' disk.format /dev/sdX1 ''' cmd = ['mkfs', '-t', six.text_type(fs_type)] if inode_size is not None: if fs_type[:3] == 'ext': cmd.extend(['-i', six.text_type(inode_size)]) elif fs_type == 'xfs': cmd.extend(['-i', 'size={0}'.format(inode_size)]) if lazy_itable_init is not None: if fs_type[:3] == 'ext': cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)]) if fat is not None and fat in (12, 16, 32): if fs_type[-3:] == 'fat': cmd.extend(['-F', fat]) if force: if fs_type[:3] == 'ext': cmd.append('-F') elif fs_type == 'xfs': cmd.append('-f') cmd.append(six.text_type(device)) mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0 sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0 return all([mkfs_success, sync_success]) @salt.utils.decorators.path.which_bin(['lsblk', 'df']) def fstype(device): ''' Return the filesystem name of the specified device .. versionadded:: 2016.11.0 device The name of the device CLI Example: .. code-block:: bash salt '*' disk.fstype /dev/sdX1 ''' if salt.utils.path.which('lsblk'): lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines() if len(lsblk_out) > 1: fs_type = lsblk_out[1].strip() if fs_type: return fs_type if salt.utils.path.which('df'): # the fstype was not set on the block device, so inspect the filesystem # itself for its type if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'): df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split() if len(df_out) > 2: fs_type = df_out[2] if fs_type: return fs_type else: df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines() if len(df_out) > 1: fs_type = df_out[1] if fs_type: return fs_type return '' @salt.utils.decorators.depends(HAS_HDPARM) def _hdparm(args, failhard=True): ''' Execute hdparm Fail hard when required return output when possible ''' cmd = 'hdparm {0}'.format(args) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: msg = '{0}: {1}'.format(cmd, result['stderr']) if failhard: raise CommandExecutionError(msg) else: log.warning(msg) return result['stdout'] @salt.utils.decorators.depends(HAS_HDPARM) def hdparms(disks, args=None): ''' Retrieve all info's for all disks parse 'em into a nice dict (which, considering hdparms output, is quite a hassle) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hdparms /dev/sda ''' all_parms = 'aAbBcCdgHiJkMmNnQrRuW' if args is None: args = all_parms elif isinstance(args, (list, tuple)): args = ''.join(args) if not isinstance(disks, (list, tuple)): disks = [disks] out = {} for disk in disks: if not disk.startswith('/dev'): disk = '/dev/{0}'.format(disk) disk_data = {} for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines(): line = line.strip() if not line or line == disk + ':': continue if ':' in line: key, vals = line.split(':', 1) key = re.sub(r' is$', '', key) elif '=' in line: key, vals = line.split('=', 1) else: continue key = key.strip().lower().replace(' ', '_') vals = vals.strip() rvals = [] if re.match(r'[0-9]+ \(.*\)', vals): vals = vals.split(' ') rvals.append(int(vals[0])) rvals.append(vals[1].strip('()')) else: valdict = {} for val in re.split(r'[/,]', vals.strip()): val = val.strip() try: val = int(val) rvals.append(val) except Exception: if '=' in val: deep_key, val = val.split('=', 1) deep_key = deep_key.strip() val = val.strip() if val: valdict[deep_key] = val elif val: rvals.append(val) if valdict: rvals.append(valdict) if not rvals: continue elif len(rvals) == 1: rvals = rvals[0] disk_data[key] = rvals out[disk] = disk_data return out @salt.utils.decorators.depends(HAS_HDPARM) def hpa(disks, size=None): ''' Get/set Host Protected Area settings T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record) and PARTIES (Protected Area Run Time Interface Extension Services), allowing for a Host Protected Area on a disk. It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's .. warning:: Setting the HPA might clobber your data, be very careful with this on active disks! .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hpa /dev/sda salt '*' disk.hpa /dev/sda 5% salt '*' disk.hpa /dev/sda 10543256 ''' hpa_data = {} for disk, data in hdparms(disks, 'N').items(): visible, total, status = data.values()[0] if visible == total or 'disabled' in status: hpa_data[disk] = { 'total': total } else: hpa_data[disk] = { 'total': total, 'visible': visible, 'hidden': total - visible } if size is None: return hpa_data for disk, data in hpa_data.items(): try: size = data['total'] - int(size) except Exception: if '%' in size: size = int(size.strip('%')) size = (100 - size) * data['total'] size /= 100 if size <= 0: size = data['total'] _hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk)) def smart_attributes(dev, attributes=None, values=None): ''' Fetch SMART attributes Providing attributes will deliver only requested attributes Providing values will deliver only requested values for attributes Default is the Backblaze recommended set (https://www.backblaze.com/blog/hard-drive-smart-stats/): (5,187,188,197,198) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.smart_attributes /dev/sda salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198) ''' if not dev.startswith('/dev/'): dev = '/dev/' + dev cmd = 'smartctl --attributes {0}'.format(dev) smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet') if smart_result['retcode'] != 0: raise CommandExecutionError(smart_result['stderr']) smart_result = iter(smart_result['stdout'].splitlines()) fields = [] for line in smart_result: if line.startswith('ID#'): fields = re.split(r'\s+', line.strip()) fields = [key.lower() for key in fields[1:]] break if values is not None: fields = [field if field in values else '_' for field in fields] smart_attr = {} for line in smart_result: if not re.match(r'[\s]*\d', line): break line = re.split(r'\s+', line.strip(), maxsplit=len(fields)) attr = int(line[0]) if attributes is not None and attr not in attributes: continue data = dict(zip(fields, line[1:])) try: del data['_'] except Exception: pass for field in data: val = data[field] try: val = int(val) except Exception: try: val = [int(value) for value in val.split(' ')] except Exception: pass data[field] = val smart_attr[attr] = data return smart_attr @salt.utils.decorators.depends(HAS_IOSTAT) def iostat(interval=1, count=5, disks=None): ''' Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda ''' if salt.utils.platform.is_linux(): return _iostat_linux(interval, count, disks) elif salt.utils.platform.is_freebsd(): return _iostat_fbsd(interval, count, disks) elif salt.utils.platform.is_aix(): return _iostat_aix(interval, count, disks) def _iostats_dict(header, stats): ''' Transpose collected data, average it, stomp it in dict using header Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq ''' stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)] stats = dict(zip(header, stats)) return stats def _iostat_fbsd(interval, count, disks): ''' Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax ''' if disks is None: iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] h_len = 1000 # randomly absurdly high ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if not line.startswith('device'): continue elif not dev_header: dev_header = line.split()[1:] while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] # h_len will become smallest number of fields in stat lines if len(stats) < h_len: h_len = len(stats) dev_stats[disk].append(stats) iostats = {} # The header was longer than the smallest number of fields # Therefore the sys stats are hidden in there if h_len < len(dev_header): sys_header = dev_header[h_len:] dev_header = dev_header[0:h_len] for disk, stats in dev_stats.items(): if len(stats[0]) > h_len: sys_stats = [stat[h_len:] for stat in stats] dev_stats[disk] = [stat[0:h_len] for stat in stats] iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_linux(interval, count, disks): if disks is None: iostat_cmd = 'iostat -x {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if line.startswith('avg-cpu:'): if not sys_header: sys_header = tuple(line.split()[1:]) line = [decimal.Decimal(x) for x in next(ret).split()] sys_stats.append(line) elif line.startswith('Device:'): if not dev_header: dev_header = tuple(line.split()[1:]) while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] dev_stats[disk].append(stats) iostats = {} if sys_header: iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_aix(interval, count, disks): ''' AIX support to gather and return (averaged) IO stats. ''' log.debug('DGM disk iostat entry') if disks is None: iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count) else: iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count) ret = {} procn = None fields = [] disk_name = '' disk_mode = '' dev_stats = collections.defaultdict(list) for line in __salt__['cmd.run'](iostat_cmd).splitlines(): # Note: iostat -dD is per-system # #root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3 # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 9.6 16.4K 4.0 16.4K 0.0 # read: rps avgserv minserv maxserv timeouts fails # 4.0 4.9 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #seen disk name dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() if disk_name not in dev_stats.keys(): dev_stats[disk_name] = [] procn = len(dev_stats[disk_name]) dev_stats[disk_name].append({}) dev_stats[disk_name][procn][disk_mode] = {} dev_stats[disk_name][procn][disk_mode]['fields'] = fields dev_stats[disk_name][procn][disk_mode]['stats'] = [] continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() if disk_mode not in dev_stats[disk_name][0].keys(): dev_stats[disk_name][0][disk_mode] = {} dev_stats[disk_name][0][disk_mode]['fields'] = fields dev_stats[disk_name][0][disk_mode]['stats'] = [] else: line = line.split() stats = [_parse_numbers(x) for x in line[:]] dev_stats[disk_name][0][disk_mode]['stats'].append(stats) iostats = {} for disk, list_modes in dev_stats.items(): iostats[disk] = {} for modes in list_modes: for disk_mode in modes.keys(): fields = modes[disk_mode]['fields'] stats = modes[disk_mode]['stats'] iostats[disk][disk_mode] = _iostats_dict(fields, stats) return iostats
saltstack/salt
salt/modules/disk.py
usage
python
def usage(args=None): ''' Return usage information for volumes mounted on this minion .. versionchanged:: 2019.2.0 Default for SunOS changed to 1 kilobyte blocks CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = _clean_flags(args, 'disk.usage') if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux': log.error('df cannot run without /etc/mtab') if __grains__.get('virtual_subtype') == 'LXC': log.error('df command failed and LXC detected. If you are running ' 'a Docker container, consider linking /proc/mounts to ' '/etc/mtab or consider running Docker with -privileged') return {} if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' elif __grains__['kernel'] == 'SunOS': cmd = 'df -k' else: cmd = 'df' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() oldline = None for line in out: if not line: continue if line.startswith('Filesystem'): continue if oldline: line = oldline + " " + line comps = line.split() if len(comps) == 1: oldline = line continue else: oldline = None while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.error('Problem parsing disk usage information') ret = {} return ret
Return usage information for volumes mounted on this minion .. versionchanged:: 2019.2.0 Default for SunOS changed to 1 kilobyte blocks CLI Example: .. code-block:: bash salt '*' disk.usage
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L84-L160
[ "def _clean_flags(args, caller):\n '''\n Sanitize flags passed into df\n '''\n flags = ''\n if args is None:\n return flags\n allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n for flag in args:\n if flag in allowed:\n flags += flag\n else:\n raise CommandExecutionError(\n 'Invalid flag passed to {0}'.format(caller)\n )\n return flags\n" ]
# -*- coding: utf-8 -*- ''' Module for managing disks and blockdevices ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os import subprocess import re import collections import decimal # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # Import salt libs import salt.utils.decorators import salt.utils.decorators.path import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError __func_alias__ = { 'format_': 'format' } log = logging.getLogger(__name__) HAS_HDPARM = salt.utils.path.which('hdparm') is not None HAS_IOSTAT = salt.utils.path.which('iostat') is not None def __virtual__(): ''' Only work on POSIX-like systems ''' if salt.utils.platform.is_windows(): return False, 'This module doesn\'t work on Windows.' return True def _parse_numbers(text): ''' Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return decimal.Decimal(text) try: postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'} if text[-1] in postPrefixes.keys(): v = decimal.Decimal(text[:-1]) v = v * decimal.Decimal(postPrefixes[text[-1]]) return v else: return decimal.Decimal(text) except ValueError: return text def _clean_flags(args, caller): ''' Sanitize flags passed into df ''' flags = '' if args is None: return flags allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: raise CommandExecutionError( 'Invalid flag passed to {0}'.format(caller) ) return flags def inodeusage(args=None): ''' Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage ''' flags = _clean_flags(args, 'disk.inodeusage') if __grains__['kernel'] == 'AIX': cmd = 'df -i' else: cmd = 'df -iP' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if line.startswith('Filesystem'): continue comps = line.split() # Don't choke on empty lines if not comps: continue try: if __grains__['kernel'] == 'OpenBSD': ret[comps[8]] = { 'inodes': int(comps[5]) + int(comps[6]), 'used': comps[5], 'free': comps[6], 'use': comps[7], 'filesystem': comps[0], } elif __grains__['kernel'] == 'AIX': ret[comps[6]] = { 'inodes': comps[4], 'used': comps[5], 'free': comps[2], 'use': comps[5], 'filesystem': comps[0], } else: ret[comps[5]] = { 'inodes': comps[1], 'used': comps[2], 'free': comps[3], 'use': comps[4], 'filesystem': comps[0], } except (IndexError, ValueError): log.error('Problem parsing inode usage information') ret = {} return ret def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' else: cmd = 'df' ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = comps[4] else: ret[comps[5]] = comps[4] except IndexError: log.error('Problem parsing disk usage information') ret = {} if args and args not in ret: log.error( 'Problem parsing disk usage information: Partition \'%s\' ' 'does not exist!', args ) ret = {} elif args: return ret[args] return ret @salt.utils.decorators.path.which('blkid') def blkid(device=None, token=None): ''' Return block device attributes: UUID, LABEL, etc. This function only works on systems where blkid is available. device Device name from the system token Any valid token used for the search CLI Example: .. code-block:: bash salt '*' disk.blkid salt '*' disk.blkid /dev/sda salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d' salt '*' disk.blkid token='TYPE=ext4' ''' cmd = ['blkid'] if device: cmd.append(device) elif token: cmd.extend(['-t', token]) ret = {} blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False) if blkid_result['retcode'] > 0: return ret for line in blkid_result['stdout'].splitlines(): if not line: continue comps = line.split() device = comps[0][:-1] info = {} device_attributes = re.split(('\"*\"'), line.partition(' ')[2]) for key, value in zip(*[iter(device_attributes)]*2): key = key.strip('=').strip(' ') info[key] = value.strip('"') ret[device] = info return ret def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(8)`` manpage for a more complete description of these options. ''' kwarg_map = {'read-ahead': 'setra', 'filesystem-read-ahead': 'setfra', 'read-only': 'setro', 'read-write': 'setrw'} opts = '' args = [] for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if key != 'read-write': args.append(switch.replace('set', 'get')) else: args.append('getro') if kwargs[key] == 'True' or kwargs[key] is True: opts += '--{0} '.format(key) else: opts += '--{0} {1} '.format(switch, kwargs[key]) cmd = 'blockdev {0}{1}'.format(opts, device) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() return dump(device, args) def wipe(device): ''' Remove the filesystem information CLI Example: .. code-block:: bash salt '*' disk.wipe /dev/sda1 ''' cmd = 'wipefs -a {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True else: log.error('Error wiping device %s: %s', device, out['stderr']) return False def dump(device, args=None): ''' Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' disk.dump /dev/sda1 ''' cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \ '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device) ret = {} opts = [c[2:] for c in cmd.split() if c.startswith('--')] out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode'] == 0: lines = [line for line in out['stdout'].splitlines() if line] count = 0 for line in lines: ret[opts[count]] = line count = count+1 if args: temp_ret = {} for arg in args: temp_ret[arg] = ret[arg] return temp_ret else: return ret else: return False def resize2fs(device): ''' Resizes the filesystem. CLI Example: .. code-block:: bash salt '*' disk.resize2fs /dev/sda1 ''' cmd = 'resize2fs {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True @salt.utils.decorators.path.which('sync') @salt.utils.decorators.path.which('mkfs') def format_(device, fs_type='ext4', inode_size=None, lazy_itable_init=None, fat=None, force=False): ''' Format a filesystem onto a device .. versionadded:: 2016.11.0 device The device in which to create the new filesystem fs_type The type of filesystem to create inode_size Size of the inodes This option is only enabled for ext and xfs filesystems lazy_itable_init If enabled and the uninit_bg feature is enabled, the inode table will not be fully initialized by mke2fs. This speeds up filesystem initialization noticeably, but it requires the kernel to finish initializing the filesystem in the background when the filesystem is first mounted. If the option value is omitted, it defaults to 1 to enable lazy inode table zeroing. This option is only enabled for ext filesystems fat FAT size option. Can be 12, 16 or 32, and can only be used on fat or vfat filesystems. force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. CLI Example: .. code-block:: bash salt '*' disk.format /dev/sdX1 ''' cmd = ['mkfs', '-t', six.text_type(fs_type)] if inode_size is not None: if fs_type[:3] == 'ext': cmd.extend(['-i', six.text_type(inode_size)]) elif fs_type == 'xfs': cmd.extend(['-i', 'size={0}'.format(inode_size)]) if lazy_itable_init is not None: if fs_type[:3] == 'ext': cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)]) if fat is not None and fat in (12, 16, 32): if fs_type[-3:] == 'fat': cmd.extend(['-F', fat]) if force: if fs_type[:3] == 'ext': cmd.append('-F') elif fs_type == 'xfs': cmd.append('-f') cmd.append(six.text_type(device)) mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0 sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0 return all([mkfs_success, sync_success]) @salt.utils.decorators.path.which_bin(['lsblk', 'df']) def fstype(device): ''' Return the filesystem name of the specified device .. versionadded:: 2016.11.0 device The name of the device CLI Example: .. code-block:: bash salt '*' disk.fstype /dev/sdX1 ''' if salt.utils.path.which('lsblk'): lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines() if len(lsblk_out) > 1: fs_type = lsblk_out[1].strip() if fs_type: return fs_type if salt.utils.path.which('df'): # the fstype was not set on the block device, so inspect the filesystem # itself for its type if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'): df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split() if len(df_out) > 2: fs_type = df_out[2] if fs_type: return fs_type else: df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines() if len(df_out) > 1: fs_type = df_out[1] if fs_type: return fs_type return '' @salt.utils.decorators.depends(HAS_HDPARM) def _hdparm(args, failhard=True): ''' Execute hdparm Fail hard when required return output when possible ''' cmd = 'hdparm {0}'.format(args) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: msg = '{0}: {1}'.format(cmd, result['stderr']) if failhard: raise CommandExecutionError(msg) else: log.warning(msg) return result['stdout'] @salt.utils.decorators.depends(HAS_HDPARM) def hdparms(disks, args=None): ''' Retrieve all info's for all disks parse 'em into a nice dict (which, considering hdparms output, is quite a hassle) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hdparms /dev/sda ''' all_parms = 'aAbBcCdgHiJkMmNnQrRuW' if args is None: args = all_parms elif isinstance(args, (list, tuple)): args = ''.join(args) if not isinstance(disks, (list, tuple)): disks = [disks] out = {} for disk in disks: if not disk.startswith('/dev'): disk = '/dev/{0}'.format(disk) disk_data = {} for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines(): line = line.strip() if not line or line == disk + ':': continue if ':' in line: key, vals = line.split(':', 1) key = re.sub(r' is$', '', key) elif '=' in line: key, vals = line.split('=', 1) else: continue key = key.strip().lower().replace(' ', '_') vals = vals.strip() rvals = [] if re.match(r'[0-9]+ \(.*\)', vals): vals = vals.split(' ') rvals.append(int(vals[0])) rvals.append(vals[1].strip('()')) else: valdict = {} for val in re.split(r'[/,]', vals.strip()): val = val.strip() try: val = int(val) rvals.append(val) except Exception: if '=' in val: deep_key, val = val.split('=', 1) deep_key = deep_key.strip() val = val.strip() if val: valdict[deep_key] = val elif val: rvals.append(val) if valdict: rvals.append(valdict) if not rvals: continue elif len(rvals) == 1: rvals = rvals[0] disk_data[key] = rvals out[disk] = disk_data return out @salt.utils.decorators.depends(HAS_HDPARM) def hpa(disks, size=None): ''' Get/set Host Protected Area settings T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record) and PARTIES (Protected Area Run Time Interface Extension Services), allowing for a Host Protected Area on a disk. It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's .. warning:: Setting the HPA might clobber your data, be very careful with this on active disks! .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hpa /dev/sda salt '*' disk.hpa /dev/sda 5% salt '*' disk.hpa /dev/sda 10543256 ''' hpa_data = {} for disk, data in hdparms(disks, 'N').items(): visible, total, status = data.values()[0] if visible == total or 'disabled' in status: hpa_data[disk] = { 'total': total } else: hpa_data[disk] = { 'total': total, 'visible': visible, 'hidden': total - visible } if size is None: return hpa_data for disk, data in hpa_data.items(): try: size = data['total'] - int(size) except Exception: if '%' in size: size = int(size.strip('%')) size = (100 - size) * data['total'] size /= 100 if size <= 0: size = data['total'] _hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk)) def smart_attributes(dev, attributes=None, values=None): ''' Fetch SMART attributes Providing attributes will deliver only requested attributes Providing values will deliver only requested values for attributes Default is the Backblaze recommended set (https://www.backblaze.com/blog/hard-drive-smart-stats/): (5,187,188,197,198) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.smart_attributes /dev/sda salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198) ''' if not dev.startswith('/dev/'): dev = '/dev/' + dev cmd = 'smartctl --attributes {0}'.format(dev) smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet') if smart_result['retcode'] != 0: raise CommandExecutionError(smart_result['stderr']) smart_result = iter(smart_result['stdout'].splitlines()) fields = [] for line in smart_result: if line.startswith('ID#'): fields = re.split(r'\s+', line.strip()) fields = [key.lower() for key in fields[1:]] break if values is not None: fields = [field if field in values else '_' for field in fields] smart_attr = {} for line in smart_result: if not re.match(r'[\s]*\d', line): break line = re.split(r'\s+', line.strip(), maxsplit=len(fields)) attr = int(line[0]) if attributes is not None and attr not in attributes: continue data = dict(zip(fields, line[1:])) try: del data['_'] except Exception: pass for field in data: val = data[field] try: val = int(val) except Exception: try: val = [int(value) for value in val.split(' ')] except Exception: pass data[field] = val smart_attr[attr] = data return smart_attr @salt.utils.decorators.depends(HAS_IOSTAT) def iostat(interval=1, count=5, disks=None): ''' Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda ''' if salt.utils.platform.is_linux(): return _iostat_linux(interval, count, disks) elif salt.utils.platform.is_freebsd(): return _iostat_fbsd(interval, count, disks) elif salt.utils.platform.is_aix(): return _iostat_aix(interval, count, disks) def _iostats_dict(header, stats): ''' Transpose collected data, average it, stomp it in dict using header Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq ''' stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)] stats = dict(zip(header, stats)) return stats def _iostat_fbsd(interval, count, disks): ''' Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax ''' if disks is None: iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] h_len = 1000 # randomly absurdly high ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if not line.startswith('device'): continue elif not dev_header: dev_header = line.split()[1:] while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] # h_len will become smallest number of fields in stat lines if len(stats) < h_len: h_len = len(stats) dev_stats[disk].append(stats) iostats = {} # The header was longer than the smallest number of fields # Therefore the sys stats are hidden in there if h_len < len(dev_header): sys_header = dev_header[h_len:] dev_header = dev_header[0:h_len] for disk, stats in dev_stats.items(): if len(stats[0]) > h_len: sys_stats = [stat[h_len:] for stat in stats] dev_stats[disk] = [stat[0:h_len] for stat in stats] iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_linux(interval, count, disks): if disks is None: iostat_cmd = 'iostat -x {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if line.startswith('avg-cpu:'): if not sys_header: sys_header = tuple(line.split()[1:]) line = [decimal.Decimal(x) for x in next(ret).split()] sys_stats.append(line) elif line.startswith('Device:'): if not dev_header: dev_header = tuple(line.split()[1:]) while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] dev_stats[disk].append(stats) iostats = {} if sys_header: iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_aix(interval, count, disks): ''' AIX support to gather and return (averaged) IO stats. ''' log.debug('DGM disk iostat entry') if disks is None: iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count) else: iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count) ret = {} procn = None fields = [] disk_name = '' disk_mode = '' dev_stats = collections.defaultdict(list) for line in __salt__['cmd.run'](iostat_cmd).splitlines(): # Note: iostat -dD is per-system # #root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3 # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 9.6 16.4K 4.0 16.4K 0.0 # read: rps avgserv minserv maxserv timeouts fails # 4.0 4.9 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #seen disk name dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() if disk_name not in dev_stats.keys(): dev_stats[disk_name] = [] procn = len(dev_stats[disk_name]) dev_stats[disk_name].append({}) dev_stats[disk_name][procn][disk_mode] = {} dev_stats[disk_name][procn][disk_mode]['fields'] = fields dev_stats[disk_name][procn][disk_mode]['stats'] = [] continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() if disk_mode not in dev_stats[disk_name][0].keys(): dev_stats[disk_name][0][disk_mode] = {} dev_stats[disk_name][0][disk_mode]['fields'] = fields dev_stats[disk_name][0][disk_mode]['stats'] = [] else: line = line.split() stats = [_parse_numbers(x) for x in line[:]] dev_stats[disk_name][0][disk_mode]['stats'].append(stats) iostats = {} for disk, list_modes in dev_stats.items(): iostats[disk] = {} for modes in list_modes: for disk_mode in modes.keys(): fields = modes[disk_mode]['fields'] stats = modes[disk_mode]['stats'] iostats[disk][disk_mode] = _iostats_dict(fields, stats) return iostats
saltstack/salt
salt/modules/disk.py
inodeusage
python
def inodeusage(args=None): ''' Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage ''' flags = _clean_flags(args, 'disk.inodeusage') if __grains__['kernel'] == 'AIX': cmd = 'df -i' else: cmd = 'df -iP' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if line.startswith('Filesystem'): continue comps = line.split() # Don't choke on empty lines if not comps: continue try: if __grains__['kernel'] == 'OpenBSD': ret[comps[8]] = { 'inodes': int(comps[5]) + int(comps[6]), 'used': comps[5], 'free': comps[6], 'use': comps[7], 'filesystem': comps[0], } elif __grains__['kernel'] == 'AIX': ret[comps[6]] = { 'inodes': comps[4], 'used': comps[5], 'free': comps[2], 'use': comps[5], 'filesystem': comps[0], } else: ret[comps[5]] = { 'inodes': comps[1], 'used': comps[2], 'free': comps[3], 'use': comps[4], 'filesystem': comps[0], } except (IndexError, ValueError): log.error('Problem parsing inode usage information') ret = {} return ret
Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L163-L218
[ "def _clean_flags(args, caller):\n '''\n Sanitize flags passed into df\n '''\n flags = ''\n if args is None:\n return flags\n allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v')\n for flag in args:\n if flag in allowed:\n flags += flag\n else:\n raise CommandExecutionError(\n 'Invalid flag passed to {0}'.format(caller)\n )\n return flags\n" ]
# -*- coding: utf-8 -*- ''' Module for managing disks and blockdevices ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os import subprocess import re import collections import decimal # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # Import salt libs import salt.utils.decorators import salt.utils.decorators.path import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError __func_alias__ = { 'format_': 'format' } log = logging.getLogger(__name__) HAS_HDPARM = salt.utils.path.which('hdparm') is not None HAS_IOSTAT = salt.utils.path.which('iostat') is not None def __virtual__(): ''' Only work on POSIX-like systems ''' if salt.utils.platform.is_windows(): return False, 'This module doesn\'t work on Windows.' return True def _parse_numbers(text): ''' Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return decimal.Decimal(text) try: postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'} if text[-1] in postPrefixes.keys(): v = decimal.Decimal(text[:-1]) v = v * decimal.Decimal(postPrefixes[text[-1]]) return v else: return decimal.Decimal(text) except ValueError: return text def _clean_flags(args, caller): ''' Sanitize flags passed into df ''' flags = '' if args is None: return flags allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: raise CommandExecutionError( 'Invalid flag passed to {0}'.format(caller) ) return flags def usage(args=None): ''' Return usage information for volumes mounted on this minion .. versionchanged:: 2019.2.0 Default for SunOS changed to 1 kilobyte blocks CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = _clean_flags(args, 'disk.usage') if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux': log.error('df cannot run without /etc/mtab') if __grains__.get('virtual_subtype') == 'LXC': log.error('df command failed and LXC detected. If you are running ' 'a Docker container, consider linking /proc/mounts to ' '/etc/mtab or consider running Docker with -privileged') return {} if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' elif __grains__['kernel'] == 'SunOS': cmd = 'df -k' else: cmd = 'df' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() oldline = None for line in out: if not line: continue if line.startswith('Filesystem'): continue if oldline: line = oldline + " " + line comps = line.split() if len(comps) == 1: oldline = line continue else: oldline = None while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.error('Problem parsing disk usage information') ret = {} return ret def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' else: cmd = 'df' ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = comps[4] else: ret[comps[5]] = comps[4] except IndexError: log.error('Problem parsing disk usage information') ret = {} if args and args not in ret: log.error( 'Problem parsing disk usage information: Partition \'%s\' ' 'does not exist!', args ) ret = {} elif args: return ret[args] return ret @salt.utils.decorators.path.which('blkid') def blkid(device=None, token=None): ''' Return block device attributes: UUID, LABEL, etc. This function only works on systems where blkid is available. device Device name from the system token Any valid token used for the search CLI Example: .. code-block:: bash salt '*' disk.blkid salt '*' disk.blkid /dev/sda salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d' salt '*' disk.blkid token='TYPE=ext4' ''' cmd = ['blkid'] if device: cmd.append(device) elif token: cmd.extend(['-t', token]) ret = {} blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False) if blkid_result['retcode'] > 0: return ret for line in blkid_result['stdout'].splitlines(): if not line: continue comps = line.split() device = comps[0][:-1] info = {} device_attributes = re.split(('\"*\"'), line.partition(' ')[2]) for key, value in zip(*[iter(device_attributes)]*2): key = key.strip('=').strip(' ') info[key] = value.strip('"') ret[device] = info return ret def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(8)`` manpage for a more complete description of these options. ''' kwarg_map = {'read-ahead': 'setra', 'filesystem-read-ahead': 'setfra', 'read-only': 'setro', 'read-write': 'setrw'} opts = '' args = [] for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if key != 'read-write': args.append(switch.replace('set', 'get')) else: args.append('getro') if kwargs[key] == 'True' or kwargs[key] is True: opts += '--{0} '.format(key) else: opts += '--{0} {1} '.format(switch, kwargs[key]) cmd = 'blockdev {0}{1}'.format(opts, device) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() return dump(device, args) def wipe(device): ''' Remove the filesystem information CLI Example: .. code-block:: bash salt '*' disk.wipe /dev/sda1 ''' cmd = 'wipefs -a {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True else: log.error('Error wiping device %s: %s', device, out['stderr']) return False def dump(device, args=None): ''' Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' disk.dump /dev/sda1 ''' cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \ '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device) ret = {} opts = [c[2:] for c in cmd.split() if c.startswith('--')] out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode'] == 0: lines = [line for line in out['stdout'].splitlines() if line] count = 0 for line in lines: ret[opts[count]] = line count = count+1 if args: temp_ret = {} for arg in args: temp_ret[arg] = ret[arg] return temp_ret else: return ret else: return False def resize2fs(device): ''' Resizes the filesystem. CLI Example: .. code-block:: bash salt '*' disk.resize2fs /dev/sda1 ''' cmd = 'resize2fs {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True @salt.utils.decorators.path.which('sync') @salt.utils.decorators.path.which('mkfs') def format_(device, fs_type='ext4', inode_size=None, lazy_itable_init=None, fat=None, force=False): ''' Format a filesystem onto a device .. versionadded:: 2016.11.0 device The device in which to create the new filesystem fs_type The type of filesystem to create inode_size Size of the inodes This option is only enabled for ext and xfs filesystems lazy_itable_init If enabled and the uninit_bg feature is enabled, the inode table will not be fully initialized by mke2fs. This speeds up filesystem initialization noticeably, but it requires the kernel to finish initializing the filesystem in the background when the filesystem is first mounted. If the option value is omitted, it defaults to 1 to enable lazy inode table zeroing. This option is only enabled for ext filesystems fat FAT size option. Can be 12, 16 or 32, and can only be used on fat or vfat filesystems. force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. CLI Example: .. code-block:: bash salt '*' disk.format /dev/sdX1 ''' cmd = ['mkfs', '-t', six.text_type(fs_type)] if inode_size is not None: if fs_type[:3] == 'ext': cmd.extend(['-i', six.text_type(inode_size)]) elif fs_type == 'xfs': cmd.extend(['-i', 'size={0}'.format(inode_size)]) if lazy_itable_init is not None: if fs_type[:3] == 'ext': cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)]) if fat is not None and fat in (12, 16, 32): if fs_type[-3:] == 'fat': cmd.extend(['-F', fat]) if force: if fs_type[:3] == 'ext': cmd.append('-F') elif fs_type == 'xfs': cmd.append('-f') cmd.append(six.text_type(device)) mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0 sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0 return all([mkfs_success, sync_success]) @salt.utils.decorators.path.which_bin(['lsblk', 'df']) def fstype(device): ''' Return the filesystem name of the specified device .. versionadded:: 2016.11.0 device The name of the device CLI Example: .. code-block:: bash salt '*' disk.fstype /dev/sdX1 ''' if salt.utils.path.which('lsblk'): lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines() if len(lsblk_out) > 1: fs_type = lsblk_out[1].strip() if fs_type: return fs_type if salt.utils.path.which('df'): # the fstype was not set on the block device, so inspect the filesystem # itself for its type if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'): df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split() if len(df_out) > 2: fs_type = df_out[2] if fs_type: return fs_type else: df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines() if len(df_out) > 1: fs_type = df_out[1] if fs_type: return fs_type return '' @salt.utils.decorators.depends(HAS_HDPARM) def _hdparm(args, failhard=True): ''' Execute hdparm Fail hard when required return output when possible ''' cmd = 'hdparm {0}'.format(args) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: msg = '{0}: {1}'.format(cmd, result['stderr']) if failhard: raise CommandExecutionError(msg) else: log.warning(msg) return result['stdout'] @salt.utils.decorators.depends(HAS_HDPARM) def hdparms(disks, args=None): ''' Retrieve all info's for all disks parse 'em into a nice dict (which, considering hdparms output, is quite a hassle) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hdparms /dev/sda ''' all_parms = 'aAbBcCdgHiJkMmNnQrRuW' if args is None: args = all_parms elif isinstance(args, (list, tuple)): args = ''.join(args) if not isinstance(disks, (list, tuple)): disks = [disks] out = {} for disk in disks: if not disk.startswith('/dev'): disk = '/dev/{0}'.format(disk) disk_data = {} for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines(): line = line.strip() if not line or line == disk + ':': continue if ':' in line: key, vals = line.split(':', 1) key = re.sub(r' is$', '', key) elif '=' in line: key, vals = line.split('=', 1) else: continue key = key.strip().lower().replace(' ', '_') vals = vals.strip() rvals = [] if re.match(r'[0-9]+ \(.*\)', vals): vals = vals.split(' ') rvals.append(int(vals[0])) rvals.append(vals[1].strip('()')) else: valdict = {} for val in re.split(r'[/,]', vals.strip()): val = val.strip() try: val = int(val) rvals.append(val) except Exception: if '=' in val: deep_key, val = val.split('=', 1) deep_key = deep_key.strip() val = val.strip() if val: valdict[deep_key] = val elif val: rvals.append(val) if valdict: rvals.append(valdict) if not rvals: continue elif len(rvals) == 1: rvals = rvals[0] disk_data[key] = rvals out[disk] = disk_data return out @salt.utils.decorators.depends(HAS_HDPARM) def hpa(disks, size=None): ''' Get/set Host Protected Area settings T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record) and PARTIES (Protected Area Run Time Interface Extension Services), allowing for a Host Protected Area on a disk. It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's .. warning:: Setting the HPA might clobber your data, be very careful with this on active disks! .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hpa /dev/sda salt '*' disk.hpa /dev/sda 5% salt '*' disk.hpa /dev/sda 10543256 ''' hpa_data = {} for disk, data in hdparms(disks, 'N').items(): visible, total, status = data.values()[0] if visible == total or 'disabled' in status: hpa_data[disk] = { 'total': total } else: hpa_data[disk] = { 'total': total, 'visible': visible, 'hidden': total - visible } if size is None: return hpa_data for disk, data in hpa_data.items(): try: size = data['total'] - int(size) except Exception: if '%' in size: size = int(size.strip('%')) size = (100 - size) * data['total'] size /= 100 if size <= 0: size = data['total'] _hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk)) def smart_attributes(dev, attributes=None, values=None): ''' Fetch SMART attributes Providing attributes will deliver only requested attributes Providing values will deliver only requested values for attributes Default is the Backblaze recommended set (https://www.backblaze.com/blog/hard-drive-smart-stats/): (5,187,188,197,198) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.smart_attributes /dev/sda salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198) ''' if not dev.startswith('/dev/'): dev = '/dev/' + dev cmd = 'smartctl --attributes {0}'.format(dev) smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet') if smart_result['retcode'] != 0: raise CommandExecutionError(smart_result['stderr']) smart_result = iter(smart_result['stdout'].splitlines()) fields = [] for line in smart_result: if line.startswith('ID#'): fields = re.split(r'\s+', line.strip()) fields = [key.lower() for key in fields[1:]] break if values is not None: fields = [field if field in values else '_' for field in fields] smart_attr = {} for line in smart_result: if not re.match(r'[\s]*\d', line): break line = re.split(r'\s+', line.strip(), maxsplit=len(fields)) attr = int(line[0]) if attributes is not None and attr not in attributes: continue data = dict(zip(fields, line[1:])) try: del data['_'] except Exception: pass for field in data: val = data[field] try: val = int(val) except Exception: try: val = [int(value) for value in val.split(' ')] except Exception: pass data[field] = val smart_attr[attr] = data return smart_attr @salt.utils.decorators.depends(HAS_IOSTAT) def iostat(interval=1, count=5, disks=None): ''' Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda ''' if salt.utils.platform.is_linux(): return _iostat_linux(interval, count, disks) elif salt.utils.platform.is_freebsd(): return _iostat_fbsd(interval, count, disks) elif salt.utils.platform.is_aix(): return _iostat_aix(interval, count, disks) def _iostats_dict(header, stats): ''' Transpose collected data, average it, stomp it in dict using header Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq ''' stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)] stats = dict(zip(header, stats)) return stats def _iostat_fbsd(interval, count, disks): ''' Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax ''' if disks is None: iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] h_len = 1000 # randomly absurdly high ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if not line.startswith('device'): continue elif not dev_header: dev_header = line.split()[1:] while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] # h_len will become smallest number of fields in stat lines if len(stats) < h_len: h_len = len(stats) dev_stats[disk].append(stats) iostats = {} # The header was longer than the smallest number of fields # Therefore the sys stats are hidden in there if h_len < len(dev_header): sys_header = dev_header[h_len:] dev_header = dev_header[0:h_len] for disk, stats in dev_stats.items(): if len(stats[0]) > h_len: sys_stats = [stat[h_len:] for stat in stats] dev_stats[disk] = [stat[0:h_len] for stat in stats] iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_linux(interval, count, disks): if disks is None: iostat_cmd = 'iostat -x {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if line.startswith('avg-cpu:'): if not sys_header: sys_header = tuple(line.split()[1:]) line = [decimal.Decimal(x) for x in next(ret).split()] sys_stats.append(line) elif line.startswith('Device:'): if not dev_header: dev_header = tuple(line.split()[1:]) while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] dev_stats[disk].append(stats) iostats = {} if sys_header: iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_aix(interval, count, disks): ''' AIX support to gather and return (averaged) IO stats. ''' log.debug('DGM disk iostat entry') if disks is None: iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count) else: iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count) ret = {} procn = None fields = [] disk_name = '' disk_mode = '' dev_stats = collections.defaultdict(list) for line in __salt__['cmd.run'](iostat_cmd).splitlines(): # Note: iostat -dD is per-system # #root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3 # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 9.6 16.4K 4.0 16.4K 0.0 # read: rps avgserv minserv maxserv timeouts fails # 4.0 4.9 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #seen disk name dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() if disk_name not in dev_stats.keys(): dev_stats[disk_name] = [] procn = len(dev_stats[disk_name]) dev_stats[disk_name].append({}) dev_stats[disk_name][procn][disk_mode] = {} dev_stats[disk_name][procn][disk_mode]['fields'] = fields dev_stats[disk_name][procn][disk_mode]['stats'] = [] continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() if disk_mode not in dev_stats[disk_name][0].keys(): dev_stats[disk_name][0][disk_mode] = {} dev_stats[disk_name][0][disk_mode]['fields'] = fields dev_stats[disk_name][0][disk_mode]['stats'] = [] else: line = line.split() stats = [_parse_numbers(x) for x in line[:]] dev_stats[disk_name][0][disk_mode]['stats'].append(stats) iostats = {} for disk, list_modes in dev_stats.items(): iostats[disk] = {} for modes in list_modes: for disk_mode in modes.keys(): fields = modes[disk_mode]['fields'] stats = modes[disk_mode]['stats'] iostats[disk][disk_mode] = _iostats_dict(fields, stats) return iostats
saltstack/salt
salt/modules/disk.py
percent
python
def percent(args=None): ''' Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var ''' if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' else: cmd = 'df' ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if not line: continue if line.startswith('Filesystem'): continue comps = line.split() while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = comps[4] else: ret[comps[5]] = comps[4] except IndexError: log.error('Problem parsing disk usage information') ret = {} if args and args not in ret: log.error( 'Problem parsing disk usage information: Partition \'%s\' ' 'does not exist!', args ) ret = {} elif args: return ret[args] return ret
Return partition information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.percent /var
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/disk.py#L221-L267
null
# -*- coding: utf-8 -*- ''' Module for managing disks and blockdevices ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import os import subprocess import re import collections import decimal # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import zip # Import salt libs import salt.utils.decorators import salt.utils.decorators.path import salt.utils.path import salt.utils.platform from salt.exceptions import CommandExecutionError __func_alias__ = { 'format_': 'format' } log = logging.getLogger(__name__) HAS_HDPARM = salt.utils.path.which('hdparm') is not None HAS_IOSTAT = salt.utils.path.which('iostat') is not None def __virtual__(): ''' Only work on POSIX-like systems ''' if salt.utils.platform.is_windows(): return False, 'This module doesn\'t work on Windows.' return True def _parse_numbers(text): ''' Convert a string to a number, allowing for a K|M|G|T postfix, 32.8K. Returns a decimal number if the string is a real number, or the string unchanged otherwise. ''' if text.isdigit(): return decimal.Decimal(text) try: postPrefixes = {'K': '10E3', 'M': '10E6', 'G': '10E9', 'T': '10E12', 'P': '10E15', 'E': '10E18', 'Z': '10E21', 'Y': '10E24'} if text[-1] in postPrefixes.keys(): v = decimal.Decimal(text[:-1]) v = v * decimal.Decimal(postPrefixes[text[-1]]) return v else: return decimal.Decimal(text) except ValueError: return text def _clean_flags(args, caller): ''' Sanitize flags passed into df ''' flags = '' if args is None: return flags allowed = ('a', 'B', 'h', 'H', 'i', 'k', 'l', 'P', 't', 'T', 'x', 'v') for flag in args: if flag in allowed: flags += flag else: raise CommandExecutionError( 'Invalid flag passed to {0}'.format(caller) ) return flags def usage(args=None): ''' Return usage information for volumes mounted on this minion .. versionchanged:: 2019.2.0 Default for SunOS changed to 1 kilobyte blocks CLI Example: .. code-block:: bash salt '*' disk.usage ''' flags = _clean_flags(args, 'disk.usage') if not os.path.isfile('/etc/mtab') and __grains__['kernel'] == 'Linux': log.error('df cannot run without /etc/mtab') if __grains__.get('virtual_subtype') == 'LXC': log.error('df command failed and LXC detected. If you are running ' 'a Docker container, consider linking /proc/mounts to ' '/etc/mtab or consider running Docker with -privileged') return {} if __grains__['kernel'] == 'Linux': cmd = 'df -P' elif __grains__['kernel'] == 'OpenBSD' or __grains__['kernel'] == 'AIX': cmd = 'df -kP' elif __grains__['kernel'] == 'SunOS': cmd = 'df -k' else: cmd = 'df' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() oldline = None for line in out: if not line: continue if line.startswith('Filesystem'): continue if oldline: line = oldline + " " + line comps = line.split() if len(comps) == 1: oldline = line continue else: oldline = None while len(comps) >= 2 and not comps[1].isdigit(): comps[0] = '{0} {1}'.format(comps[0], comps[1]) comps.pop(1) if len(comps) < 2: continue try: if __grains__['kernel'] == 'Darwin': ret[comps[8]] = { 'filesystem': comps[0], '512-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], 'iused': comps[5], 'ifree': comps[6], '%iused': comps[7], } else: ret[comps[5]] = { 'filesystem': comps[0], '1K-blocks': comps[1], 'used': comps[2], 'available': comps[3], 'capacity': comps[4], } except IndexError: log.error('Problem parsing disk usage information') ret = {} return ret def inodeusage(args=None): ''' Return inode usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.inodeusage ''' flags = _clean_flags(args, 'disk.inodeusage') if __grains__['kernel'] == 'AIX': cmd = 'df -i' else: cmd = 'df -iP' if flags: cmd += ' -{0}'.format(flags) ret = {} out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() for line in out: if line.startswith('Filesystem'): continue comps = line.split() # Don't choke on empty lines if not comps: continue try: if __grains__['kernel'] == 'OpenBSD': ret[comps[8]] = { 'inodes': int(comps[5]) + int(comps[6]), 'used': comps[5], 'free': comps[6], 'use': comps[7], 'filesystem': comps[0], } elif __grains__['kernel'] == 'AIX': ret[comps[6]] = { 'inodes': comps[4], 'used': comps[5], 'free': comps[2], 'use': comps[5], 'filesystem': comps[0], } else: ret[comps[5]] = { 'inodes': comps[1], 'used': comps[2], 'free': comps[3], 'use': comps[4], 'filesystem': comps[0], } except (IndexError, ValueError): log.error('Problem parsing inode usage information') ret = {} return ret @salt.utils.decorators.path.which('blkid') def blkid(device=None, token=None): ''' Return block device attributes: UUID, LABEL, etc. This function only works on systems where blkid is available. device Device name from the system token Any valid token used for the search CLI Example: .. code-block:: bash salt '*' disk.blkid salt '*' disk.blkid /dev/sda salt '*' disk.blkid token='UUID=6a38ee5-7235-44e7-8b22-816a403bad5d' salt '*' disk.blkid token='TYPE=ext4' ''' cmd = ['blkid'] if device: cmd.append(device) elif token: cmd.extend(['-t', token]) ret = {} blkid_result = __salt__['cmd.run_all'](cmd, python_shell=False) if blkid_result['retcode'] > 0: return ret for line in blkid_result['stdout'].splitlines(): if not line: continue comps = line.split() device = comps[0][:-1] info = {} device_attributes = re.split(('\"*\"'), line.partition(' ')[2]) for key, value in zip(*[iter(device_attributes)]*2): key = key.strip('=').strip(' ') info[key] = value.strip('"') ret[device] = info return ret def tune(device, **kwargs): ''' Set attributes for the specified device CLI Example: .. code-block:: bash salt '*' disk.tune /dev/sda1 read-ahead=1024 read-write=True Valid options are: ``read-ahead``, ``filesystem-read-ahead``, ``read-only``, ``read-write``. See the ``blockdev(8)`` manpage for a more complete description of these options. ''' kwarg_map = {'read-ahead': 'setra', 'filesystem-read-ahead': 'setfra', 'read-only': 'setro', 'read-write': 'setrw'} opts = '' args = [] for key in kwargs: if key in kwarg_map: switch = kwarg_map[key] if key != 'read-write': args.append(switch.replace('set', 'get')) else: args.append('getro') if kwargs[key] == 'True' or kwargs[key] is True: opts += '--{0} '.format(key) else: opts += '--{0} {1} '.format(switch, kwargs[key]) cmd = 'blockdev {0}{1}'.format(opts, device) out = __salt__['cmd.run'](cmd, python_shell=False).splitlines() return dump(device, args) def wipe(device): ''' Remove the filesystem information CLI Example: .. code-block:: bash salt '*' disk.wipe /dev/sda1 ''' cmd = 'wipefs -a {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True else: log.error('Error wiping device %s: %s', device, out['stderr']) return False def dump(device, args=None): ''' Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' disk.dump /dev/sda1 ''' cmd = 'blockdev --getro --getsz --getss --getpbsz --getiomin --getioopt --getalignoff ' \ '--getmaxsect --getsize --getsize64 --getra --getfra {0}'.format(device) ret = {} opts = [c[2:] for c in cmd.split() if c.startswith('--')] out = __salt__['cmd.run_all'](cmd, python_shell=False) if out['retcode'] == 0: lines = [line for line in out['stdout'].splitlines() if line] count = 0 for line in lines: ret[opts[count]] = line count = count+1 if args: temp_ret = {} for arg in args: temp_ret[arg] = ret[arg] return temp_ret else: return ret else: return False def resize2fs(device): ''' Resizes the filesystem. CLI Example: .. code-block:: bash salt '*' disk.resize2fs /dev/sda1 ''' cmd = 'resize2fs {0}'.format(device) try: out = __salt__['cmd.run_all'](cmd, python_shell=False) except subprocess.CalledProcessError as err: return False if out['retcode'] == 0: return True @salt.utils.decorators.path.which('sync') @salt.utils.decorators.path.which('mkfs') def format_(device, fs_type='ext4', inode_size=None, lazy_itable_init=None, fat=None, force=False): ''' Format a filesystem onto a device .. versionadded:: 2016.11.0 device The device in which to create the new filesystem fs_type The type of filesystem to create inode_size Size of the inodes This option is only enabled for ext and xfs filesystems lazy_itable_init If enabled and the uninit_bg feature is enabled, the inode table will not be fully initialized by mke2fs. This speeds up filesystem initialization noticeably, but it requires the kernel to finish initializing the filesystem in the background when the filesystem is first mounted. If the option value is omitted, it defaults to 1 to enable lazy inode table zeroing. This option is only enabled for ext filesystems fat FAT size option. Can be 12, 16 or 32, and can only be used on fat or vfat filesystems. force Force mke2fs to create a filesystem, even if the specified device is not a partition on a block special device. This option is only enabled for ext and xfs filesystems This option is dangerous, use it with caution. CLI Example: .. code-block:: bash salt '*' disk.format /dev/sdX1 ''' cmd = ['mkfs', '-t', six.text_type(fs_type)] if inode_size is not None: if fs_type[:3] == 'ext': cmd.extend(['-i', six.text_type(inode_size)]) elif fs_type == 'xfs': cmd.extend(['-i', 'size={0}'.format(inode_size)]) if lazy_itable_init is not None: if fs_type[:3] == 'ext': cmd.extend(['-E', 'lazy_itable_init={0}'.format(lazy_itable_init)]) if fat is not None and fat in (12, 16, 32): if fs_type[-3:] == 'fat': cmd.extend(['-F', fat]) if force: if fs_type[:3] == 'ext': cmd.append('-F') elif fs_type == 'xfs': cmd.append('-f') cmd.append(six.text_type(device)) mkfs_success = __salt__['cmd.retcode'](cmd, ignore_retcode=True) == 0 sync_success = __salt__['cmd.retcode']('sync', ignore_retcode=True) == 0 return all([mkfs_success, sync_success]) @salt.utils.decorators.path.which_bin(['lsblk', 'df']) def fstype(device): ''' Return the filesystem name of the specified device .. versionadded:: 2016.11.0 device The name of the device CLI Example: .. code-block:: bash salt '*' disk.fstype /dev/sdX1 ''' if salt.utils.path.which('lsblk'): lsblk_out = __salt__['cmd.run']('lsblk -o fstype {0}'.format(device)).splitlines() if len(lsblk_out) > 1: fs_type = lsblk_out[1].strip() if fs_type: return fs_type if salt.utils.path.which('df'): # the fstype was not set on the block device, so inspect the filesystem # itself for its type if __grains__['kernel'] == 'AIX' and os.path.isfile('/usr/sysv/bin/df'): df_out = __salt__['cmd.run']('/usr/sysv/bin/df -n {0}'.format(device)).split() if len(df_out) > 2: fs_type = df_out[2] if fs_type: return fs_type else: df_out = __salt__['cmd.run']('df -T {0}'.format(device)).splitlines() if len(df_out) > 1: fs_type = df_out[1] if fs_type: return fs_type return '' @salt.utils.decorators.depends(HAS_HDPARM) def _hdparm(args, failhard=True): ''' Execute hdparm Fail hard when required return output when possible ''' cmd = 'hdparm {0}'.format(args) result = __salt__['cmd.run_all'](cmd) if result['retcode'] != 0: msg = '{0}: {1}'.format(cmd, result['stderr']) if failhard: raise CommandExecutionError(msg) else: log.warning(msg) return result['stdout'] @salt.utils.decorators.depends(HAS_HDPARM) def hdparms(disks, args=None): ''' Retrieve all info's for all disks parse 'em into a nice dict (which, considering hdparms output, is quite a hassle) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hdparms /dev/sda ''' all_parms = 'aAbBcCdgHiJkMmNnQrRuW' if args is None: args = all_parms elif isinstance(args, (list, tuple)): args = ''.join(args) if not isinstance(disks, (list, tuple)): disks = [disks] out = {} for disk in disks: if not disk.startswith('/dev'): disk = '/dev/{0}'.format(disk) disk_data = {} for line in _hdparm('-{0} {1}'.format(args, disk), False).splitlines(): line = line.strip() if not line or line == disk + ':': continue if ':' in line: key, vals = line.split(':', 1) key = re.sub(r' is$', '', key) elif '=' in line: key, vals = line.split('=', 1) else: continue key = key.strip().lower().replace(' ', '_') vals = vals.strip() rvals = [] if re.match(r'[0-9]+ \(.*\)', vals): vals = vals.split(' ') rvals.append(int(vals[0])) rvals.append(vals[1].strip('()')) else: valdict = {} for val in re.split(r'[/,]', vals.strip()): val = val.strip() try: val = int(val) rvals.append(val) except Exception: if '=' in val: deep_key, val = val.split('=', 1) deep_key = deep_key.strip() val = val.strip() if val: valdict[deep_key] = val elif val: rvals.append(val) if valdict: rvals.append(valdict) if not rvals: continue elif len(rvals) == 1: rvals = rvals[0] disk_data[key] = rvals out[disk] = disk_data return out @salt.utils.decorators.depends(HAS_HDPARM) def hpa(disks, size=None): ''' Get/set Host Protected Area settings T13 INCITS 346-2001 (1367D) defines the BEER (Boot Engineering Extension Record) and PARTIES (Protected Area Run Time Interface Extension Services), allowing for a Host Protected Area on a disk. It's often used by OEMS to hide parts of a disk, and for overprovisioning SSD's .. warning:: Setting the HPA might clobber your data, be very careful with this on active disks! .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.hpa /dev/sda salt '*' disk.hpa /dev/sda 5% salt '*' disk.hpa /dev/sda 10543256 ''' hpa_data = {} for disk, data in hdparms(disks, 'N').items(): visible, total, status = data.values()[0] if visible == total or 'disabled' in status: hpa_data[disk] = { 'total': total } else: hpa_data[disk] = { 'total': total, 'visible': visible, 'hidden': total - visible } if size is None: return hpa_data for disk, data in hpa_data.items(): try: size = data['total'] - int(size) except Exception: if '%' in size: size = int(size.strip('%')) size = (100 - size) * data['total'] size /= 100 if size <= 0: size = data['total'] _hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk)) def smart_attributes(dev, attributes=None, values=None): ''' Fetch SMART attributes Providing attributes will deliver only requested attributes Providing values will deliver only requested values for attributes Default is the Backblaze recommended set (https://www.backblaze.com/blog/hard-drive-smart-stats/): (5,187,188,197,198) .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' disk.smart_attributes /dev/sda salt '*' disk.smart_attributes /dev/sda attributes=(5,187,188,197,198) ''' if not dev.startswith('/dev/'): dev = '/dev/' + dev cmd = 'smartctl --attributes {0}'.format(dev) smart_result = __salt__['cmd.run_all'](cmd, output_loglevel='quiet') if smart_result['retcode'] != 0: raise CommandExecutionError(smart_result['stderr']) smart_result = iter(smart_result['stdout'].splitlines()) fields = [] for line in smart_result: if line.startswith('ID#'): fields = re.split(r'\s+', line.strip()) fields = [key.lower() for key in fields[1:]] break if values is not None: fields = [field if field in values else '_' for field in fields] smart_attr = {} for line in smart_result: if not re.match(r'[\s]*\d', line): break line = re.split(r'\s+', line.strip(), maxsplit=len(fields)) attr = int(line[0]) if attributes is not None and attr not in attributes: continue data = dict(zip(fields, line[1:])) try: del data['_'] except Exception: pass for field in data: val = data[field] try: val = int(val) except Exception: try: val = [int(value) for value in val.split(' ')] except Exception: pass data[field] = val smart_attr[attr] = data return smart_attr @salt.utils.decorators.depends(HAS_IOSTAT) def iostat(interval=1, count=5, disks=None): ''' Gather and return (averaged) IO stats. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' disk.iostat 1 5 disks=sda ''' if salt.utils.platform.is_linux(): return _iostat_linux(interval, count, disks) elif salt.utils.platform.is_freebsd(): return _iostat_fbsd(interval, count, disks) elif salt.utils.platform.is_aix(): return _iostat_aix(interval, count, disks) def _iostats_dict(header, stats): ''' Transpose collected data, average it, stomp it in dict using header Use Decimals so we can properly calc & round, convert to float 'caus' we can't transmit Decimals over 0mq ''' stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)] stats = dict(zip(header, stats)) return stats def _iostat_fbsd(interval, count, disks): ''' Tested on FreeBSD, quite likely other BSD's only need small changes in cmd syntax ''' if disks is None: iostat_cmd = 'iostat -xC -w {0} -c {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -x -w {0} -c {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] h_len = 1000 # randomly absurdly high ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if not line.startswith('device'): continue elif not dev_header: dev_header = line.split()[1:] while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] # h_len will become smallest number of fields in stat lines if len(stats) < h_len: h_len = len(stats) dev_stats[disk].append(stats) iostats = {} # The header was longer than the smallest number of fields # Therefore the sys stats are hidden in there if h_len < len(dev_header): sys_header = dev_header[h_len:] dev_header = dev_header[0:h_len] for disk, stats in dev_stats.items(): if len(stats[0]) > h_len: sys_stats = [stat[h_len:] for stat in stats] dev_stats[disk] = [stat[0:h_len] for stat in stats] iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_linux(interval, count, disks): if disks is None: iostat_cmd = 'iostat -x {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, disks) else: iostat_cmd = 'iostat -xd {0} {1} {2}'.format(interval, count, ' '.join(disks)) sys_stats = [] dev_stats = collections.defaultdict(list) sys_header = [] dev_header = [] ret = iter(__salt__['cmd.run_stdout'](iostat_cmd, output_loglevel='quiet').splitlines()) for line in ret: if line.startswith('avg-cpu:'): if not sys_header: sys_header = tuple(line.split()[1:]) line = [decimal.Decimal(x) for x in next(ret).split()] sys_stats.append(line) elif line.startswith('Device:'): if not dev_header: dev_header = tuple(line.split()[1:]) while line is not False: line = next(ret, False) if not line or not line[0].isalnum(): break line = line.split() disk = line[0] stats = [decimal.Decimal(x) for x in line[1:]] dev_stats[disk].append(stats) iostats = {} if sys_header: iostats['sys'] = _iostats_dict(sys_header, sys_stats) for disk, stats in dev_stats.items(): iostats[disk] = _iostats_dict(dev_header, stats) return iostats def _iostat_aix(interval, count, disks): ''' AIX support to gather and return (averaged) IO stats. ''' log.debug('DGM disk iostat entry') if disks is None: iostat_cmd = 'iostat -dD {0} {1} '.format(interval, count) elif isinstance(disks, six.string_types): iostat_cmd = 'iostat -dD {0} {1} {2}'.format(disks, interval, count) else: iostat_cmd = 'iostat -dD {0} {1} {2}'.format(' '.join(disks), interval, count) ret = {} procn = None fields = [] disk_name = '' disk_mode = '' dev_stats = collections.defaultdict(list) for line in __salt__['cmd.run'](iostat_cmd).splitlines(): # Note: iostat -dD is per-system # #root@l490vp031_pub:~/devtest# iostat -dD hdisk6 1 3 # #System configuration: lcpu=8 drives=1 paths=2 vdisks=2 # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 9.6 16.4K 4.0 16.4K 0.0 # read: rps avgserv minserv maxserv timeouts fails # 4.0 4.9 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- # #hdisk6 xfer: %tm_act bps tps bread bwrtn # 0.0 0.0 0.0 0.0 0.0 # read: rps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.3 9.9 0 0 # write: wps avgserv minserv maxserv timeouts fails # 0.0 0.0 0.0 0.0 0 0 # queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull # 0.0 0.0 0.0 0.0 0.0 0.0 #-------------------------------------------------------------------------------- if not line or line.startswith('System') or line.startswith('-----------'): continue if not re.match(r'\s', line): #seen disk name dsk_comps = line.split(':') dsk_firsts = dsk_comps[0].split() disk_name = dsk_firsts[0] disk_mode = dsk_firsts[1] fields = dsk_comps[1].split() if disk_name not in dev_stats.keys(): dev_stats[disk_name] = [] procn = len(dev_stats[disk_name]) dev_stats[disk_name].append({}) dev_stats[disk_name][procn][disk_mode] = {} dev_stats[disk_name][procn][disk_mode]['fields'] = fields dev_stats[disk_name][procn][disk_mode]['stats'] = [] continue if ':' in line: comps = line.split(':') fields = comps[1].split() disk_mode = comps[0].lstrip() if disk_mode not in dev_stats[disk_name][0].keys(): dev_stats[disk_name][0][disk_mode] = {} dev_stats[disk_name][0][disk_mode]['fields'] = fields dev_stats[disk_name][0][disk_mode]['stats'] = [] else: line = line.split() stats = [_parse_numbers(x) for x in line[:]] dev_stats[disk_name][0][disk_mode]['stats'].append(stats) iostats = {} for disk, list_modes in dev_stats.items(): iostats[disk] = {} for modes in list_modes: for disk_mode in modes.keys(): fields = modes[disk_mode]['fields'] stats = modes[disk_mode]['stats'] iostats[disk][disk_mode] = _iostats_dict(fields, stats) return iostats