repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/boto_vpc.py
route_table_exists
def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
python
def route_table_exists(route_table_id=None, name=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d' ''' if name: log.warning('boto_vpc.route_table_exists: name parameter is deprecated ' 'use route_table_name instead.') route_table_name = name return resource_exists('route_table', name=route_table_name, resource_id=route_table_id, tags=tags, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "route_table_exists", "(", "route_table_id", "=", "None", ",", "name", "=", "None", ",", "route_table_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "...
Checks if a route table exists. CLI Example: .. code-block:: bash salt myminion boto_vpc.route_table_exists route_table_id='rtb-1f382e7d'
[ "Checks", "if", "a", "route", "table", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2092-L2113
train
saltstack/salt
salt/modules/boto_vpc.py
route_exists
def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def route_exists(destination_cidr_block, route_table_name=None, route_table_id=None, gateway_id=None, instance_id=None, interface_id=None, tags=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test' ''' if not any((route_table_name, route_table_id)): raise SaltInvocationError('At least one of the following must be specified: route table name or route table id.') if not any((gateway_id, instance_id, interface_id, vpc_peering_connection_id)): raise SaltInvocationError('At least one of the following must be specified: gateway id, instance id, ' 'interface id or VPC peering connection id.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = [route_table_id] if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if len(route_tables) != 1: raise SaltInvocationError('Found more than one route table.') route_check = {'destination_cidr_block': destination_cidr_block, 'gateway_id': gateway_id, 'instance_id': instance_id, 'interface_id': interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } for route_match in route_tables[0].routes: route_dict = {'destination_cidr_block': route_match.destination_cidr_block, 'gateway_id': route_match.gateway_id, 'instance_id': route_match.instance_id, 'interface_id': route_match.interface_id, 'vpc_peering_connection_id': vpc_peering_connection_id } route_comp = set(route_dict.items()) ^ set(route_check.items()) if not route_comp: log.info('Route %s exists.', destination_cidr_block) return {'exists': True} log.warning('Route %s does not exist.', destination_cidr_block) return {'exists': False} except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "route_exists", "(", "destination_cidr_block", ",", "route_table_name", "=", "None", ",", "route_table_id", "=", "None", ",", "gateway_id", "=", "None", ",", "instance_id", "=", "None", ",", "interface_id", "=", "None", ",", "tags", "=", "None", ",", ...
Checks if a route exists. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.route_exists destination_cidr_block='10.0.0.0/20' gateway_id='local' route_table_name='test'
[ "Checks", "if", "a", "route", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2116-L2181
train
saltstack/salt
salt/modules/boto_vpc.py
associate_route_table
def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
python
def associate_route_table(route_table_id=None, subnet_id=None, route_table_name=None, subnet_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet' ''' if all((subnet_id, subnet_name)): raise SaltInvocationError('Only one of subnet_name or subnet_id may be ' 'provided.') if subnet_name: subnet_id = _get_resource_id('subnet', subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not subnet_id: return {'associated': False, 'error': {'message': 'Subnet {0} does not exist.'.format(subnet_name)}} if all((route_table_id, route_table_name)): raise SaltInvocationError('Only one of route_table_name or route_table_id may be ' 'provided.') if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'associated': False, 'error': {'message': 'Route table {0} does not exist.'.format(route_table_name)}} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.associate_route_table(route_table_id, subnet_id) log.info('Route table %s was associated with subnet %s', route_table_id, subnet_id) return {'association_id': association_id} except BotoServerError as e: return {'associated': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "associate_route_table", "(", "route_table_id", "=", "None", ",", "subnet_id", "=", "None", ",", "route_table_name", "=", "None", ",", "subnet_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", ...
Given a route table and subnet name or id, associates the route table with the subnet. CLI Example: .. code-block:: bash salt myminion boto_vpc.associate_route_table 'rtb-1f382e7d' 'subnet-6a1fe403' .. code-block:: bash salt myminion boto_vpc.associate_route_table route_table_name='myrtb' \\ subnet_name='mysubnet'
[ "Given", "a", "route", "table", "and", "subnet", "name", "or", "id", "associates", "the", "route", "table", "with", "the", "subnet", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2184-L2233
train
saltstack/salt
salt/modules/boto_vpc.py
disassociate_route_table
def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}
python
def disassociate_route_table(association_id, region=None, key=None, keyid=None, profile=None): ''' Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.disassociate_route_table(association_id): log.info('Route table with association id %s has been disassociated.', association_id) return {'disassociated': True} else: log.warning('Route table with association id %s has not been disassociated.', association_id) return {'disassociated': False} except BotoServerError as e: return {'disassociated': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "disassociate_route_table", "(", "association_id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "k...
Dissassociates a route table. association_id The Route Table Association ID to disassociate CLI Example: .. code-block:: bash salt myminion boto_vpc.disassociate_route_table 'rtbassoc-d8ccddba'
[ "Dissassociates", "a", "route", "table", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2236-L2260
train
saltstack/salt
salt/modules/boto_vpc.py
replace_route_table_association
def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)}
python
def replace_route_table_association(association_id, route_table_id, region=None, key=None, keyid=None, profile=None): ''' Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) association_id = conn.replace_route_table_association_with_assoc(association_id, route_table_id) log.info('Route table %s was reassociated with association id %s', route_table_id, association_id) return {'replaced': True, 'association_id': association_id} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "replace_route_table_association", "(", "association_id", ",", "route_table_id", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "regio...
Replaces a route table association. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route_table_association 'rtbassoc-d8ccddba' 'rtb-1f382e7d'
[ "Replaces", "a", "route", "table", "association", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2263-L2282
train
saltstack/salt
salt/modules/boto_vpc.py
create_route
def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
python
def create_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, internet_gateway_name=None, instance_id=None, interface_id=None, vpc_peering_connection_id=None, vpc_peering_connection_name=None, region=None, key=None, keyid=None, profile=None, nat_gateway_id=None, nat_gateway_subnet_name=None, nat_gateway_subnet_id=None, ): ''' Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if not _exactly_one((gateway_id, internet_gateway_name, instance_id, interface_id, vpc_peering_connection_id, nat_gateway_id, nat_gateway_subnet_id, nat_gateway_subnet_name, vpc_peering_connection_name)): raise SaltInvocationError('Only one of gateway_id, internet_gateway_name, instance_id, ' 'interface_id, vpc_peering_connection_id, nat_gateway_id, ' 'nat_gateway_subnet_id, nat_gateway_subnet_name or vpc_peering_connection_name may be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} if internet_gateway_name: gateway_id = _get_resource_id('internet_gateway', internet_gateway_name, region=region, key=key, keyid=keyid, profile=profile) if not gateway_id: return {'created': False, 'error': {'message': 'internet gateway {0} does not exist.'.format(internet_gateway_name)}} if vpc_peering_connection_name: vpc_peering_connection_id = _get_resource_id('vpc_peering_connection', vpc_peering_connection_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_peering_connection_id: return {'created': False, 'error': {'message': 'VPC peering connection {0} does not exist.'.format(vpc_peering_connection_name)}} if nat_gateway_subnet_name: gws = describe_nat_gateways(subnet_name=nat_gateway_subnet_name, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_name)}} nat_gateway_id = gws[0]['NatGatewayId'] if nat_gateway_subnet_id: gws = describe_nat_gateways(subnet_id=nat_gateway_subnet_id, region=region, key=key, keyid=keyid, profile=profile) if not gws: return {'created': False, 'error': {'message': 'nat gateway for {0} does not exist.'.format(nat_gateway_subnet_id)}} nat_gateway_id = gws[0]['NatGatewayId'] except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} if not nat_gateway_id: return _create_resource('route', route_table_id=route_table_id, destination_cidr_block=destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id, region=region, key=key, keyid=keyid, profile=profile) # for nat gateway, boto3 is required try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) ret = conn3.create_route(RouteTableId=route_table_id, DestinationCidrBlock=destination_cidr_block, NatGatewayId=nat_gateway_id) return {'created': True, 'id': ret.get('NatGatewayId')} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "create_route", "(", "route_table_id", "=", "None", ",", "destination_cidr_block", "=", "None", ",", "route_table_name", "=", "None", ",", "gateway_id", "=", "None", ",", "internet_gateway_name", "=", "None", ",", "instance_id", "=", "None", ",", "interfa...
Creates a route. If a nat gateway is specified, boto3 must be installed CLI Example: .. code-block:: bash salt myminion boto_vpc.create_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3'
[ "Creates", "a", "route", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2285-L2379
train
saltstack/salt
salt/modules/boto_vpc.py
delete_route
def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile)
python
def delete_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, region=None, key=None, keyid=None, profile=None): ''' Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'created': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} except BotoServerError as e: return {'created': False, 'error': __utils__['boto.get_error'](e)} return _delete_resource(resource='route', resource_id=route_table_id, destination_cidr_block=destination_cidr_block, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "delete_route", "(", "route_table_id", "=", "None", ",", "destination_cidr_block", "=", "None", ",", "route_table_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ...
Deletes a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.delete_route 'rtb-1f382e7d' '10.0.0.0/16'
[ "Deletes", "a", "route", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2382-L2417
train
saltstack/salt
salt/modules/boto_vpc.py
replace_route
def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)}
python
def replace_route(route_table_id=None, destination_cidr_block=None, route_table_name=None, gateway_id=None, instance_id=None, interface_id=None, region=None, key=None, keyid=None, profile=None, vpc_peering_connection_id=None): ''' Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3' ''' if not _exactly_one((route_table_name, route_table_id)): raise SaltInvocationError('One (but not both) of route_table_id or route_table_name ' 'must be provided.') if destination_cidr_block is None: raise SaltInvocationError('destination_cidr_block is required.') try: if route_table_name: route_table_id = _get_resource_id('route_table', route_table_name, region=region, key=key, keyid=keyid, profile=profile) if not route_table_id: return {'replaced': False, 'error': {'message': 'route table {0} does not exist.'.format(route_table_name)}} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.replace_route(route_table_id, destination_cidr_block, gateway_id=gateway_id, instance_id=instance_id, interface_id=interface_id, vpc_peering_connection_id=vpc_peering_connection_id): log.info( 'Route with cidr block %s on route table %s was replaced', route_table_id, destination_cidr_block ) return {'replaced': True} else: log.warning( 'Route with cidr block %s on route table %s was not replaced', route_table_id, destination_cidr_block ) return {'replaced': False} except BotoServerError as e: return {'replaced': False, 'error': __utils__['boto.get_error'](e)}
[ "def", "replace_route", "(", "route_table_id", "=", "None", ",", "destination_cidr_block", "=", "None", ",", "route_table_name", "=", "None", ",", "gateway_id", "=", "None", ",", "instance_id", "=", "None", ",", "interface_id", "=", "None", ",", "region", "=",...
Replaces a route. CLI Example: .. code-block:: bash salt myminion boto_vpc.replace_route 'rtb-1f382e7d' '10.0.0.0/16' gateway_id='vgw-a1b2c3'
[ "Replaces", "a", "route", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2420-L2468
train
saltstack/salt
salt/modules/boto_vpc.py
describe_route_table
def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def describe_route_table(route_table_id=None, route_table_name=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d' ''' salt.utils.versions.warn_until( 'Neon', 'The \'describe_route_table\' method has been deprecated and ' 'replaced by \'describe_route_tables\'.' ) if not any((route_table_id, route_table_name, tags)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, or tags.') try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'filters': {}} if route_table_id: filter_parameters['route_table_ids'] = route_table_id if route_table_name: filter_parameters['filters']['tag:Name'] = route_table_name if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['filters']['tag:{0}'.format(tag_name)] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) if not route_tables: return {} route_table = {} keys = ['id', 'vpc_id', 'tags', 'routes', 'associations'] route_keys = ['destination_cidr_block', 'gateway_id', 'instance_id', 'interface_id', 'vpc_peering_connection_id'] assoc_keys = ['id', 'main', 'route_table_id', 'subnet_id'] for item in route_tables: for key in keys: if hasattr(item, key): route_table[key] = getattr(item, key) if key == 'routes': route_table[key] = _key_iter(key, route_keys, item) if key == 'associations': route_table[key] = _key_iter(key, assoc_keys, item) return route_table except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "describe_route_table", "(", "route_table_id", "=", "None", ",", "route_table_name", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "s...
Given route table properties, return route table details if matching table(s) exist. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_table route_table_id='rtb-1f382e7d'
[ "Given", "route", "table", "properties", "return", "route", "table", "details", "if", "matching", "table", "(", "s", ")", "exist", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2471-L2529
train
saltstack/salt
salt/modules/boto_vpc.py
describe_route_tables
def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
python
def describe_route_tables(route_table_id=None, route_table_name=None, vpc_id=None, tags=None, region=None, key=None, keyid=None, profile=None): ''' Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3' ''' if not any((route_table_id, route_table_name, tags, vpc_id)): raise SaltInvocationError('At least one of the following must be specified: ' 'route table id, route table name, vpc_id, or tags.') try: conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filter_parameters = {'Filters': []} if route_table_id: filter_parameters['RouteTableIds'] = [route_table_id] if vpc_id: filter_parameters['Filters'].append({'Name': 'vpc-id', 'Values': [vpc_id]}) if route_table_name: filter_parameters['Filters'].append({'Name': 'tag:Name', 'Values': [route_table_name]}) if tags: for tag_name, tag_value in six.iteritems(tags): filter_parameters['Filters'].append({'Name': 'tag:{0}'.format(tag_name), 'Values': [tag_value]}) route_tables = conn3.describe_route_tables(**filter_parameters).get('RouteTables', []) if not route_tables: return [] tables = [] keys = {'id': 'RouteTableId', 'vpc_id': 'VpcId', 'tags': 'Tags', 'routes': 'Routes', 'associations': 'Associations' } route_keys = {'destination_cidr_block': 'DestinationCidrBlock', 'gateway_id': 'GatewayId', 'instance_id': 'Instance', 'interface_id': 'NetworkInterfaceId', 'nat_gateway_id': 'NatGatewayId', 'vpc_peering_connection_id': 'VpcPeeringConnectionId', } assoc_keys = {'id': 'RouteTableAssociationId', 'main': 'Main', 'route_table_id': 'RouteTableId', 'SubnetId': 'subnet_id', } for item in route_tables: route_table = {} for outkey, inkey in six.iteritems(keys): if inkey in item: if outkey == 'routes': route_table[outkey] = _key_remap(inkey, route_keys, item) elif outkey == 'associations': route_table[outkey] = _key_remap(inkey, assoc_keys, item) elif outkey == 'tags': route_table[outkey] = {} for tagitem in item.get(inkey, []): route_table[outkey][tagitem.get('Key')] = tagitem.get('Value') else: route_table[outkey] = item.get(inkey) tables.append(route_table) return tables except BotoServerError as e: return {'error': __utils__['boto.get_error'](e)}
[ "def", "describe_route_tables", "(", "route_table_id", "=", "None", ",", "route_table_name", "=", "None", ",", "vpc_id", "=", "None", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile"...
Given route table properties, return details of all matching route tables. This function requires boto3 to be installed. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_route_tables vpc_id='vpc-a6a9efc3'
[ "Given", "route", "table", "properties", "return", "details", "of", "all", "matching", "route", "tables", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2532-L2615
train
saltstack/salt
salt/modules/boto_vpc.py
_get_subnet_explicit_route_table
def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None
python
def _get_subnet_explicit_route_table(subnet_id, vpc_id, conn=None, region=None, key=None, keyid=None, profile=None): ''' helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0 ''' if not conn: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn: vpc_route_tables = conn.get_all_route_tables(filters={'vpc_id': vpc_id}) for vpc_route_table in vpc_route_tables: for rt_association in vpc_route_table.associations: if rt_association.subnet_id == subnet_id and not rt_association.main: return rt_association.id return None
[ "def", "_get_subnet_explicit_route_table", "(", "subnet_id", ",", "vpc_id", ",", "conn", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "conn", ":", "conn...
helper function to find subnet explicit route table associations .. versionadded:: 2016.11.0
[ "helper", "function", "to", "find", "subnet", "explicit", "route", "table", "associations" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2694-L2708
train
saltstack/salt
salt/modules/boto_vpc.py
request_vpc_peering_connection
def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)}
python
def request_vpc_peering_connection(requester_vpc_id=None, requester_vpc_name=None, peer_vpc_id=None, peer_vpc_name=None, name=None, peer_owner_id=None, peer_region=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name and _vpc_peering_conn_id_for_name(name, conn): raise SaltInvocationError('A VPC peering connection with this name already ' 'exists! Please specify a different name.') if not _exactly_one((requester_vpc_id, requester_vpc_name)): raise SaltInvocationError('Exactly one of requester_vpc_id or ' 'requester_vpc_name is required') if not _exactly_one((peer_vpc_id, peer_vpc_name)): raise SaltInvocationError('Exactly one of peer_vpc_id or ' 'peer_vpc_name is required.') if requester_vpc_name: requester_vpc_id = _get_id(vpc_name=requester_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not requester_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(requester_vpc_name)} if peer_vpc_name: peer_vpc_id = _get_id(vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not peer_vpc_id: return {'error': 'Could not resolve VPC name {0} to an ID'.format(peer_vpc_name)} peering_params = {"VpcId": requester_vpc_id, "PeerVpcId": peer_vpc_id, "DryRun": dry_run} if peer_owner_id: peering_params.update({"PeerOwnerId": peer_owner_id}) if peer_region: peering_params.update({"PeerRegion": peer_region}) try: log.debug('Trying to request vpc peering connection') vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get('VpcPeeringConnection', {}) peering_conn_id = peering.get('VpcPeeringConnectionId', 'ERROR') msg = 'VPC peering {0} requested.'.format(peering_conn_id) log.debug(msg) if name: log.debug('Adding name tag to vpc peering connection') conn.create_tags( Resources=[peering_conn_id], Tags=[{'Key': 'Name', 'Value': name}] ) log.debug('Applied name tag to vpc peering connection') msg += ' With name {0}.'.format(name) return {'msg': msg} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to request vpc peering') return {'error': __utils__['boto.get_error'](err)}
[ "def", "request_vpc_peering_connection", "(", "requester_vpc_id", "=", "None", ",", "requester_vpc_name", "=", "None", ",", "peer_vpc_id", "=", "None", ",", "peer_vpc_name", "=", "None", ",", "name", "=", "None", ",", "peer_owner_id", "=", "None", ",", "peer_reg...
Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 requester_vpc_id ID of the requesting VPC. Exclusive with requester_vpc_name. requester_vpc_name Name tag of the requesting VPC. Exclusive with requester_vpc_id. peer_vpc_id ID of the VPC to create VPC peering connection with. This can be a VPC in another account. Exclusive with peer_vpc_name. peer_vpc_name Name tag of the VPC to create VPC peering connection with. This can only be a VPC in the same account and same region, else resolving it into a vpc ID will almost certainly fail. Exclusive with peer_vpc_id. name The name to use for this VPC peering connection. peer_owner_id ID of the owner of the peer VPC. Defaults to your account ID, so a value is required if peering with a VPC in a different account. peer_region Region of peer VPC. For inter-region vpc peering connections. Not required for intra-region peering connections. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and return status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da name=my_vpc_connection # Without a name salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da # Specify a region salt myminion boto_vpc.request_vpc_peering_connection vpc-4a3e622e vpc-be82e9da region=us-west-2
[ "Request", "a", "VPC", "peering", "connection", "between", "two", "VPCs", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2711-L2826
train
saltstack/salt
salt/modules/boto_vpc.py
_get_peering_connection_ids
def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings]
python
def _get_peering_connection_ids(name, conn): ''' :param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name. ''' filters = [{ 'Name': 'tag:Name', 'Values': [name], }, { 'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING], }] peerings = conn.describe_vpc_peering_connections( Filters=filters).get('VpcPeeringConnections', []) return [x['VpcPeeringConnectionId'] for x in peerings]
[ "def", "_get_peering_connection_ids", "(", "name", ",", "conn", ")", ":", "filters", "=", "[", "{", "'Name'", ":", "'tag:Name'", ",", "'Values'", ":", "[", "name", "]", ",", "}", ",", "{", "'Name'", ":", "'status-code'", ",", "'Values'", ":", "[", "ACT...
:param name: The name of the VPC peering connection. :type name: String :param conn: The boto aws ec2 connection. :return: The id associated with this peering connection Returns the VPC peering connection ids given the VPC peering connection name.
[ ":", "param", "name", ":", "The", "name", "of", "the", "VPC", "peering", "connection", ".", ":", "type", "name", ":", "String", ":", "param", "conn", ":", "The", "boto", "aws", "ec2", "connection", ".", ":", "return", ":", "The", "id", "associated", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2829-L2850
train
saltstack/salt
salt/modules/boto_vpc.py
describe_vpc_peering_connection
def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) }
python
def describe_vpc_peering_connection(name, region=None, key=None, keyid=None, profile=None): ''' Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2 ''' conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) return { 'VPC-Peerings': _get_peering_connection_ids(name, conn) }
[ "def", "describe_vpc_peering_connection", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn3", "(", "region", "=", "region", ",", "key", "=", "key...
Returns any VPC peering connection id(s) for the given VPC peering connection name. VPC peering connection ids are only returned for connections that are in the ``active``, ``pending-acceptance`` or ``provisioning`` state. .. versionadded:: 2016.11.0 :param name: The string name for this VPC peering connection :param region: The aws region to use :param key: Your aws key :param keyid: The key id associated with this aws account :param profile: The profile to use :return: dict CLI Example: .. code-block:: bash salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc # Specify a region salt myminion boto_vpc.describe_vpc_peering_connection salt-vpc region=us-west-2
[ "Returns", "any", "VPC", "peering", "connection", "id", "(", "s", ")", "for", "the", "given", "VPC", "peering", "connection", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2853-L2888
train
saltstack/salt
salt/modules/boto_vpc.py
accept_vpc_peering_connection
def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)}
python
def accept_vpc_peering_connection( # pylint: disable=too-many-arguments conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, name)): raise SaltInvocationError('One (but not both) of ' 'vpc_peering_connection_id or name ' 'must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if name: conn_id = _vpc_peering_conn_id_for_name(name, conn) if not conn_id: raise SaltInvocationError('No ID found for this ' 'VPC peering connection! ({0}) ' 'Please make sure this VPC peering ' 'connection exists ' 'or invoke this function with ' 'a VPC peering connection ' 'ID'.format(name)) try: log.debug('Trying to accept vpc peering connection') conn.accept_vpc_peering_connection( DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection accepted.'} except botocore.exceptions.ClientError as err: log.error('Got an error while trying to accept vpc peering') return {'error': __utils__['boto.get_error'](err)}
[ "def", "accept_vpc_peering_connection", "(", "# pylint: disable=too-many-arguments", "conn_id", "=", "''", ",", "name", "=", "''", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "dry_run", "=...
Request a VPC peering connection between two VPCs. .. versionadded:: 2016.11.0 :param conn_id: The ID to use. String type. :param name: The name of this VPC peering connection. String type. :param region: The AWS region to use. Type string. :param key: The key to use for this connection. Type string. :param keyid: The key id to use. :param profile: The profile to use. :param dry_run: The dry_run flag to set. :return: dict Warning: Please specify either the ``vpc_peering_connection_id`` or ``name`` but not both. Specifying both will result in an error! CLI Example: .. code-block:: bash salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc # Specify a region salt myminion boto_vpc.accept_vpc_peering_connection name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.accept_vpc_peering_connection conn_id=pcx-8a8939e3
[ "Request", "a", "VPC", "peering", "connection", "between", "two", "VPCs", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2891-L2953
train
saltstack/salt
salt/modules/boto_vpc.py
_vpc_peering_conn_id_for_name
def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0]
python
def _vpc_peering_conn_id_for_name(name, conn): ''' Get the ID associated with this name ''' log.debug('Retrieving VPC peering connection id') ids = _get_peering_connection_ids(name, conn) if not ids: ids = [None] # Let callers handle the case where we have no id elif len(ids) > 1: raise SaltInvocationError('Found multiple VPC peering connections ' 'with the same name!! ' 'Please make sure you have only ' 'one VPC peering connection named {0} ' 'or invoke this function with a VPC ' 'peering connection ID'.format(name)) return ids[0]
[ "def", "_vpc_peering_conn_id_for_name", "(", "name", ",", "conn", ")", ":", "log", ".", "debug", "(", "'Retrieving VPC peering connection id'", ")", "ids", "=", "_get_peering_connection_ids", "(", "name", ",", "conn", ")", "if", "not", "ids", ":", "ids", "=", ...
Get the ID associated with this name
[ "Get", "the", "ID", "associated", "with", "this", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2956-L2972
train
saltstack/salt
salt/modules/boto_vpc.py
delete_vpc_peering_connection
def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e}
python
def delete_vpc_peering_connection(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None, dry_run=False): ''' Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or ' 'conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_name: conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError("Couldn't resolve VPC peering connection " "{0} to an ID".format(conn_name)) try: log.debug('Trying to delete vpc peering connection') conn.delete_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id) return {'msg': 'VPC peering connection deleted.'} except botocore.exceptions.ClientError as err: e = __utils__['boto.get_error'](err) log.error('Failed to delete VPC peering %s: %s', conn_name or conn_id, e) return {'error': e}
[ "def", "delete_vpc_peering_connection", "(", "conn_id", "=", "None", ",", "conn_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "dry_run", "=", "False", ")", ":", "if...
Delete a VPC peering connection. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. dry_run If True, skip application and simply return projected status. CLI Example: .. code-block:: bash # Create a named VPC peering connection salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc # Specify a region salt myminion boto_vpc.delete_vpc_peering_connection conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3
[ "Delete", "a", "VPC", "peering", "connection", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L2975-L3033
train
saltstack/salt
salt/modules/boto_vpc.py
is_peering_connection_pending
def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE
python
def is_peering_connection_pending(conn_id=None, conn_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3 ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) if conn_id: vpcs = conn.describe_vpc_peering_connections(VpcPeeringConnectionIds=[conn_id]).get('VpcPeeringConnections', []) else: filters = [{'Name': 'tag:Name', 'Values': [conn_name]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return status == PENDING_ACCEPTANCE
[ "def", "is_peering_connection_pending", "(", "conn_id", "=", "None", ",", "conn_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "not", "_exactly_one", "(", ...
Check if a VPC peering connection is in the pending state. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc # Specify a region salt myminion boto_vpc.is_peering_connection_pending conn_name=salt-vpc region=us-west-2 # specify an id salt myminion boto_vpc.is_peering_connection_pending conn_id=pcx-8a8939e3
[ "Check", "if", "a", "VPC", "peering", "connection", "is", "in", "the", "pending", "state", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L3036-L3094
train
saltstack/salt
salt/modules/boto_vpc.py
peering_connection_pending_from_vpc
def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
python
def peering_connection_pending_from_vpc(conn_id=None, conn_name=None, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc ''' if not _exactly_one((conn_id, conn_name)): raise SaltInvocationError('Exactly one of conn_id or conn_name must be provided.') if not _exactly_one((vpc_id, vpc_name)): raise SaltInvocationError('Exactly one of vpc_id or vpc_name must be provided.') if vpc_name: vpc_id = check_vpc(vpc_name=vpc_name, region=region, key=key, keyid=keyid, profile=profile) if not vpc_id: log.warning('Could not resolve VPC name %s to an ID', vpc_name) return False conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) filters = [{'Name': 'requester-vpc-info.vpc-id', 'Values': [vpc_id]}, {'Name': 'status-code', 'Values': [ACTIVE, PENDING_ACCEPTANCE, PROVISIONING]}] if conn_id: filters += [{'Name': 'vpc-peering-connection-id', 'Values': [conn_id]}] else: filters += [{'Name': 'tag:Name', 'Values': [conn_name]}] vpcs = conn.describe_vpc_peering_connections(Filters=filters).get('VpcPeeringConnections', []) if not vpcs: return False elif len(vpcs) > 1: raise SaltInvocationError('Found more than one ID for the VPC peering ' 'connection ({0}). Please call this function ' 'with an ID instead.'.format(conn_id or conn_name)) else: status = vpcs[0]['Status']['Code'] return bool(status == PENDING_ACCEPTANCE)
[ "def", "peering_connection_pending_from_vpc", "(", "conn_id", "=", "None", ",", "conn_name", "=", "None", ",", "vpc_id", "=", "None", ",", "vpc_name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "prof...
Check if a VPC peering connection is in the pending state, and requested from the given VPC. .. versionadded:: 2016.11.0 conn_id The connection ID to check. Exclusive with conn_name. conn_name The connection name to check. Exclusive with conn_id. vpc_id Is this the ID of the requesting VPC for this peering connection. Exclusive with vpc_name. vpc_name Is this the Name of the requesting VPC for this peering connection. Exclusive with vpc_id. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. CLI Example: .. code-block:: bash salt myminion boto_vpc.is_peering_connection_pending name=salt-vpc
[ "Check", "if", "a", "VPC", "peering", "connection", "is", "in", "the", "pending", "state", "and", "requested", "from", "the", "given", "VPC", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_vpc.py#L3097-L3168
train
saltstack/salt
salt/utils/botomod.py
cache_id
def cache_id(service, name, sub_resource=None, resource_id=None, invalidate=False, region=None, key=None, keyid=None, profile=None): ''' Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile') ''' cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: cxkey = '{0}:{1}:{2}:id'.format(cxkey, sub_resource, name) else: cxkey = '{0}:{1}:id'.format(cxkey, name) if invalidate: if cxkey in __context__: del __context__[cxkey] return True elif resource_id in __context__.values(): ctx = dict((k, v) for k, v in __context__.items() if v != resource_id) __context__.clear() __context__.update(ctx) return True else: return False if resource_id: __context__[cxkey] = resource_id return True return __context__.get(cxkey)
python
def cache_id(service, name, sub_resource=None, resource_id=None, invalidate=False, region=None, key=None, keyid=None, profile=None): ''' Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile') ''' cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: cxkey = '{0}:{1}:{2}:id'.format(cxkey, sub_resource, name) else: cxkey = '{0}:{1}:id'.format(cxkey, name) if invalidate: if cxkey in __context__: del __context__[cxkey] return True elif resource_id in __context__.values(): ctx = dict((k, v) for k, v in __context__.items() if v != resource_id) __context__.clear() __context__.update(ctx) return True else: return False if resource_id: __context__[cxkey] = resource_id return True return __context__.get(cxkey)
[ "def", "cache_id", "(", "service", ",", "name", ",", "sub_resource", "=", "None", ",", "resource_id", "=", "None", ",", "invalidate", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "...
Cache, invalidate, or retrieve an AWS resource id keyed by name. .. code-block:: python __utils__['boto.cache_id']('ec2', 'myinstance', 'i-a1b2c3', profile='custom_profile')
[ "Cache", "invalidate", "or", "retrieve", "an", "AWS", "resource", "id", "keyed", "by", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L115-L150
train
saltstack/salt
salt/utils/botomod.py
get_connection
def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' # future lint: disable=blacklisted-function module = str(module or service) module, submodule = (str('boto.') + module).rsplit(str('.'), 1) # future lint: enable=blacklisted-function svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule) cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn' if cxkey in __context__: return __context__[cxkey] try: conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn
python
def get_connection(service, module=None, region=None, key=None, keyid=None, profile=None): ''' Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile') ''' # future lint: disable=blacklisted-function module = str(module or service) module, submodule = (str('boto.') + module).rsplit(str('.'), 1) # future lint: enable=blacklisted-function svc_mod = getattr(__import__(module, fromlist=[submodule]), submodule) cxkey, region, key, keyid = _get_profile(service, region, key, keyid, profile) cxkey = cxkey + ':conn' if cxkey in __context__: return __context__[cxkey] try: conn = svc_mod.connect_to_region(region, aws_access_key_id=keyid, aws_secret_access_key=key) if conn is None: raise SaltInvocationError('Region "{0}" is not ' 'valid.'.format(region)) except boto.exception.NoAuthHandlerFound: raise SaltInvocationError('No authentication credentials found when ' 'attempting to make boto {0} connection to ' 'region "{1}".'.format(service, region)) __context__[cxkey] = conn return conn
[ "def", "get_connection", "(", "service", ",", "module", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "# future lint: disable=blacklisted-function", "module", "=", "str", ...
Return a boto connection for the service. .. code-block:: python conn = __utils__['boto.get_connection']('ec2', profile='custom_profile')
[ "Return", "a", "boto", "connection", "for", "the", "service", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L166-L201
train
saltstack/salt
salt/utils/botomod.py
exactly_n
def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i)
python
def exactly_n(l, n=1): ''' Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0). ''' i = iter(l) return all(any(i) for j in range(n)) and not any(i)
[ "def", "exactly_n", "(", "l", ",", "n", "=", "1", ")", ":", "i", "=", "iter", "(", "l", ")", "return", "all", "(", "any", "(", "i", ")", "for", "j", "in", "range", "(", "n", ")", ")", "and", "not", "any", "(", "i", ")" ]
Tests that exactly N items in an iterable are "truthy" (neither None, False, nor 0).
[ "Tests", "that", "exactly", "N", "items", "in", "an", "iterable", "are", "truthy", "(", "neither", "None", "False", "nor", "0", ")", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L243-L249
train
saltstack/salt
salt/utils/botomod.py
assign_funcs
def assign_funcs(modname, service, module=None, pack=None): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2') ''' if pack: global __salt__ # pylint: disable=W0601 __salt__ = pack mod = sys.modules[modname] setattr(mod, '_get_conn', get_connection_func(service, module=module)) setattr(mod, '_cache_id', cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported setattr(mod, '_exactly_one', exactly_one)
python
def assign_funcs(modname, service, module=None, pack=None): ''' Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2') ''' if pack: global __salt__ # pylint: disable=W0601 __salt__ = pack mod = sys.modules[modname] setattr(mod, '_get_conn', get_connection_func(service, module=module)) setattr(mod, '_cache_id', cache_id_func(service)) # TODO: Remove this and import salt.utils.data.exactly_one into boto_* modules instead # Leaving this way for now so boto modules can be back ported setattr(mod, '_exactly_one', exactly_one)
[ "def", "assign_funcs", "(", "modname", ",", "service", ",", "module", "=", "None", ",", "pack", "=", "None", ")", ":", "if", "pack", ":", "global", "__salt__", "# pylint: disable=W0601", "__salt__", "=", "pack", "mod", "=", "sys", ".", "modules", "[", "m...
Assign _get_conn and _cache_id functions to the named module. .. code-block:: python __utils__['boto.assign_partials'](__name__, 'ec2')
[ "Assign", "_get_conn", "and", "_cache_id", "functions", "to", "the", "named", "module", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/botomod.py#L256-L273
train
saltstack/salt
salt/matchers/ipcidr_match.py
match
def match(tgt, opts=None): ''' Matches based on IP address or CIDR notation ''' if not opts: opts = __opts__ try: # Target is an address? tgt = ipaddress.ip_address(tgt) except: # pylint: disable=bare-except try: # Target is a network? tgt = ipaddress.ip_network(tgt) except: # pylint: disable=bare-except log.error('Invalid IP/CIDR target: %s', tgt) return [] proto = 'ipv{0}'.format(tgt.version) grains = opts['grains'] if proto not in grains: match = False elif isinstance(tgt, (ipaddress.IPv4Address, ipaddress.IPv6Address)): match = six.text_type(tgt) in grains[proto] else: match = salt.utils.network.in_subnet(tgt, grains[proto]) return match
python
def match(tgt, opts=None): ''' Matches based on IP address or CIDR notation ''' if not opts: opts = __opts__ try: # Target is an address? tgt = ipaddress.ip_address(tgt) except: # pylint: disable=bare-except try: # Target is a network? tgt = ipaddress.ip_network(tgt) except: # pylint: disable=bare-except log.error('Invalid IP/CIDR target: %s', tgt) return [] proto = 'ipv{0}'.format(tgt.version) grains = opts['grains'] if proto not in grains: match = False elif isinstance(tgt, (ipaddress.IPv4Address, ipaddress.IPv6Address)): match = six.text_type(tgt) in grains[proto] else: match = salt.utils.network.in_subnet(tgt, grains[proto]) return match
[ "def", "match", "(", "tgt", ",", "opts", "=", "None", ")", ":", "if", "not", "opts", ":", "opts", "=", "__opts__", "try", ":", "# Target is an address?", "tgt", "=", "ipaddress", ".", "ip_address", "(", "tgt", ")", "except", ":", "# pylint: disable=bare-ex...
Matches based on IP address or CIDR notation
[ "Matches", "based", "on", "IP", "address", "or", "CIDR", "notation" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/ipcidr_match.py#L20-L48
train
saltstack/salt
salt/utils/dictupdate.py
update
def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest
python
def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list. ''' if (not isinstance(dest, Mapping)) \ or (not isinstance(upd, Mapping)): raise TypeError('Cannot update using non-dict types in dictupdate.update()') updkeys = list(upd.keys()) if not set(list(dest.keys())) & set(updkeys): recursive_update = False if recursive_update: for key in updkeys: val = upd[key] try: dest_subkey = dest.get(key, None) except AttributeError: dest_subkey = None if isinstance(dest_subkey, Mapping) \ and isinstance(val, Mapping): ret = update(dest_subkey, val, merge_lists=merge_lists) dest[key] = ret elif isinstance(dest_subkey, list) and isinstance(val, list): if merge_lists: merged = copy.deepcopy(dest_subkey) merged.extend([x for x in val if x not in merged]) dest[key] = merged else: dest[key] = upd[key] else: dest[key] = upd[key] return dest try: for k in upd: dest[k] = upd[k] except AttributeError: # this mapping is not a dict for k in upd: dest[k] = upd[k] return dest
[ "def", "update", "(", "dest", ",", "upd", ",", "recursive_update", "=", "True", ",", "merge_lists", "=", "False", ")", ":", "if", "(", "not", "isinstance", "(", "dest", ",", "Mapping", ")", ")", "or", "(", "not", "isinstance", "(", "upd", ",", "Mappi...
Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If merge_lists=True, will aggregate list object types instead of replace. The list in ``upd`` is added to the list in ``dest``, so the resulting list is ``dest[key] + upd[key]``. This behavior is only activated when recursive_update=True. By default merge_lists=False. .. versionchanged: 2016.11.6 When merging lists, duplicate values are removed. Values already present in the ``dest`` list are not added from the ``upd`` list.
[ "Recursive", "version", "of", "the", "default", "dict", ".", "update" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L30-L82
train
saltstack/salt
salt/utils/dictupdate.py
ensure_dict_key
def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict
python
def ensure_dict_key( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. ''' if delimiter in keys: a_keys = keys.split(delimiter) else: a_keys = [keys] dict_pointer = in_dict while a_keys: current_key = a_keys.pop(0) if current_key not in dict_pointer or not isinstance(dict_pointer[current_key], dict): dict_pointer[current_key] = OrderedDict() if ordered_dict else {} dict_pointer = dict_pointer[current_key] return in_dict
[ "def", "ensure_dict_key", "(", "in_dict", ",", "keys", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "if", "delimiter", "in", "keys", ":", "a_keys", "=", "keys", ".", "split", "(", "delimiter", ")", "else", ":"...
Ensures that in_dict contains the series of recursive keys defined in keys. :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts.
[ "Ensures", "that", "in_dict", "contains", "the", "series", "of", "recursive", "keys", "defined", "in", "keys", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L142-L166
train
saltstack/salt
salt/utils/dictupdate.py
_dict_rpartition
def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key
python
def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str) ''' if delimiter in keys: all_but_last_keys, _, last_key = keys.rpartition(delimiter) ensure_dict_key(in_dict, all_but_last_keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer = salt.utils.data.traverse_dict(in_dict, all_but_last_keys, default=None, delimiter=delimiter) else: dict_pointer = in_dict last_key = keys return dict_pointer, last_key
[ "def", "_dict_rpartition", "(", "in_dict", ",", "keys", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "if", "delimiter", "in", "keys", ":", "all_but_last_keys", ",", "_", ",", "last_key", "=", "keys", ".", "rpart...
Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: The dict to work with. :param str keys: The delimited string with one or more keys. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return tuple(dict, str)
[ "Helper", "function", "to", ":", "-", "Ensure", "all", "but", "the", "last", "key", "in", "keys", "exist", "recursively", "in", "in_dict", ".", "-", "Return", "the", "dict", "at", "the", "one", "-", "to", "-", "last", "key", "and", "the", "last", "ke...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L169-L200
train
saltstack/salt
salt/utils/dictupdate.py
set_dict_key_value
def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict
python
def set_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) dict_pointer[last_key] = value return in_dict
[ "def", "set_dict_key_value", "(", "in_dict", ",", "keys", ",", "value", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "dict_pointer", ",", "last_key", "=", "_dict_rpartition", "(", "in_dict", ",", "keys", ",", "del...
Ensures that in_dict contains the series of recursive keys defined in keys. Also sets whatever is at the end of `in_dict` traversed with `keys` to `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to assign to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
[ "Ensures", "that", "in_dict", "contains", "the", "series", "of", "recursive", "keys", "defined", "in", "keys", ".", "Also", "sets", "whatever", "is", "at", "the", "end", "of", "in_dict", "traversed", "with", "keys", "to", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L204-L228
train
saltstack/salt
salt/utils/dictupdate.py
update_dict_key_value
def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
python
def update_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = OrderedDict() if ordered_dict else {} try: dict_pointer[last_key].update(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot update.' ''.format(type(dict_pointer[last_key]))) except (ValueError, TypeError): raise SaltInvocationError('Cannot update {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
[ "def", "update_dict_key_value", "(", "in_dict", ",", "keys", ",", "value", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "dict_pointer", ",", "last_key", "=", "_dict_rpartition", "(", "in_dict", ",", "keys", ",", "...
Ensures that in_dict contains the series of recursive keys defined in keys. Also updates the dict, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to update the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
[ "Ensures", "that", "in_dict", "contains", "the", "series", "of", "recursive", "keys", "defined", "in", "keys", ".", "Also", "updates", "the", "dict", "that", "is", "at", "the", "end", "of", "in_dict", "traversed", "with", "keys", "with", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L232-L266
train
saltstack/salt
salt/utils/dictupdate.py
append_dict_key_value
def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict
python
def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition(in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].append(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot append.' ''.format(type(dict_pointer[last_key]))) return in_dict
[ "def", "append_dict_key_value", "(", "in_dict", ",", "keys", ",", "value", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "dict_pointer", ",", "last_key", "=", "_dict_rpartition", "(", "in_dict", ",", "keys", ",", "...
Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to append to the nested dict-key. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
[ "Ensures", "that", "in_dict", "contains", "the", "series", "of", "recursive", "keys", "defined", "in", "keys", ".", "Also", "appends", "value", "to", "the", "list", "that", "is", "at", "the", "end", "of", "in_dict", "traversed", "with", "keys", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L270-L301
train
saltstack/salt
salt/utils/dictupdate.py
extend_dict_key_value
def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
python
def extend_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place. ''' dict_pointer, last_key = _dict_rpartition( in_dict, keys, delimiter=delimiter, ordered_dict=ordered_dict) if last_key not in dict_pointer or dict_pointer[last_key] is None: dict_pointer[last_key] = [] try: dict_pointer[last_key].extend(value) except AttributeError: raise SaltInvocationError('The last key contains a {}, which cannot extend.' ''.format(type(dict_pointer[last_key]))) except TypeError: raise SaltInvocationError('Cannot extend {} with a {}.' ''.format(type(dict_pointer[last_key]), type(value))) return in_dict
[ "def", "extend_dict_key_value", "(", "in_dict", ",", "keys", ",", "value", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "dict_pointer", ",", "last_key", "=", "_dict_rpartition", "(", "in_dict", ",", "keys", ",", "...
Ensures that in_dict contains the series of recursive keys defined in keys. Also extends the list, that is at the end of `in_dict` traversed with `keys`, with `value`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The value to extend the nested dict-key with. :param str delimiter: The delimiter to use in `keys`. Defaults to ':'. :param bool ordered_dict: Create OrderedDicts if keys are missing. Default: create regular dicts. :return dict: Though it updates in_dict in-place.
[ "Ensures", "that", "in_dict", "contains", "the", "series", "of", "recursive", "keys", "defined", "in", "keys", ".", "Also", "extends", "the", "list", "that", "is", "at", "the", "end", "of", "in_dict", "traversed", "with", "keys", "with", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/dictupdate.py#L305-L340
train
saltstack/salt
salt/cli/batch.py
get_bnum
def get_bnum(opts, minions, quiet): ''' Return the active number of minions to maintain ''' partition = lambda x: float(x) / 100.0 * len(minions) try: if '%' in opts['batch']: res = partition(float(opts['batch'].strip('%'))) if res < 1: return int(math.ceil(res)) else: return int(res) else: return int(opts['batch']) except ValueError: if not quiet: salt.utils.stringutils.print_cli('Invalid batch data sent: {0}\nData must be in the ' 'form of %10, 10% or 3'.format(opts['batch']))
python
def get_bnum(opts, minions, quiet): ''' Return the active number of minions to maintain ''' partition = lambda x: float(x) / 100.0 * len(minions) try: if '%' in opts['batch']: res = partition(float(opts['batch'].strip('%'))) if res < 1: return int(math.ceil(res)) else: return int(res) else: return int(opts['batch']) except ValueError: if not quiet: salt.utils.stringutils.print_cli('Invalid batch data sent: {0}\nData must be in the ' 'form of %10, 10% or 3'.format(opts['batch']))
[ "def", "get_bnum", "(", "opts", ",", "minions", ",", "quiet", ")", ":", "partition", "=", "lambda", "x", ":", "float", "(", "x", ")", "/", "100.0", "*", "len", "(", "minions", ")", "try", ":", "if", "'%'", "in", "opts", "[", "'batch'", "]", ":", ...
Return the active number of minions to maintain
[ "Return", "the", "active", "number", "of", "minions", "to", "maintain" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/batch.py#L29-L46
train
saltstack/salt
salt/cli/batch.py
Batch.__gather_minions
def __gather_minions(self): ''' Return a list of minions to use for the batch run ''' args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('tgt_type', 'glob')) self.pub_kwargs['yield_pub_data'] = True ping_gen = self.local.cmd_iter(*args, gather_job_timeout=self.opts['gather_job_timeout'], **self.pub_kwargs) # Broadcast to targets fret = set() nret = set() for ret in ping_gen: if ('minions' and 'jid') in ret: for minion in ret['minions']: nret.add(minion) continue else: try: m = next(six.iterkeys(ret)) except StopIteration: if not self.quiet: salt.utils.stringutils.print_cli('No minions matched the target.') break if m is not None: fret.add(m) return (list(fret), ping_gen, nret.difference(fret))
python
def __gather_minions(self): ''' Return a list of minions to use for the batch run ''' args = [self.opts['tgt'], 'test.ping', [], self.opts['timeout'], ] selected_target_option = self.opts.get('selected_target_option', None) if selected_target_option is not None: args.append(selected_target_option) else: args.append(self.opts.get('tgt_type', 'glob')) self.pub_kwargs['yield_pub_data'] = True ping_gen = self.local.cmd_iter(*args, gather_job_timeout=self.opts['gather_job_timeout'], **self.pub_kwargs) # Broadcast to targets fret = set() nret = set() for ret in ping_gen: if ('minions' and 'jid') in ret: for minion in ret['minions']: nret.add(minion) continue else: try: m = next(six.iterkeys(ret)) except StopIteration: if not self.quiet: salt.utils.stringutils.print_cli('No minions matched the target.') break if m is not None: fret.add(m) return (list(fret), ping_gen, nret.difference(fret))
[ "def", "__gather_minions", "(", "self", ")", ":", "args", "=", "[", "self", ".", "opts", "[", "'tgt'", "]", ",", "'test.ping'", ",", "[", "]", ",", "self", ".", "opts", "[", "'timeout'", "]", ",", "]", "selected_target_option", "=", "self", ".", "opt...
Return a list of minions to use for the batch run
[ "Return", "a", "list", "of", "minions", "to", "use", "for", "the", "batch", "run" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/batch.py#L115-L153
train
saltstack/salt
salt/cli/batch.py
Batch.run
def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() # No targets to run if not self.minions: return to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] # wait the specified time before decide a job is actually done bwait = self.opts.get('batch_wait', 0) wait = [] if self.options: show_jid = self.options.show_jid show_verbose = self.options.verbose else: show_jid = False show_verbose = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} if not self.quiet: # We already know some minions didn't respond to the ping, so inform # the user we won't be attempting to run a job on them for down_minion in self.down_minions: salt.utils.stringutils.print_cli('Minion {0} did not respond. No job will be sent.'.format(down_minion)) # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if bwait and wait: self.__update_wait(wait) if len(to_run) <= bnum - len(wait) and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active) - len(wait)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: salt.utils.stringutils.print_cli('\nExecuting run on {0}\n'.format(sorted(next_))) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, verbose=show_verbose, gather_job_timeout=self.opts['gather_job_timeout'], **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(six.iterkeys(ping_ret)) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['data']['id']: part}) if part['data']['id'] in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(part['data']['id']) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(part['id'])) else: parts.update(part) for id in part: if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(id)) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait)) # Munge retcode into return data failhard = False if 'retcode' in data and isinstance(data['ret'], dict) and 'retcode' not in data['ret']: data['ret']['retcode'] = data['retcode'] if self.opts.get('failhard') and data['ret']['retcode'] > 0: failhard = True if self.opts.get('raw'): ret[minion] = data yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) if failhard: log.error( 'Minion %s returned with non-zero exit code. ' 'Batch run stopped due to failhard', minion ) raise StopIteration # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait))
python
def run(self): ''' Execute the batch run ''' args = [[], self.opts['fun'], self.opts['arg'], self.opts['timeout'], 'list', ] bnum = self.get_bnum() # No targets to run if not self.minions: return to_run = copy.deepcopy(self.minions) active = [] ret = {} iters = [] # wait the specified time before decide a job is actually done bwait = self.opts.get('batch_wait', 0) wait = [] if self.options: show_jid = self.options.show_jid show_verbose = self.options.verbose else: show_jid = False show_verbose = False # the minion tracker keeps track of responses and iterators # - it removes finished iterators from iters[] # - if a previously detected minion does not respond, its # added with an empty answer to ret{} once the timeout is reached # - unresponsive minions are removed from active[] to make # sure that the main while loop finishes even with unresp minions minion_tracker = {} if not self.quiet: # We already know some minions didn't respond to the ping, so inform # the user we won't be attempting to run a job on them for down_minion in self.down_minions: salt.utils.stringutils.print_cli('Minion {0} did not respond. No job will be sent.'.format(down_minion)) # Iterate while we still have things to execute while len(ret) < len(self.minions): next_ = [] if bwait and wait: self.__update_wait(wait) if len(to_run) <= bnum - len(wait) and not active: # last bit of them, add them all to next iterator while to_run: next_.append(to_run.pop()) else: for i in range(bnum - len(active) - len(wait)): if to_run: minion_id = to_run.pop() if isinstance(minion_id, dict): next_.append(minion_id.keys()[0]) else: next_.append(minion_id) active += next_ args[0] = next_ if next_: if not self.quiet: salt.utils.stringutils.print_cli('\nExecuting run on {0}\n'.format(sorted(next_))) # create a new iterator for this batch of minions new_iter = self.local.cmd_iter_no_block( *args, raw=self.opts.get('raw', False), ret=self.opts.get('return', ''), show_jid=show_jid, verbose=show_verbose, gather_job_timeout=self.opts['gather_job_timeout'], **self.eauth) # add it to our iterators and to the minion_tracker iters.append(new_iter) minion_tracker[new_iter] = {} # every iterator added is 'active' and has its set of minions minion_tracker[new_iter]['minions'] = next_ minion_tracker[new_iter]['active'] = True else: time.sleep(0.02) parts = {} # see if we found more minions for ping_ret in self.ping_gen: if ping_ret is None: break m = next(six.iterkeys(ping_ret)) if m not in self.minions: self.minions.append(m) to_run.append(m) for queue in iters: try: # Gather returns until we get to the bottom ncnt = 0 while True: part = next(queue) if part is None: time.sleep(0.01) ncnt += 1 if ncnt > 5: break continue if self.opts.get('raw'): parts.update({part['data']['id']: part}) if part['data']['id'] in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(part['data']['id']) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(part['id'])) else: parts.update(part) for id in part: if id in minion_tracker[queue]['minions']: minion_tracker[queue]['minions'].remove(id) else: salt.utils.stringutils.print_cli('minion {0} was already deleted from tracker, probably a duplicate key'.format(id)) except StopIteration: # if a iterator is done: # - set it to inactive # - add minions that have not responded to parts{} # check if the tracker contains the iterator if queue in minion_tracker: minion_tracker[queue]['active'] = False # add all minions that belong to this iterator and # that have not responded to parts{} with an empty response for minion in minion_tracker[queue]['minions']: if minion not in parts: parts[minion] = {} parts[minion]['ret'] = {} for minion, data in six.iteritems(parts): if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait)) # Munge retcode into return data failhard = False if 'retcode' in data and isinstance(data['ret'], dict) and 'retcode' not in data['ret']: data['ret']['retcode'] = data['retcode'] if self.opts.get('failhard') and data['ret']['retcode'] > 0: failhard = True if self.opts.get('raw'): ret[minion] = data yield data else: ret[minion] = data['ret'] yield {minion: data['ret']} if not self.quiet: ret[minion] = data['ret'] data[minion] = data.pop('ret') if 'out' in data: out = data.pop('out') else: out = None salt.output.display_output( data, out, self.opts) if failhard: log.error( 'Minion %s returned with non-zero exit code. ' 'Batch run stopped due to failhard', minion ) raise StopIteration # remove inactive iterators from the iters list for queue in minion_tracker: # only remove inactive queues if not minion_tracker[queue]['active'] and queue in iters: iters.remove(queue) # also remove the iterator's minions from the active list for minion in minion_tracker[queue]['minions']: if minion in active: active.remove(minion) if bwait: wait.append(datetime.now() + timedelta(seconds=bwait))
[ "def", "run", "(", "self", ")", ":", "args", "=", "[", "[", "]", ",", "self", ".", "opts", "[", "'fun'", "]", ",", "self", ".", "opts", "[", "'arg'", "]", ",", "self", ".", "opts", "[", "'timeout'", "]", ",", "'list'", ",", "]", "bnum", "=", ...
Execute the batch run
[ "Execute", "the", "batch", "run" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/batch.py#L166-L349
train
saltstack/salt
salt/modules/dummyproxy_service.py
status
def status(name, sig=None): ''' Return the status for a service via dummy, returns a bool whether the service is running. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' proxy_fn = 'dummy.service_status' resp = __proxy__[proxy_fn](name) if resp['comment'] == 'stopped': return False if resp['comment'] == 'running': return True
python
def status(name, sig=None): ''' Return the status for a service via dummy, returns a bool whether the service is running. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.status <service name> ''' proxy_fn = 'dummy.service_status' resp = __proxy__[proxy_fn](name) if resp['comment'] == 'stopped': return False if resp['comment'] == 'running': return True
[ "def", "status", "(", "name", ",", "sig", "=", "None", ")", ":", "proxy_fn", "=", "'dummy.service_status'", "resp", "=", "__proxy__", "[", "proxy_fn", "]", "(", "name", ")", "if", "resp", "[", "'comment'", "]", "==", "'stopped'", ":", "return", "False", ...
Return the status for a service via dummy, returns a bool whether the service is running. .. versionadded:: 2016.11.3 CLI Example: .. code-block:: bash salt '*' service.status <service name>
[ "Return", "the", "status", "for", "a", "service", "via", "dummy", "returns", "a", "bool", "whether", "the", "service", "is", "running", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dummyproxy_service.py#L127-L146
train
saltstack/salt
salt/states/xmpp.py
send_msg
def send_msg(name, recipient, profile): ''' Send a message to an XMPP user .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __opts__['test']: ret['comment'] = 'Need to send message to {0}: {1}'.format( recipient, name, ) return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=[recipient], profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to {0}: {1}'.format(recipient, name) return ret
python
def send_msg(name, recipient, profile): ''' Send a message to an XMPP user .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if __opts__['test']: ret['comment'] = 'Need to send message to {0}: {1}'.format( recipient, name, ) return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=[recipient], profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to {0}: {1}'.format(recipient, name) return ret
[ "def", "send_msg", "(", "name", ",", "recipient", ",", "profile", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", "''", "}", "if", "__opts__", "[", "'test'", "]...
Send a message to an XMPP user .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipient: admins@xmpp.example.com/salt name The message to send to the XMPP user
[ "Send", "a", "message", "to", "an", "XMPP", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/xmpp.py#L31-L63
train
saltstack/salt
salt/states/xmpp.py
send_msg_multi
def send_msg_multi(name, profile, recipients=None, rooms=None): ''' Send a message to an list of recipients or rooms .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipients: - admins@xmpp.example.com/salt - rooms: - qa@conference.xmpp.example.com name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if recipients is None and rooms is None: ret['comment'] = "Recipients and rooms are empty, no need to send" return ret comment = '' if recipients: comment += ' users {0}'.format(recipients) if rooms: comment += ' rooms {0}'.format(rooms) comment += ', message: {0}'.format(name) if __opts__['test']: ret['comment'] = 'Need to send' + comment return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=recipients, rooms=rooms, profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to' + comment return ret
python
def send_msg_multi(name, profile, recipients=None, rooms=None): ''' Send a message to an list of recipients or rooms .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipients: - admins@xmpp.example.com/salt - rooms: - qa@conference.xmpp.example.com name The message to send to the XMPP user ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} if recipients is None and rooms is None: ret['comment'] = "Recipients and rooms are empty, no need to send" return ret comment = '' if recipients: comment += ' users {0}'.format(recipients) if rooms: comment += ' rooms {0}'.format(rooms) comment += ', message: {0}'.format(name) if __opts__['test']: ret['comment'] = 'Need to send' + comment return ret __salt__['xmpp.send_msg_multi']( message=name, recipients=recipients, rooms=rooms, profile=profile, ) ret['result'] = True ret['comment'] = 'Sent message to' + comment return ret
[ "def", "send_msg_multi", "(", "name", ",", "profile", ",", "recipients", "=", "None", ",", "rooms", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "None", ",", "'comment'", ":", ...
Send a message to an list of recipients or rooms .. code-block:: yaml server-warning-message: xmpp.send_msg: - name: 'This is a server warning message' - profile: my-xmpp-account - recipients: - admins@xmpp.example.com/salt - rooms: - qa@conference.xmpp.example.com name The message to send to the XMPP user
[ "Send", "a", "message", "to", "an", "list", "of", "recipients", "or", "rooms" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/xmpp.py#L66-L116
train
saltstack/salt
salt/states/libcloud_dns.py
zone_present
def zone_present(domain, type, profile): ''' Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) if not type: type = 'master' matching_zone = [z for z in zones if z['domain'] == domain] if matching_zone: return state_result(True, 'Zone already exists', domain) else: result = __salt__['libcloud_dns.create_zone'](domain, profile, type) return state_result(True, 'Created new zone', domain, result)
python
def zone_present(domain, type, profile): ''' Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) if not type: type = 'master' matching_zone = [z for z in zones if z['domain'] == domain] if matching_zone: return state_result(True, 'Zone already exists', domain) else: result = __salt__['libcloud_dns.create_zone'](domain, profile, type) return state_result(True, 'Created new zone', domain, result)
[ "def", "zone_present", "(", "domain", ",", "type", ",", "profile", ")", ":", "zones", "=", "__salt__", "[", "'libcloud_dns.list_zones'", "]", "(", "profile", ")", "if", "not", "type", ":", "type", "=", "'master'", "matching_zone", "=", "[", "z", "for", "...
Ensures a record is present. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param type: Zone type (master / slave), defaults to master :type type: ``str`` :param profile: The profile key :type profile: ``str``
[ "Ensures", "a", "record", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L74-L95
train
saltstack/salt
salt/states/libcloud_dns.py
zone_absent
def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones if z['domain'] == domain] if not matching_zone: return state_result(True, 'Zone already absent', domain) else: result = __salt__['libcloud_dns.delete_zone'](matching_zone[0]['id'], profile) return state_result(result, 'Deleted zone', domain)
python
def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones if z['domain'] == domain] if not matching_zone: return state_result(True, 'Zone already absent', domain) else: result = __salt__['libcloud_dns.delete_zone'](matching_zone[0]['id'], profile) return state_result(result, 'Deleted zone', domain)
[ "def", "zone_absent", "(", "domain", ",", "profile", ")", ":", "zones", "=", "__salt__", "[", "'libcloud_dns.list_zones'", "]", "(", "profile", ")", "matching_zone", "=", "[", "z", "for", "z", "in", "zones", "if", "z", "[", "'domain'", "]", "==", "domain...
Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str``
[ "Ensures", "a", "record", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L98-L114
train
saltstack/salt
salt/states/libcloud_dns.py
record_present
def record_present(name, zone, type, data, profile): ''' Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Could not locate zone', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if not matching_records: result = __salt__['libcloud_dns.create_record']( name, matching_zone['id'], type, data, profile) return state_result(True, 'Created new record', name, result) else: return state_result(True, 'Record already exists', name)
python
def record_present(name, zone, type, data, profile): ''' Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Could not locate zone', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if not matching_records: result = __salt__['libcloud_dns.create_record']( name, matching_zone['id'], type, data, profile) return state_result(True, 'Created new record', name, result) else: return state_result(True, 'Record already exists', name)
[ "def", "record_present", "(", "name", ",", "zone", ",", "type", ",", "data", ",", "profile", ")", ":", "zones", "=", "__salt__", "[", "'libcloud_dns.list_zones'", "]", "(", "profile", ")", "try", ":", "matching_zone", "=", "[", "z", "for", "z", "in", "...
Ensures a record is present. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str``
[ "Ensures", "a", "record", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L117-L155
train
saltstack/salt
salt/states/libcloud_dns.py
record_absent
def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Zone could not be found', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if matching_records: result = [] for record in matching_records: result.append(__salt__['libcloud_dns.delete_record']( matching_zone['id'], record['id'], profile)) return state_result(all(result), 'Removed {0} records'.format(len(result)), name) else: return state_result(True, 'Records already absent', name)
python
def record_absent(name, zone, type, data, profile): ''' Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) try: matching_zone = [z for z in zones if z['domain'] == zone][0] except IndexError: return state_result(False, 'Zone could not be found', name) records = __salt__['libcloud_dns.list_records'](matching_zone['id'], profile) matching_records = [record for record in records if record['name'] == name and record['type'] == type and record['data'] == data] if matching_records: result = [] for record in matching_records: result.append(__salt__['libcloud_dns.delete_record']( matching_zone['id'], record['id'], profile)) return state_result(all(result), 'Removed {0} records'.format(len(result)), name) else: return state_result(True, 'Records already absent', name)
[ "def", "record_absent", "(", "name", ",", "zone", ",", "type", ",", "data", ",", "profile", ")", ":", "zones", "=", "__salt__", "[", "'libcloud_dns.list_zones'", "]", "(", "profile", ")", "try", ":", "matching_zone", "=", "[", "z", "for", "z", "in", "z...
Ensures a record is absent. :param name: Record name without the domain name (e.g. www). Note: If you want to create a record for a base domain name, you should specify empty string ('') for this argument. :type name: ``str`` :param zone: Zone where the requested record is created, the domain name :type zone: ``str`` :param type: DNS record type (A, AAAA, ...). :type type: ``str`` :param data: Data for the record (depends on the record type). :type data: ``str`` :param profile: The profile key :type profile: ``str``
[ "Ensures", "a", "record", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_dns.py#L158-L199
train
saltstack/salt
salt/modules/mod_random.py
hash
def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out
python
def hash(value, algorithm='sha512'): ''' .. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5 ''' if six.PY3 and isinstance(value, six.string_types): # Under Python 3 we must work with bytes value = value.encode(__salt_system_encoding__) if hasattr(hashlib, ALGORITHMS_ATTR_NAME) and algorithm in getattr(hashlib, ALGORITHMS_ATTR_NAME): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() elif hasattr(hashlib, algorithm): hasher = hashlib.new(algorithm) hasher.update(value) out = hasher.hexdigest() else: raise SaltInvocationError('You must specify a valid algorithm.') return out
[ "def", "hash", "(", "value", ",", "algorithm", "=", "'sha512'", ")", ":", "if", "six", ".", "PY3", "and", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "# Under Python 3 we must work with bytes", "value", "=", "value", ".", "encode",...
.. versionadded:: 2014.7.0 Encodes a value with the specified encoder. value The value to be hashed. algorithm : sha512 The algorithm to use. May be any valid algorithm supported by hashlib. CLI Example: .. code-block:: bash salt '*' random.hash 'I am a string' md5
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L46-L80
train
saltstack/salt
salt/modules/mod_random.py
str_encode
def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out
python
def str_encode(value, encoder='base64'): ''' .. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64 ''' if six.PY2: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') else: if isinstance(value, six.string_types): value = value.encode(__salt_system_encoding__) if encoder == 'base64': try: out = base64.b64encode(value) out = out.decode(__salt_system_encoding__) except TypeError: raise SaltInvocationError('Value must be an encode-able string') else: try: out = value.encode(encoder) except LookupError: raise SaltInvocationError('You must specify a valid encoder') except AttributeError: raise SaltInvocationError('Value must be an encode-able string') return out
[ "def", "str_encode", "(", "value", ",", "encoder", "=", "'base64'", ")", ":", "if", "six", ".", "PY2", ":", "try", ":", "out", "=", "value", ".", "encode", "(", "encoder", ")", "except", "LookupError", ":", "raise", "SaltInvocationError", "(", "'You must...
.. versionadded:: 2014.7.0 value The value to be encoded. encoder : base64 The encoder to use on the subsequent string. CLI Example: .. code-block:: bash salt '*' random.str_encode 'I am a new string' base64
[ "..", "versionadded", "::", "2014", ".", "7", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L83-L122
train
saltstack/salt
salt/modules/mod_random.py
shadow_hash
def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm)
python
def shadow_hash(crypt_salt=None, password=None, algorithm='sha512'): ''' Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5 ''' return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm)
[ "def", "shadow_hash", "(", "crypt_salt", "=", "None", ",", "password", "=", "None", ",", "algorithm", "=", "'sha512'", ")", ":", "return", "salt", ".", "utils", ".", "pycrypto", ".", "gen_hash", "(", "crypt_salt", ",", "password", ",", "algorithm", ")" ]
Generates a salted hash suitable for /etc/shadow. crypt_salt : None Salt to be used in the generation of the hash. If one is not provided, a random salt will be generated. password : None Value to be salted and hashed. If one is not provided, a random password will be generated. algorithm : sha512 Hash algorithm to use. CLI Example: .. code-block:: bash salt '*' random.shadow_hash 'My5alT' 'MyP@asswd' md5
[ "Generates", "a", "salted", "hash", "suitable", "for", "/", "etc", "/", "shadow", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L143-L164
train
saltstack/salt
salt/modules/mod_random.py
rand_int
def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end)
python
def rand_int(start=1, end=10, seed=None): ''' Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 ''' if seed is not None: random.seed(seed) return random.randint(start, end)
[ "def", "rand_int", "(", "start", "=", "1", ",", "end", "=", "10", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "not", "None", ":", "random", ".", "seed", "(", "seed", ")", "return", "random", ".", "randint", "(", "start", ",", "end", ...
Returns a random integer number between the start and end number. .. versionadded: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10
[ "Returns", "a", "random", "integer", "number", "between", "the", "start", "and", "end", "number", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L167-L194
train
saltstack/salt
salt/modules/mod_random.py
seed
def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
python
def seed(range=10, hash=None): ''' Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None ''' if hash is None: hash = __grains__['id'] random.seed(hash) return random.randrange(range)
[ "def", "seed", "(", "range", "=", "10", ",", "hash", "=", "None", ")", ":", "if", "hash", "is", "None", ":", "hash", "=", "__grains__", "[", "'id'", "]", "random", ".", "seed", "(", "hash", ")", "return", "random", ".", "randrange", "(", "range", ...
Returns a random number within a range. Optional hash argument can be any hashable object. If hash is omitted or None, the id of the minion is used. .. versionadded: 2015.8.0 hash: None Any hashable object. range: 10 Any valid integer number CLI Example: .. code-block:: bash salt '*' random.seed 10 hash=None
[ "Returns", "a", "random", "number", "within", "a", "range", ".", "Optional", "hash", "argument", "can", "be", "any", "hashable", "object", ".", "If", "hash", "is", "omitted", "or", "None", "the", "id", "of", "the", "minion", "is", "used", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mod_random.py#L197-L220
train
saltstack/salt
salt/auth/mysql.py
__get_connection_info
def __get_connection_info(): ''' Grab MySQL Connection Details ''' conn_info = {} try: conn_info['hostname'] = __opts__['mysql_auth']['hostname'] conn_info['username'] = __opts__['mysql_auth']['username'] conn_info['password'] = __opts__['mysql_auth']['password'] conn_info['database'] = __opts__['mysql_auth']['database'] conn_info['auth_sql'] = __opts__['mysql_auth']['auth_sql'] except KeyError as e: log.error('%s does not exist', e) return None return conn_info
python
def __get_connection_info(): ''' Grab MySQL Connection Details ''' conn_info = {} try: conn_info['hostname'] = __opts__['mysql_auth']['hostname'] conn_info['username'] = __opts__['mysql_auth']['username'] conn_info['password'] = __opts__['mysql_auth']['password'] conn_info['database'] = __opts__['mysql_auth']['database'] conn_info['auth_sql'] = __opts__['mysql_auth']['auth_sql'] except KeyError as e: log.error('%s does not exist', e) return None return conn_info
[ "def", "__get_connection_info", "(", ")", ":", "conn_info", "=", "{", "}", "try", ":", "conn_info", "[", "'hostname'", "]", "=", "__opts__", "[", "'mysql_auth'", "]", "[", "'hostname'", "]", "conn_info", "[", "'username'", "]", "=", "__opts__", "[", "'mysq...
Grab MySQL Connection Details
[ "Grab", "MySQL", "Connection", "Details" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/mysql.py#L83-L100
train
saltstack/salt
salt/auth/mysql.py
auth
def auth(username, password): ''' Authenticate using a MySQL user table ''' _info = __get_connection_info() if _info is None: return False try: conn = MySQLdb.connect(_info['hostname'], _info['username'], _info['password'], _info['database']) except OperationalError as e: log.error(e) return False cur = conn.cursor() cur.execute(_info['auth_sql'].format(username, password)) if cur.rowcount == 1: return True return False
python
def auth(username, password): ''' Authenticate using a MySQL user table ''' _info = __get_connection_info() if _info is None: return False try: conn = MySQLdb.connect(_info['hostname'], _info['username'], _info['password'], _info['database']) except OperationalError as e: log.error(e) return False cur = conn.cursor() cur.execute(_info['auth_sql'].format(username, password)) if cur.rowcount == 1: return True return False
[ "def", "auth", "(", "username", ",", "password", ")", ":", "_info", "=", "__get_connection_info", "(", ")", "if", "_info", "is", "None", ":", "return", "False", "try", ":", "conn", "=", "MySQLdb", ".", "connect", "(", "_info", "[", "'hostname'", "]", "...
Authenticate using a MySQL user table
[ "Authenticate", "using", "a", "MySQL", "user", "table" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/mysql.py#L103-L127
train
saltstack/salt
salt/modules/uptime.py
create
def create(name, **params): '''Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org ''' if check_exists(name): msg = 'Trying to create check that already exists : {0}'.format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying PUT request') params.update(url=name) req = requests.put('{0}/api/checks'.format(application_url), data=params) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] PUT request successful') return req.json()['_id']
python
def create(name, **params): '''Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org ''' if check_exists(name): msg = 'Trying to create check that already exists : {0}'.format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying PUT request') params.update(url=name) req = requests.put('{0}/api/checks'.format(application_url), data=params) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] PUT request successful') return req.json()['_id']
[ "def", "create", "(", "name", ",", "*", "*", "params", ")", ":", "if", "check_exists", "(", "name", ")", ":", "msg", "=", "'Trying to create check that already exists : {0}'", ".", "format", "(", "name", ")", "log", ".", "error", "(", "msg", ")", "raise", ...
Create a check on a given URL. Additional parameters can be used and are passed to API (for example interval, maxTime, etc). See the documentation https://github.com/fzaninotto/uptime for a full list of the parameters. CLI Example: .. code-block:: bash salt '*' uptime.create http://example.org
[ "Create", "a", "check", "on", "a", "given", "URL", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uptime.py#L32-L60
train
saltstack/salt
salt/modules/uptime.py
delete
def delete(name): ''' Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org ''' if not check_exists(name): msg = "Trying to delete check that doesn't exists : {0}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying DELETE request') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() url_id = [x['_id'] for x in jcontent if x['url'] == name][0] req = requests.delete('{0}/api/checks/{1}'.format(application_url, url_id)) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] DELETE request successful') return True
python
def delete(name): ''' Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org ''' if not check_exists(name): msg = "Trying to delete check that doesn't exists : {0}".format(name) log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug('[uptime] trying DELETE request') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() url_id = [x['_id'] for x in jcontent if x['url'] == name][0] req = requests.delete('{0}/api/checks/{1}'.format(application_url, url_id)) if not req.ok: raise CommandExecutionError( 'request to uptime failed : {0}'.format(req.reason) ) log.debug('[uptime] DELETE request successful') return True
[ "def", "delete", "(", "name", ")", ":", "if", "not", "check_exists", "(", "name", ")", ":", "msg", "=", "\"Trying to delete check that doesn't exists : {0}\"", ".", "format", "(", "name", ")", "log", ".", "error", "(", "msg", ")", "raise", "CommandExecutionErr...
Delete a check on a given URL CLI Example: .. code-block:: bash salt '*' uptime.delete http://example.org
[ "Delete", "a", "check", "on", "a", "given", "URL" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uptime.py#L63-L87
train
saltstack/salt
salt/modules/uptime.py
checks_list
def checks_list(): ''' List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list ''' application_url = _get_application_url() log.debug('[uptime] get checks') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() return [x['url'] for x in jcontent]
python
def checks_list(): ''' List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list ''' application_url = _get_application_url() log.debug('[uptime] get checks') jcontent = requests.get('{0}/api/checks'.format(application_url)).json() return [x['url'] for x in jcontent]
[ "def", "checks_list", "(", ")", ":", "application_url", "=", "_get_application_url", "(", ")", "log", ".", "debug", "(", "'[uptime] get checks'", ")", "jcontent", "=", "requests", ".", "get", "(", "'{0}/api/checks'", ".", "format", "(", "application_url", ")", ...
List URL checked by uptime CLI Example: .. code-block:: bash salt '*' uptime.checks_list
[ "List", "URL", "checked", "by", "uptime" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/uptime.py#L103-L116
train
saltstack/salt
salt/states/acme.py
cert
def cert(name, aliases=None, email=None, webroot=None, test_cert=False, renew=None, keysize=None, server=None, owner='root', group='root', mode='0640', certname=None, preferred_challenges=None, tls_sni_01_port=None, tls_sni_01_address=None, http_01_port=None, http_01_address=None, dns_plugin=None, dns_plugin_credentials=None): ''' Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full path to webroot. Otherwise use standalone mode :param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server') :param renew: True/'force' to force a renewal, or a window of renewal before expiry in days :param keysize: RSA key bits :param server: API endpoint to talk to :param owner: owner of the private key file :param group: group of the private key file :param mode: mode of the private key file :param certname: Name of the certificate to save :param preferred_challenges: A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first. :param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. :param tls_sni_01_address: The address the server listens to during tls-sni-01 challenge. :param http_01_port: Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. :param https_01_address: The address the server listens to during http-01 challenge. :param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare') :param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin ''' if __opts__['test']: ret = { 'name': name, 'changes': {}, 'result': None } window = None try: window = int(renew) except Exception: pass comment = 'Certificate {0} '.format(name) if not __salt__['acme.has'](name): comment += 'would have been obtained' elif __salt__['acme.needs_renewal'](name, window): comment += 'would have been renewed' else: comment += 'would not have been touched' ret['result'] = True ret['comment'] = comment return ret if not __salt__['acme.has'](name): old = None else: old = __salt__['acme.info'](name) res = __salt__['acme.cert']( name, aliases=aliases, email=email, webroot=webroot, certname=certname, test_cert=test_cert, renew=renew, keysize=keysize, server=server, owner=owner, group=group, mode=mode, preferred_challenges=preferred_challenges, tls_sni_01_port=tls_sni_01_port, tls_sni_01_address=tls_sni_01_address, http_01_port=http_01_port, http_01_address=http_01_address, dns_plugin=dns_plugin, dns_plugin_credentials=dns_plugin_credentials, ) ret = { 'name': name, 'result': res['result'] is not False, 'comment': res['comment'] } if res['result'] is None: ret['changes'] = {} else: if not __salt__['acme.has'](name): new = None else: new = __salt__['acme.info'](name) ret['changes'] = { 'old': old, 'new': new } return ret
python
def cert(name, aliases=None, email=None, webroot=None, test_cert=False, renew=None, keysize=None, server=None, owner='root', group='root', mode='0640', certname=None, preferred_challenges=None, tls_sni_01_port=None, tls_sni_01_address=None, http_01_port=None, http_01_address=None, dns_plugin=None, dns_plugin_credentials=None): ''' Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full path to webroot. Otherwise use standalone mode :param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server') :param renew: True/'force' to force a renewal, or a window of renewal before expiry in days :param keysize: RSA key bits :param server: API endpoint to talk to :param owner: owner of the private key file :param group: group of the private key file :param mode: mode of the private key file :param certname: Name of the certificate to save :param preferred_challenges: A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first. :param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. :param tls_sni_01_address: The address the server listens to during tls-sni-01 challenge. :param http_01_port: Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. :param https_01_address: The address the server listens to during http-01 challenge. :param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare') :param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin ''' if __opts__['test']: ret = { 'name': name, 'changes': {}, 'result': None } window = None try: window = int(renew) except Exception: pass comment = 'Certificate {0} '.format(name) if not __salt__['acme.has'](name): comment += 'would have been obtained' elif __salt__['acme.needs_renewal'](name, window): comment += 'would have been renewed' else: comment += 'would not have been touched' ret['result'] = True ret['comment'] = comment return ret if not __salt__['acme.has'](name): old = None else: old = __salt__['acme.info'](name) res = __salt__['acme.cert']( name, aliases=aliases, email=email, webroot=webroot, certname=certname, test_cert=test_cert, renew=renew, keysize=keysize, server=server, owner=owner, group=group, mode=mode, preferred_challenges=preferred_challenges, tls_sni_01_port=tls_sni_01_port, tls_sni_01_address=tls_sni_01_address, http_01_port=http_01_port, http_01_address=http_01_address, dns_plugin=dns_plugin, dns_plugin_credentials=dns_plugin_credentials, ) ret = { 'name': name, 'result': res['result'] is not False, 'comment': res['comment'] } if res['result'] is None: ret['changes'] = {} else: if not __salt__['acme.has'](name): new = None else: new = __salt__['acme.info'](name) ret['changes'] = { 'old': old, 'new': new } return ret
[ "def", "cert", "(", "name", ",", "aliases", "=", "None", ",", "email", "=", "None", ",", "webroot", "=", "None", ",", "test_cert", "=", "False", ",", "renew", "=", "None", ",", "keysize", "=", "None", ",", "server", "=", "None", ",", "owner", "=", ...
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt. :param name: Common Name of the certificate (DNS name of certificate) :param aliases: subjectAltNames (Additional DNS names on certificate) :param email: e-mail address for interaction with ACME provider :param webroot: True or a full path to webroot. Otherwise use standalone mode :param test_cert: Request a certificate from the Happy Hacker Fake CA (mutually exclusive with 'server') :param renew: True/'force' to force a renewal, or a window of renewal before expiry in days :param keysize: RSA key bits :param server: API endpoint to talk to :param owner: owner of the private key file :param group: group of the private key file :param mode: mode of the private key file :param certname: Name of the certificate to save :param preferred_challenges: A sorted, comma delimited list of the preferred challenge to use during authorization with the most preferred challenge listed first. :param tls_sni_01_port: Port used during tls-sni-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 443. :param tls_sni_01_address: The address the server listens to during tls-sni-01 challenge. :param http_01_port: Port used in the http-01 challenge. This only affects the port Certbot listens on. A conforming ACME server will still attempt to connect on port 80. :param https_01_address: The address the server listens to during http-01 challenge. :param dns_plugin: Name of a DNS plugin to use (currently only 'cloudflare') :param dns_plugin_credentials: Path to the credentials file if required by the specified DNS plugin
[ "Obtain", "/", "renew", "a", "certificate", "from", "an", "ACME", "CA", "probably", "Let", "s", "Encrypt", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/acme.py#L42-L161
train
saltstack/salt
salt/states/vagrant.py
_vagrant_call
def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply ''' ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''} targeted_nodes = [] if isinstance(node, six.string_types): try: # use shortcut if a single node name if __salt__['vagrant.get_vm_info'](node): targeted_nodes = [node] except SaltInvocationError: pass if not targeted_nodes: # the shortcut failed, do this the hard way all_domains = __salt__['vagrant.list_domains']() targeted_nodes = fnmatch.filter(all_domains, node) changed_nodes = [] ignored_nodes = [] for node in targeted_nodes: if status_when_done: try: present_state = __salt__['vagrant.vm_state'](node)[0] if present_state['state'] == status_when_done: continue # no change is needed except (IndexError, SaltInvocationError, CommandExecutionError): pass try: response = __salt__['vagrant.{0}'.format(function)](node, **kwargs) if isinstance(response, dict): response = response['name'] changed_nodes.append({'node': node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: ignored_nodes.append({'node': node, 'issue': six.text_type(err)}) if not changed_nodes: ret['result'] = True ret['comment'] = 'No changes seen' if ignored_nodes: ret['changes'] = {'ignored': ignored_nodes} else: ret['changes'] = {section: changed_nodes} ret['comment'] = comment return ret
python
def _vagrant_call(node, function, section, comment, status_when_done=None, **kwargs): ''' Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply ''' ret = {'name': node, 'changes': {}, 'result': True, 'comment': ''} targeted_nodes = [] if isinstance(node, six.string_types): try: # use shortcut if a single node name if __salt__['vagrant.get_vm_info'](node): targeted_nodes = [node] except SaltInvocationError: pass if not targeted_nodes: # the shortcut failed, do this the hard way all_domains = __salt__['vagrant.list_domains']() targeted_nodes = fnmatch.filter(all_domains, node) changed_nodes = [] ignored_nodes = [] for node in targeted_nodes: if status_when_done: try: present_state = __salt__['vagrant.vm_state'](node)[0] if present_state['state'] == status_when_done: continue # no change is needed except (IndexError, SaltInvocationError, CommandExecutionError): pass try: response = __salt__['vagrant.{0}'.format(function)](node, **kwargs) if isinstance(response, dict): response = response['name'] changed_nodes.append({'node': node, function: response}) except (SaltInvocationError, CommandExecutionError) as err: ignored_nodes.append({'node': node, 'issue': six.text_type(err)}) if not changed_nodes: ret['result'] = True ret['comment'] = 'No changes seen' if ignored_nodes: ret['changes'] = {'ignored': ignored_nodes} else: ret['changes'] = {section: changed_nodes} ret['comment'] = comment return ret
[ "def", "_vagrant_call", "(", "node", ",", "function", ",", "section", ",", "comment", ",", "status_when_done", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "node", ",", "'changes'", ":", "{", "}", ",", "'result'", "...
Helper to call the vagrant functions. Wildcards supported. :param node: The Salt-id or wildcard :param function: the vagrant submodule to call :param section: the name for the state call. :param comment: what the state reply should say :param status_when_done: the Vagrant status expected for this state :return: the dictionary for the state reply
[ "Helper", "to", "call", "the", "vagrant", "functions", ".", "Wildcards", "supported", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L77-L127
train
saltstack/salt
salt/states/vagrant.py
running
def running(name, **kwargs): r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 ''' if '*' in name or '?' in name: return _vagrant_call(name, 'start', 'restarted', "Machine has been restarted", "running") else: ret = {'name': name, 'changes': {}, 'result': True, 'comment': '{0} is already running'.format(name) } try: info = __salt__['vagrant.vm_state'](name) if info[0]['state'] != 'running': __salt__['vagrant.start'](name) ret['changes'][name] = 'Machine started' ret['comment'] = 'Node {0} started'.format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs['start'] = True __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node defined and started' ret['comment'] = 'Node {0} defined and started'.format(name) return ret
python
def running(name, **kwargs): r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 ''' if '*' in name or '?' in name: return _vagrant_call(name, 'start', 'restarted', "Machine has been restarted", "running") else: ret = {'name': name, 'changes': {}, 'result': True, 'comment': '{0} is already running'.format(name) } try: info = __salt__['vagrant.vm_state'](name) if info[0]['state'] != 'running': __salt__['vagrant.start'](name) ret['changes'][name] = 'Machine started' ret['comment'] = 'Node {0} started'.format(name) except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs['start'] = True __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node defined and started' ret['comment'] = 'Node {0} defined and started'.format(name) return ret
[ "def", "running", "(", "name", ",", "*", "*", "kwargs", ")", ":", "if", "'*'", "in", "name", "or", "'?'", "in", "name", ":", "return", "_vagrant_call", "(", "name", ",", "'start'", ",", "'restarted'", ",", "\"Machine has been restarted\"", ",", "\"running\...
r''' Defines and starts a new VM with specified arguments, or restart a VM (or group of VMs). (Runs ``vagrant up``.) :param name: the Salt_id node name you wish your VM to have. If ``name`` contains a "?" or "*" then it will re-start a group of VMs which have been paused or stopped. Each machine must be initially started individually using this function or the vagrant.init execution module call. \[NOTE:\] Keyword arguments are silently ignored when re-starting an existing VM. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name: vagrant.running .. code-block:: yaml node_name: vagrant.running: - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1
[ "r", "Defines", "and", "starts", "a", "new", "VM", "with", "specified", "arguments", "or", "restart", "a", "VM", "(", "or", "group", "of", "VMs", ")", ".", "(", "Runs", "vagrant", "up", ".", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L130-L194
train
saltstack/salt
salt/states/vagrant.py
_find_init_change
def _find_init_change(name, ret, **kwargs): ''' look for changes from any previous init of machine. :return: modified ret and kwargs ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'vm' in kwargs: kwargs.update(kwargs.pop('vm')) # the state processing eats 'runas' so we rename kwargs['runas'] = kwargs.pop('vagrant_runas', '') try: vm_ = __salt__['vagrant.get_vm_info'](name) except SaltInvocationError: vm_ = {} for key, value in kwargs.items(): ret['changes'][key] = {'old': None, 'new': value} if vm_: # test for changed values for key in vm_: value = vm_[key] or '' # supply a blank if value is None if key != 'name': # will be missing in kwargs new = kwargs.get(key, '') if new != value: if key == 'machine' and new == '': continue # we don't know the default machine name ret['changes'][key] = {'old': value, 'new': new} return ret, kwargs
python
def _find_init_change(name, ret, **kwargs): ''' look for changes from any previous init of machine. :return: modified ret and kwargs ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'vm' in kwargs: kwargs.update(kwargs.pop('vm')) # the state processing eats 'runas' so we rename kwargs['runas'] = kwargs.pop('vagrant_runas', '') try: vm_ = __salt__['vagrant.get_vm_info'](name) except SaltInvocationError: vm_ = {} for key, value in kwargs.items(): ret['changes'][key] = {'old': None, 'new': value} if vm_: # test for changed values for key in vm_: value = vm_[key] or '' # supply a blank if value is None if key != 'name': # will be missing in kwargs new = kwargs.get(key, '') if new != value: if key == 'machine' and new == '': continue # we don't know the default machine name ret['changes'][key] = {'old': value, 'new': new} return ret, kwargs
[ "def", "_find_init_change", "(", "name", ",", "ret", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "kwargs", ")", "if", "'vm'", "in", "kwargs", ":", "kwargs", ".", "update", ...
look for changes from any previous init of machine. :return: modified ret and kwargs
[ "look", "for", "changes", "from", "any", "previous", "init", "of", "machine", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L197-L223
train
saltstack/salt
salt/states/vagrant.py
initialized
def initialized(name, **kwargs): r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name? ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'The VM is already correctly defined' } # define a machine to start later ret, kwargs = _find_init_change(name, ret, **kwargs) if ret['changes'] == {}: return ret kwargs['start'] = False __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node initialized' ret['comment'] = 'Node {0} defined but not started.'.format(name) return ret
python
def initialized(name, **kwargs): r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name? ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'The VM is already correctly defined' } # define a machine to start later ret, kwargs = _find_init_change(name, ret, **kwargs) if ret['changes'] == {}: return ret kwargs['start'] = False __salt__['vagrant.init'](name, **kwargs) ret['changes'][name] = 'Node initialized' ret['comment'] = 'Node {0} defined but not started.'.format(name) return ret
[ "def", "initialized", "(", "name", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "'The VM is already correctly defined'", "}", "# define a ma...
r''' Defines a new VM with specified arguments, but does not start it. :param name: the Salt_id node name you wish your VM to have. Each machine must be initialized individually using this function or the "vagrant.running" function, or the vagrant.init execution module call. This command will not change the state of a running or paused machine. Possible keyword arguments: - cwd: The directory (path) containing the Vagrantfile - machine: ('') the name of the machine (in the Vagrantfile) if not default - vagrant_runas: ('root') the username who owns the vagrantbox file - vagrant_provider: the provider to run the VM (usually 'virtualbox') - vm: ({}) a dictionary containing these or other keyword arguments .. code-block:: yaml node_name1: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine1 node_name2: vagrant.initialized - cwd: /projects/my_project - vagrant_runas: my_username - machine: machine2 start_nodes: vagrant.start: - name: node_name?
[ "r", "Defines", "a", "new", "VM", "with", "specified", "arguments", "but", "does", "not", "start", "it", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/vagrant.py#L226-L280
train
saltstack/salt
salt/modules/pw_user.py
_get_gecos
def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])}
python
def _get_gecos(name): ''' Retrieve GECOS field info and return it in dictionary form ''' try: gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3) except KeyError: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if not gecos_field: return {} else: # Assign empty strings for any unspecified trailing GECOS fields while len(gecos_field) < 4: gecos_field.append('') return {'fullname': salt.utils.data.decode(gecos_field[0]), 'roomnumber': salt.utils.data.decode(gecos_field[1]), 'workphone': salt.utils.data.decode(gecos_field[2]), 'homephone': salt.utils.data.decode(gecos_field[3])}
[ "def", "_get_gecos", "(", "name", ")", ":", "try", ":", "gecos_field", "=", "pwd", ".", "getpwnam", "(", "name", ")", ".", "pw_gecos", ".", "split", "(", "','", ",", "3", ")", "except", "KeyError", ":", "raise", "CommandExecutionError", "(", "'User \\'{0...
Retrieve GECOS field info and return it in dictionary form
[ "Retrieve", "GECOS", "field", "info", "and", "return", "it", "in", "dictionary", "form" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L70-L89
train
saltstack/salt
salt/modules/pw_user.py
add
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
python
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, unique=True, fullname='', roomnumber='', workphone='', homephone='', createhome=True, loginclass=None, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_user module does not support the \'system\' argument') if kwargs: log.warning('Invalid kwargs passed to user.add') if isinstance(groups, six.string_types): groups = groups.split(',') cmd = ['pw', 'useradd'] if uid: cmd.extend(['-u', uid]) if gid: cmd.extend(['-g', gid]) if groups: cmd.extend(['-G', ','.join(groups)]) if home is not None: cmd.extend(['-d', home]) if createhome is True: cmd.append('-m') if loginclass: cmd.extend(['-L', loginclass]) if shell: cmd.extend(['-s', shell]) if not salt.utils.data.is_true(unique): cmd.append('-o') gecos_field = _build_gecos({'fullname': fullname, 'roomnumber': roomnumber, 'workphone': workphone, 'homephone': homephone}) cmd.extend(['-c', gecos_field]) cmd.extend(['-n', name]) return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
[ "def", "add", "(", "name", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "groups", "=", "None", ",", "home", "=", "None", ",", "shell", "=", "None", ",", "unique", "=", "True", ",", "fullname", "=", "''", ",", "roomnumber", "=", "''", ...
Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell>
[ "Add", "a", "user", "to", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L122-L176
train
saltstack/salt
salt/modules/pw_user.py
getent
def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret
python
def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(info(data.pw_name)) __context__['user.getent'] = ret return ret
[ "def", "getent", "(", "refresh", "=", "False", ")", ":", "if", "'user.getent'", "in", "__context__", "and", "not", "refresh", ":", "return", "__context__", "[", "'user.getent'", "]", "ret", "=", "[", "]", "for", "data", "in", "pwd", ".", "getpwall", "(",...
Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent
[ "Return", "the", "list", "of", "all", "info", "for", "all", "users" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L199-L216
train
saltstack/salt
salt/modules/pw_user.py
chuid
def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid
python
def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' pre_info = info(name) if not pre_info: raise CommandExecutionError( 'User \'{0}\' does not exist'.format(name) ) if uid == pre_info['uid']: return True cmd = ['pw', 'usermod', '-u', uid, '-n', name] __salt__['cmd.run'](cmd, python_shell=False) return info(name).get('uid') == uid
[ "def", "chuid", "(", "name", ",", "uid", ")", ":", "pre_info", "=", "info", "(", "name", ")", "if", "not", "pre_info", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' does not exist'", ".", "format", "(", "name", ")", ")", "if", "uid", "==", ...
Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376
[ "Change", "the", "uid", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L219-L238
train
saltstack/salt
salt/modules/pw_user.py
chloginclass
def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass
python
def chloginclass(name, loginclass, root=None): ''' Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff ''' if loginclass == get_loginclass(name): return True cmd = ['pw', 'usermod', '-L', '{0}'.format(loginclass), '-n', '{0}'.format(name)] __salt__['cmd.run'](cmd, python_shell=False) return get_loginclass(name) == loginclass
[ "def", "chloginclass", "(", "name", ",", "loginclass", ",", "root", "=", "None", ")", ":", "if", "loginclass", "==", "get_loginclass", "(", "name", ")", ":", "return", "True", "cmd", "=", "[", "'pw'", ",", "'usermod'", ",", "'-L'", ",", "'{0}'", ".", ...
Change the default login class of the user .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt '*' user.chloginclass foo staff
[ "Change", "the", "default", "login", "class", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L405-L425
train
saltstack/salt
salt/modules/pw_user.py
info
def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret
python
def info(name): ''' Return user information CLI Example: .. code-block:: bash salt '*' user.info root ''' ret = {} try: data = pwd.getpwnam(name) ret['gid'] = data.pw_gid ret['groups'] = list_groups(name) ret['home'] = data.pw_dir ret['name'] = data.pw_name ret['passwd'] = data.pw_passwd ret['shell'] = data.pw_shell ret['uid'] = data.pw_uid # Put GECOS info into a list gecos_field = data.pw_gecos.split(',', 3) # Assign empty strings for any unspecified GECOS fields while len(gecos_field) < 4: gecos_field.append('') ret['fullname'] = gecos_field[0] ret['roomnumber'] = gecos_field[1] ret['workphone'] = gecos_field[2] ret['homephone'] = gecos_field[3] except KeyError: return {} return ret
[ "def", "info", "(", "name", ")", ":", "ret", "=", "{", "}", "try", ":", "data", "=", "pwd", ".", "getpwnam", "(", "name", ")", "ret", "[", "'gid'", "]", "=", "data", ".", "pw_gid", "ret", "[", "'groups'", "]", "=", "list_groups", "(", "name", "...
Return user information CLI Example: .. code-block:: bash salt '*' user.info root
[ "Return", "user", "information" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L428-L459
train
saltstack/salt
salt/modules/pw_user.py
get_loginclass
def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else ''
python
def get_loginclass(name): ''' Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' userinfo = __salt__['cmd.run_stdout'](['pw', 'usershow', '-n', name]) userinfo = userinfo.split(':') return userinfo[4] if len(userinfo) == 10 else ''
[ "def", "get_loginclass", "(", "name", ")", ":", "userinfo", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "[", "'pw'", ",", "'usershow'", ",", "'-n'", ",", "name", "]", ")", "userinfo", "=", "userinfo", ".", "split", "(", "':'", ")", "return", "u...
Get the login class of the user .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo
[ "Get", "the", "login", "class", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L462-L479
train
saltstack/salt
salt/modules/pw_user.py
rename
def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
python
def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) cmd = ['pw', 'usermod', '-l', new_name, '-n', name] __salt__['cmd.run'](cmd) post_info = info(new_name) if post_info['name'] != current_info['name']: return post_info['name'] == new_name return False
[ "def", "rename", "(", "name", ",", "new_name", ")", ":", "current_info", "=", "info", "(", "name", ")", "if", "not", "current_info", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' does not exist'", ".", "format", "(", "name", ")", ")", "new_info"...
Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name
[ "Change", "the", "username", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pw_user.py#L508-L531
train
saltstack/salt
salt/proxy/nxos_api.py
init
def init(opts): ''' Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) which doesn't come with much overhead and it's sufficient to confirm we are indeed able to connect to the NX-API endpoint as configured. ''' proxy_dict = opts.get('proxy', {}) conn_args = copy.deepcopy(proxy_dict) conn_args.pop('proxytype', None) opts['multiprocessing'] = conn_args.pop('multiprocessing', True) # This is not a SSH-based proxy, so it should be safe to enable # multiprocessing. try: rpc_reply = __utils__['nxos_api.rpc']('show clock', **conn_args) # Execute a very simple command to confirm we are able to connect properly nxos_device['conn_args'] = conn_args nxos_device['initialized'] = True nxos_device['up'] = True except SaltException: log.error('Unable to connect to %s', conn_args['host'], exc_info=True) raise return True
python
def init(opts): ''' Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) which doesn't come with much overhead and it's sufficient to confirm we are indeed able to connect to the NX-API endpoint as configured. ''' proxy_dict = opts.get('proxy', {}) conn_args = copy.deepcopy(proxy_dict) conn_args.pop('proxytype', None) opts['multiprocessing'] = conn_args.pop('multiprocessing', True) # This is not a SSH-based proxy, so it should be safe to enable # multiprocessing. try: rpc_reply = __utils__['nxos_api.rpc']('show clock', **conn_args) # Execute a very simple command to confirm we are able to connect properly nxos_device['conn_args'] = conn_args nxos_device['initialized'] = True nxos_device['up'] = True except SaltException: log.error('Unable to connect to %s', conn_args['host'], exc_info=True) raise return True
[ "def", "init", "(", "opts", ")", ":", "proxy_dict", "=", "opts", ".", "get", "(", "'proxy'", ",", "{", "}", ")", "conn_args", "=", "copy", ".", "deepcopy", "(", "proxy_dict", ")", "conn_args", ".", "pop", "(", "'proxytype'", ",", "None", ")", "opts",...
Open the connection to the Nexsu switch over the NX-API. As the communication is HTTP based, there is no connection to maintain, however, in order to test the connectivity and make sure we are able to bring up this Minion, we are executing a very simple command (``show clock``) which doesn't come with much overhead and it's sufficient to confirm we are indeed able to connect to the NX-API endpoint as configured.
[ "Open", "the", "connection", "to", "the", "Nexsu", "switch", "over", "the", "NX", "-", "API", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos_api.py#L142-L167
train
saltstack/salt
salt/proxy/nxos_api.py
rpc
def rpc(commands, method='cli', **kwargs): ''' Executes an RPC request over the NX-API. ''' conn_args = nxos_device['conn_args'] conn_args.update(kwargs) return __utils__['nxos_api.rpc'](commands, method=method, **conn_args)
python
def rpc(commands, method='cli', **kwargs): ''' Executes an RPC request over the NX-API. ''' conn_args = nxos_device['conn_args'] conn_args.update(kwargs) return __utils__['nxos_api.rpc'](commands, method=method, **conn_args)
[ "def", "rpc", "(", "commands", ",", "method", "=", "'cli'", ",", "*", "*", "kwargs", ")", ":", "conn_args", "=", "nxos_device", "[", "'conn_args'", "]", "conn_args", ".", "update", "(", "kwargs", ")", "return", "__utils__", "[", "'nxos_api.rpc'", "]", "(...
Executes an RPC request over the NX-API.
[ "Executes", "an", "RPC", "request", "over", "the", "NX", "-", "API", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos_api.py#L203-L209
train
saltstack/salt
salt/cloud/__init__.py
communicator
def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call
python
def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') except KeyboardInterrupt as ex: trace = traceback.format_exc() queue.put('KEYBOARDINT') queue.put('Keyboard interrupt') queue.put('{0}\n{1}\n'.format(ex, trace)) except Exception as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('Exception') queue.put('{0}\n{1}\n'.format(ex, trace)) except SystemExit as ex: trace = traceback.format_exc() queue.put('ERROR') queue.put('System exit') queue.put('{0}\n{1}\n'.format(ex, trace)) return ret return _call
[ "def", "communicator", "(", "func", ")", ":", "def", "_call", "(", "queue", ",", "args", ",", "kwargs", ")", ":", "'''called with [queue, args, kwargs] as first optional arg'''", "kwargs", "[", "'queue'", "]", "=", "queue", "ret", "=", "None", "try", ":", "ret...
Warning, this is a picklable decorator !
[ "Warning", "this", "is", "a", "picklable", "decorator", "!" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L60-L85
train
saltstack/salt
salt/cloud/__init__.py
enter_mainloop
def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret
python
def enter_mainloop(target, mapped_args=None, args=None, kwargs=None, pool=None, pool_size=None, callback=None, queue=None): ''' Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file) ''' if not kwargs: kwargs = {} if not pool_size: pool_size = 1 if not pool: pool = multiprocessing.Pool(pool_size) if not queue: manager = multiprocessing.Manager() queue = manager.Queue() if mapped_args is not None and not mapped_args: msg = ( 'We are called to asynchronously execute {0}' ' but we do no have anything to execute, weird,' ' we bail out'.format(target)) log.error(msg) raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif mapped_args is not None: iterable = [[queue, [arg], kwargs] for arg in mapped_args] ret = pool.map(func=target, iterable=iterable) else: ret = pool.apply(target, [queue, args, kwargs]) while True: test = queue.get() if test in ['ERROR', 'KEYBOARDINT']: type_ = queue.get() trace = queue.get() msg = 'Caught {0}, terminating workers\n'.format(type_) msg += 'TRACE: {0}\n'.format(trace) log.error(msg) pool.terminate() pool.join() raise SaltCloudSystemExit('Exception caught\n{0}'.format(msg)) elif test in ['END'] or (callback and callback(test)): pool.close() pool.join() break else: time.sleep(0.125) return ret
[ "def", "enter_mainloop", "(", "target", ",", "mapped_args", "=", "None", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "pool", "=", "None", ",", "pool_size", "=", "None", ",", "callback", "=", "None", ",", "queue", "=", "None", ")", ":",...
Manage a multiprocessing pool - If the queue does not output anything, the pool runs indefinitely - If the queue returns KEYBOARDINT or ERROR, this will kill the pool totally calling terminate & join and ands with a SaltCloudSystemExit exception notifying callers from the abnormal termination - If the queue returns END or callback is defined and returns True, it just join the process and return the data. target the function you want to execute in multiproccessing pool pool object can be None if you want a default pool, but you ll have then to define pool_size instead pool_size pool size if you did not provide yourself a pool callback a boolean taking a string in argument which returns True to signal that 'target' is finished and we need to join the pool queue A custom multiproccessing queue in case you want to do extra stuff and need it later in your program args positional arguments to call the function with if you don't want to use pool.map mapped_args a list of one or more arguments combinations to call the function with e.g. (foo, [[1], [2]]) will call:: foo([1]) foo([2]) kwargs kwargs to give to the function in case of process Attention, the function must have the following signature: target(queue, *args, **kw) You may use the 'communicator' decorator to generate such a function (see end of this file)
[ "Manage", "a", "multiprocessing", "pool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L88-L182
train
saltstack/salt
salt/cloud/__init__.py
create_multiprocessing
def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) }
python
def create_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the create is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' cloud = Cloud(parallel_data['opts']) try: output = cloud.create( parallel_data['profile'], local_master=parallel_data['local_master'] ) except SaltCloudException as exc: log.error( 'Failed to deploy \'%s\'. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} if parallel_data['opts'].get('show_deploy_args', False) is False and isinstance(output, dict): output.pop('deploy_kwargs', None) return { parallel_data['name']: salt.utils.data.simple_types_filter(output) }
[ "def", "create_multiprocessing", "(", "parallel_data", ",", "queue", "=", "None", ")", ":", "salt", ".", "utils", ".", "crypt", ".", "reinit_crypto", "(", ")", "parallel_data", "[", "'opts'", "]", "[", "'output'", "]", "=", "'json'", "cloud", "=", "Cloud",...
This function will be called from another process when running a map in parallel mode. The result from the create is always a json object.
[ "This", "function", "will", "be", "called", "from", "another", "process", "when", "running", "a", "map", "in", "parallel", "mode", ".", "The", "result", "from", "the", "create", "is", "always", "a", "json", "object", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L2304-L2330
train
saltstack/salt
salt/cloud/__init__.py
destroy_multiprocessing
def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) }
python
def destroy_multiprocessing(parallel_data, queue=None): ''' This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object. ''' salt.utils.crypt.reinit_crypto() parallel_data['opts']['output'] = 'json' clouds = salt.loader.clouds(parallel_data['opts']) try: fun = clouds['{0}.destroy'.format(parallel_data['driver'])] with salt.utils.context.func_globals_inject( fun, __active_provider_name__=':'.join([ parallel_data['alias'], parallel_data['driver'] ]) ): output = fun(parallel_data['name']) except SaltCloudException as exc: log.error( 'Failed to destroy %s. Error: %s', parallel_data['name'], exc, exc_info_on_loglevel=logging.DEBUG ) return {parallel_data['name']: {'Error': str(exc)}} return { parallel_data['name']: salt.utils.data.simple_types_filter(output) }
[ "def", "destroy_multiprocessing", "(", "parallel_data", ",", "queue", "=", "None", ")", ":", "salt", ".", "utils", ".", "crypt", ".", "reinit_crypto", "(", ")", "parallel_data", "[", "'opts'", "]", "[", "'output'", "]", "=", "'json'", "clouds", "=", "salt"...
This function will be called from another process when running a map in parallel mode. The result from the destroy is always a json object.
[ "This", "function", "will", "be", "called", "from", "another", "process", "when", "running", "a", "map", "in", "parallel", "mode", ".", "The", "result", "from", "the", "destroy", "is", "always", "a", "json", "object", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L2333-L2363
train
saltstack/salt
salt/cloud/__init__.py
run_parallel_map_providers_query
def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], ()
python
def run_parallel_map_providers_query(data, queue=None): ''' This function will be called from another process when building the providers map. ''' salt.utils.crypt.reinit_crypto() cloud = Cloud(data['opts']) try: with salt.utils.context.func_globals_inject( cloud.clouds[data['fun']], __active_provider_name__=':'.join([ data['alias'], data['driver'] ]) ): return ( data['alias'], data['driver'], salt.utils.data.simple_types_filter( cloud.clouds[data['fun']]() ) ) except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for running nodes: %s', data['fun'], err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any nodes return data['alias'], data['driver'], ()
[ "def", "run_parallel_map_providers_query", "(", "data", ",", "queue", "=", "None", ")", ":", "salt", ".", "utils", ".", "crypt", ".", "reinit_crypto", "(", ")", "cloud", "=", "Cloud", "(", "data", "[", "'opts'", "]", ")", "try", ":", "with", "salt", "....
This function will be called from another process when building the providers map.
[ "This", "function", "will", "be", "called", "from", "another", "process", "when", "building", "the", "providers", "map", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L2366-L2395
train
saltstack/salt
salt/cloud/__init__.py
CloudClient._opts_defaults
def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts
python
def _opts_defaults(self, **kwargs): ''' Set the opts dict to defaults and allow for opts to be overridden in the kwargs ''' # Let's start with the default salt cloud configuration opts = salt.config.DEFAULT_CLOUD_OPTS.copy() # Update it with the loaded configuration opts.update(self.opts.copy()) # Reset some of the settings to sane values opts['parallel'] = False opts['keep_tmp'] = False opts['deploy'] = True opts['update_bootstrap'] = False opts['show_deploy_args'] = False opts['script_args'] = '' # Update it with the passed kwargs if 'kwargs' in kwargs: opts.update(kwargs['kwargs']) opts.update(kwargs) profile = opts.get('profile', None) # filter other profiles if one is specified if profile: tmp_profiles = opts.get('profiles', {}).copy() for _profile in [a for a in tmp_profiles]: if not _profile == profile: tmp_profiles.pop(_profile) # if profile is specified and we have enough info about providers # also filter them to speedup methods like # __filter_non_working_providers providers = [a.get('provider', '').split(':')[0] for a in six.itervalues(tmp_profiles) if a.get('provider', '')] if providers: _providers = opts.get('providers', {}) for provider in _providers.copy(): if provider not in providers: _providers.pop(provider) return opts
[ "def", "_opts_defaults", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Let's start with the default salt cloud configuration", "opts", "=", "salt", ".", "config", ".", "DEFAULT_CLOUD_OPTS", ".", "copy", "(", ")", "# Update it with the loaded configuration", "opts",...
Set the opts dict to defaults and allow for opts to be overridden in the kwargs
[ "Set", "the", "opts", "dict", "to", "defaults", "and", "allow", "for", "opts", "to", "be", "overridden", "in", "the", "kwargs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L219-L257
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.low
def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
python
def low(self, fun, low): ''' Pass the cloud function and low data structure to run ''' l_fun = getattr(self, fun) f_call = salt.utils.args.format_call(l_fun, low) return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
[ "def", "low", "(", "self", ",", "fun", ",", "low", ")", ":", "l_fun", "=", "getattr", "(", "self", ",", "fun", ")", "f_call", "=", "salt", ".", "utils", ".", "args", ".", "format_call", "(", "l_fun", ",", "low", ")", "return", "l_fun", "(", "*", ...
Pass the cloud function and low data structure to run
[ "Pass", "the", "cloud", "function", "and", "low", "data", "structure", "to", "run" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L259-L265
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.list_sizes
def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) )
python
def list_sizes(self, provider=None): ''' List all available sizes in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.size_list(provider) )
[ "def", "list_sizes", "(", "self", ",", "provider", "=", "None", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "return", "salt", ".", "utils", ".", "data", ".", "simple_types_filter", "(", ...
List all available sizes in configured cloud systems
[ "List", "all", "available", "sizes", "in", "configured", "cloud", "systems" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L267-L274
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.list_images
def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) )
python
def list_images(self, provider=None): ''' List all available images in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.image_list(provider) )
[ "def", "list_images", "(", "self", ",", "provider", "=", "None", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "return", "salt", ".", "utils", ".", "data", ".", "simple_types_filter", "(",...
List all available images in configured cloud systems
[ "List", "all", "available", "images", "in", "configured", "cloud", "systems" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L276-L283
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.list_locations
def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) )
python
def list_locations(self, provider=None): ''' List all available locations in configured cloud systems ''' mapper = salt.cloud.Map(self._opts_defaults()) return salt.utils.data.simple_types_filter( mapper.location_list(provider) )
[ "def", "list_locations", "(", "self", ",", "provider", "=", "None", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "return", "salt", ".", "utils", ".", "data", ".", "simple_types_filter", "...
List all available locations in configured cloud systems
[ "List", "all", "available", "locations", "in", "configured", "cloud", "systems" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L285-L292
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.min_query
def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type)
python
def min_query(self, query_type='list_nodes_min'): ''' Query select instance information ''' mapper = salt.cloud.Map(self._opts_defaults()) mapper.opts['selected_query_option'] = 'list_nodes_min' return mapper.map_providers_parallel(query_type)
[ "def", "min_query", "(", "self", ",", "query_type", "=", "'list_nodes_min'", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "mapper", ".", "opts", "[", "'selected_query_option'", "]", "=", "'...
Query select instance information
[ "Query", "select", "instance", "information" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L318-L324
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.profile
def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) )
python
def profile(self, profile, names, vm_overrides=None, **kwargs): ''' Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}} ''' if not vm_overrides: vm_overrides = {} kwargs['profile'] = profile mapper = salt.cloud.Map(self._opts_defaults(**kwargs)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.run_profile(profile, names, vm_overrides=vm_overrides) )
[ "def", "profile", "(", "self", ",", "profile", ",", "names", ",", "vm_overrides", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "vm_overrides", ":", "vm_overrides", "=", "{", "}", "kwargs", "[", "'profile'", "]", "=", "profile", "mapper"...
Pass in a profile to create, names is a list of vm names to allocate vm_overrides is a special dict that will be per node options overrides Example: .. code-block:: python >>> client= salt.cloud.CloudClient(path='/etc/salt/cloud') >>> client.profile('do_512_git', names=['minion01',]) {'minion01': {'backups_active': 'False', 'created_at': '2014-09-04T18:10:15Z', 'droplet': {'event_id': 31000502, 'id': 2530006, 'image_id': 5140006, 'name': 'minion01', 'size_id': 66}, 'id': '2530006', 'image_id': '5140006', 'ip_address': '107.XXX.XXX.XXX', 'locked': 'True', 'name': 'minion01', 'private_ip_address': None, 'region_id': '4', 'size_id': '66', 'status': 'new'}}
[ "Pass", "in", "a", "profile", "to", "create", "names", "is", "a", "list", "of", "vm", "names", "to", "allocate" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L326-L366
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.map_run
def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) )
python
def map_run(self, path=None, **kwargs): ''' To execute a map ''' kwarg = {} if path: kwarg['map'] = path kwarg.update(kwargs) mapper = salt.cloud.Map(self._opts_defaults(**kwarg)) dmap = mapper.map_data() return salt.utils.data.simple_types_filter( mapper.run_map(dmap) )
[ "def", "map_run", "(", "self", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwarg", "=", "{", "}", "if", "path", ":", "kwarg", "[", "'map'", "]", "=", "path", "kwarg", ".", "update", "(", "kwargs", ")", "mapper", "=", "salt", "...
To execute a map
[ "To", "execute", "a", "map" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L368-L380
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.destroy
def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) )
python
def destroy(self, names): ''' Destroy the named VMs ''' mapper = salt.cloud.Map(self._opts_defaults(destroy=True)) if isinstance(names, six.string_types): names = names.split(',') return salt.utils.data.simple_types_filter( mapper.destroy(names) )
[ "def", "destroy", "(", "self", ",", "names", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", "destroy", "=", "True", ")", ")", "if", "isinstance", "(", "names", ",", "six", ".", "string_types", ")",...
Destroy the named VMs
[ "Destroy", "the", "named", "VMs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L382-L391
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.create
def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret
python
def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = self.opts['providers'] if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: vm_ = kwargs.copy() vm_['name'] = name vm_['driver'] = provider # This function doesn't require a profile, but many cloud drivers # check for profile information (which includes the provider key) to # help with config file debugging and setting up instances. Setting # the profile and provider defaults here avoids errors in other # cloud functions relying on these keys. See SaltStack Issue #41971 # and PR #38166 for more information. vm_['profile'] = None vm_['provider'] = provider ret[name] = salt.utils.data.simple_types_filter( mapper.create(vm_)) return ret
[ "def", "create", "(", "self", ",", "provider", ",", "names", ",", "*", "*", "kwargs", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "providers", "=", "self", ".", "opts", "[", "'provid...
Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', securitygroup='default', delvol_on_destroy=True)
[ "Create", "the", "named", "VMs", "without", "using", "a", "profile" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L393-L430
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.extra_action
def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret
python
def extra_action(self, names, provider, action, **kwargs): ''' Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} ) ''' mapper = salt.cloud.Map(self._opts_defaults()) providers = mapper.map_providers_parallel() if provider in providers: provider += ':{0}'.format(next(six.iterkeys(providers[provider]))) else: return False if isinstance(names, six.string_types): names = names.split(',') ret = {} for name in names: extra_ = kwargs.copy() extra_['name'] = name extra_['provider'] = provider extra_['profile'] = None extra_['action'] = action ret[name] = salt.utils.data.simple_types_filter( mapper.extras(extra_) ) return ret
[ "def", "extra_action", "(", "self", ",", "names", ",", "provider", ",", "action", ",", "*", "*", "kwargs", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "providers", "=", "mapper", ".", ...
Perform actions with block storage devices Example: .. code-block:: python client.extra_action(names=['myblock'], action='volume_create', provider='my-nova', kwargs={'voltype': 'SSD', 'size': 1000} ) client.extra_action(names=['salt-net'], action='network_create', provider='my-nova', kwargs={'cidr': '192.168.100.0/24'} )
[ "Perform", "actions", "with", "block", "storage", "devices" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L432-L466
train
saltstack/salt
salt/cloud/__init__.py
CloudClient.action
def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
python
def action( self, fun=None, cloudmap=None, names=None, provider=None, instance=None, kwargs=None ): ''' Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} ) ''' if kwargs is None: kwargs = {} mapper = salt.cloud.Map(self._opts_defaults( action=fun, names=names, **kwargs)) if instance: if names: raise SaltCloudConfigError( 'Please specify either a list of \'names\' or a single ' '\'instance\', but not both.' ) names = [instance] if names and not provider: self.opts['action'] = fun return mapper.do_action(names, kwargs) if provider and not names: return mapper.do_function(provider, fun, kwargs) else: # This should not be called without either an instance or a # provider. If both an instance/list of names and a provider # are given, then we also need to exit. We can only have one # or the other. raise SaltCloudConfigError( 'Either an instance (or list of names) or a provider must be ' 'specified, but not both.' )
[ "def", "action", "(", "self", ",", "fun", "=", "None", ",", "cloudmap", "=", "None", ",", "names", "=", "None", ",", "provider", "=", "None", ",", "instance", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "kwargs", "is", "None", ":", "...
Execute a single action via the cloud plugin backend Examples: .. code-block:: python client.action(fun='show_instance', names=['myinstance']) client.action(fun='show_image', provider='my-ec2-config', kwargs={'image': 'ami-10314d79'} )
[ "Execute", "a", "single", "action", "via", "the", "cloud", "plugin", "backend" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L468-L518
train
saltstack/salt
salt/cloud/__init__.py
Cloud.get_configured_providers
def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers
python
def get_configured_providers(self): ''' Return the configured providers ''' providers = set() for alias, drivers in six.iteritems(self.opts['providers']): if len(drivers) > 1: for driver in drivers: providers.add('{0}:{1}'.format(alias, driver)) continue providers.add(alias) return providers
[ "def", "get_configured_providers", "(", "self", ")", ":", "providers", "=", "set", "(", ")", "for", "alias", ",", "drivers", "in", "six", ".", "iteritems", "(", "self", ".", "opts", "[", "'providers'", "]", ")", ":", "if", "len", "(", "drivers", ")", ...
Return the configured providers
[ "Return", "the", "configured", "providers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L532-L543
train
saltstack/salt
salt/cloud/__init__.py
Cloud.lookup_providers
def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers
python
def lookup_providers(self, lookup): ''' Get a dict describing the configured providers ''' if lookup is None: lookup = 'all' if lookup == 'all': providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'There are no cloud providers configured.' ) return providers if ':' in lookup: alias, driver = lookup.split(':') if alias not in self.opts['providers'] or \ driver not in self.opts['providers'][alias]: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. Available: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) providers = set() for alias, drivers in six.iteritems(self.opts['providers']): for driver in drivers: if lookup in (alias, driver): providers.add((alias, driver)) if not providers: raise SaltCloudSystemExit( 'No cloud providers matched \'{0}\'. ' 'Available selections: {1}'.format( lookup, ', '.join(self.get_configured_providers()) ) ) return providers
[ "def", "lookup_providers", "(", "self", ",", "lookup", ")", ":", "if", "lookup", "is", "None", ":", "lookup", "=", "'all'", "if", "lookup", "==", "'all'", ":", "providers", "=", "set", "(", ")", "for", "alias", ",", "drivers", "in", "six", ".", "iter...
Get a dict describing the configured providers
[ "Get", "a", "dict", "describing", "the", "configured", "providers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L545-L587
train
saltstack/salt
salt/cloud/__init__.py
Cloud.lookup_profiles
def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles
python
def lookup_profiles(self, provider, lookup): ''' Return a dictionary describing the configured profiles ''' if provider is None: provider = 'all' if lookup is None: lookup = 'all' if lookup == 'all': profiles = set() provider_profiles = set() for alias, info in six.iteritems(self.opts['profiles']): providers = info.get('provider') if providers: given_prov_name = providers.split(':')[0] salt_prov_name = providers.split(':')[1] if given_prov_name == provider: provider_profiles.add((alias, given_prov_name)) elif salt_prov_name == provider: provider_profiles.add((alias, salt_prov_name)) profiles.add((alias, given_prov_name)) if not profiles: raise SaltCloudSystemExit( 'There are no cloud profiles configured.' ) if provider != 'all': return provider_profiles return profiles
[ "def", "lookup_profiles", "(", "self", ",", "provider", ",", "lookup", ")", ":", "if", "provider", "is", "None", ":", "provider", "=", "'all'", "if", "lookup", "is", "None", ":", "lookup", "=", "'all'", "if", "lookup", "==", "'all'", ":", "profiles", "...
Return a dictionary describing the configured profiles
[ "Return", "a", "dictionary", "describing", "the", "configured", "profiles" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L589-L621
train
saltstack/salt
salt/cloud/__init__.py
Cloud.map_providers
def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap
python
def map_providers(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] pmap = {} for alias, drivers in six.iteritems(self.opts['providers']): for driver, details in six.iteritems(drivers): fun = '{0}.{1}'.format(driver, query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue if alias not in pmap: pmap[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): pmap[alias][driver] = self.clouds[fun]() except Exception as err: log.debug( 'Failed to execute \'%s()\' while querying for ' 'running nodes: %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) # Failed to communicate with the provider, don't list any # nodes pmap[alias][driver] = [] self.__cached_provider_queries[query] = pmap return pmap
[ "def", "map_providers", "(", "self", ",", "query", "=", "'list_nodes'", ",", "cached", "=", "False", ")", ":", "if", "cached", "is", "True", "and", "query", "in", "self", ".", "__cached_provider_queries", ":", "return", "self", ".", "__cached_provider_queries"...
Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs
[ "Return", "a", "mapping", "of", "what", "named", "VMs", "are", "running", "on", "what", "VM", "providers", "based", "on", "what", "providers", "are", "defined", "in", "the", "configuration", "and", "VMs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L623-L657
train
saltstack/salt
salt/cloud/__init__.py
Cloud.map_providers_parallel
def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output
python
def map_providers_parallel(self, query='list_nodes', cached=False): ''' Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel. ''' if cached is True and query in self.__cached_provider_queries: return self.__cached_provider_queries[query] opts = self.opts.copy() multiprocessing_data = [] # Optimize Providers opts['providers'] = self._optimize_providers(opts['providers']) for alias, drivers in six.iteritems(opts['providers']): # Make temp query for this driver to avoid overwrite next this_query = query for driver, details in six.iteritems(drivers): # If driver has function list_nodes_min, just replace it # with query param to check existing vms on this driver # for minimum information, Otherwise still use query param. if opts.get('selected_query_option') is None and '{0}.list_nodes_min'.format(driver) in self.clouds: this_query = 'list_nodes_min' fun = '{0}.{1}'.format(driver, this_query) if fun not in self.clouds: log.error('Public cloud provider %s is not available', driver) continue multiprocessing_data.append({ 'fun': fun, 'opts': opts, 'query': this_query, 'alias': alias, 'driver': driver }) output = {} if not multiprocessing_data: return output data_count = len(multiprocessing_data) pool = multiprocessing.Pool(data_count < 10 and data_count or 10, init_pool_worker) parallel_pmap = enter_mainloop(_run_parallel_map_providers_query, multiprocessing_data, pool=pool) for alias, driver, details in parallel_pmap: if not details: # There's no providers details?! Skip it! continue if alias not in output: output[alias] = {} output[alias][driver] = details self.__cached_provider_queries[query] = output return output
[ "def", "map_providers_parallel", "(", "self", ",", "query", "=", "'list_nodes'", ",", "cached", "=", "False", ")", ":", "if", "cached", "is", "True", "and", "query", "in", "self", ".", "__cached_provider_queries", ":", "return", "self", ".", "__cached_provider...
Return a mapping of what named VMs are running on what VM providers based on what providers are defined in the configuration and VMs Same as map_providers but query in parallel.
[ "Return", "a", "mapping", "of", "what", "named", "VMs", "are", "running", "on", "what", "VM", "providers", "based", "on", "what", "providers", "are", "defined", "in", "the", "configuration", "and", "VMs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L659-L715
train
saltstack/salt
salt/cloud/__init__.py
Cloud._optimize_providers
def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers
python
def _optimize_providers(self, providers): ''' Return an optimized mapping of available providers ''' new_providers = {} provider_by_driver = {} for alias, driver in six.iteritems(providers): for name, data in six.iteritems(driver): if name not in provider_by_driver: provider_by_driver[name] = {} provider_by_driver[name][alias] = data for driver, providers_data in six.iteritems(provider_by_driver): fun = '{0}.optimize_providers'.format(driver) if fun not in self.clouds: log.debug('The \'%s\' cloud driver is unable to be optimized.', driver) for name, prov_data in six.iteritems(providers_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data continue new_data = self.clouds[fun](providers_data) if new_data: for name, prov_data in six.iteritems(new_data): if name not in new_providers: new_providers[name] = {} new_providers[name][driver] = prov_data return new_providers
[ "def", "_optimize_providers", "(", "self", ",", "providers", ")", ":", "new_providers", "=", "{", "}", "provider_by_driver", "=", "{", "}", "for", "alias", ",", "driver", "in", "six", ".", "iteritems", "(", "providers", ")", ":", "for", "name", ",", "dat...
Return an optimized mapping of available providers
[ "Return", "an", "optimized", "mapping", "of", "available", "providers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L763-L795
train
saltstack/salt
salt/cloud/__init__.py
Cloud.image_list
def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data
python
def image_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: fun = '{0}.avail_images'.format(driver) if fun not in self.clouds: # The capability to gather images is not supported by this # cloud module log.debug( 'The \'%s\' cloud driver defined under \'%s\' provider ' 'alias is unable to get the images information', driver, alias ) continue if alias not in data: data[alias] = {} try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): data[alias][driver] = self.clouds[fun]() except Exception as err: log.error( 'Failed to get the output of \'%s()\': %s', fun, err, exc_info_on_loglevel=logging.DEBUG ) return data
[ "def", "image_list", "(", "self", ",", "lookup", "=", "'all'", ")", ":", "data", "=", "{", "}", "lookups", "=", "self", ".", "lookup_providers", "(", "lookup", ")", "if", "not", "lookups", ":", "return", "data", "for", "alias", ",", "driver", "in", "...
Return a mapping of all image data for available providers
[ "Return", "a", "mapping", "of", "all", "image", "data", "for", "available", "providers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L836-L872
train
saltstack/salt
salt/cloud/__init__.py
Cloud.provider_list
def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data
python
def provider_list(self, lookup='all'): ''' Return a mapping of all image data for available providers ''' data = {} lookups = self.lookup_providers(lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data
[ "def", "provider_list", "(", "self", ",", "lookup", "=", "'all'", ")", ":", "data", "=", "{", "}", "lookups", "=", "self", ".", "lookup_providers", "(", "lookup", ")", "if", "not", "lookups", ":", "return", "data", "for", "alias", ",", "driver", "in", ...
Return a mapping of all image data for available providers
[ "Return", "a", "mapping", "of", "all", "image", "data", "for", "available", "providers" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L912-L926
train
saltstack/salt
salt/cloud/__init__.py
Cloud.profile_list
def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data
python
def profile_list(self, provider, lookup='all'): ''' Return a mapping of all configured profiles ''' data = {} lookups = self.lookup_profiles(provider, lookup) if not lookups: return data for alias, driver in lookups: if alias not in data: data[alias] = {} if driver not in data[alias]: data[alias][driver] = {} return data
[ "def", "profile_list", "(", "self", ",", "provider", ",", "lookup", "=", "'all'", ")", ":", "data", "=", "{", "}", "lookups", "=", "self", ".", "lookup_profiles", "(", "provider", ",", "lookup", ")", "if", "not", "lookups", ":", "return", "data", "for"...
Return a mapping of all configured profiles
[ "Return", "a", "mapping", "of", "all", "configured", "profiles" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L928-L943
train
saltstack/salt
salt/cloud/__init__.py
Cloud.create_all
def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret
python
def create_all(self): ''' Create/Verify the VMs in the VM data ''' ret = [] for vm_name, vm_details in six.iteritems(self.opts['profiles']): ret.append( {vm_name: self.create(vm_details)} ) return ret
[ "def", "create_all", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "vm_name", ",", "vm_details", "in", "six", ".", "iteritems", "(", "self", ".", "opts", "[", "'profiles'", "]", ")", ":", "ret", ".", "append", "(", "{", "vm_name", ":", "self"...
Create/Verify the VMs in the VM data
[ "Create", "/", "Verify", "the", "VMs", "in", "the", "VM", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L945-L956
train
saltstack/salt
salt/cloud/__init__.py
Cloud.destroy
def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed
python
def destroy(self, names, cached=False): ''' Destroy the named VMs ''' processed = {} names = set(names) matching = self.get_running_by_names(names, cached=cached) vms_to_destroy = set() parallel_data = [] for alias, drivers in six.iteritems(matching): for driver, vms in six.iteritems(drivers): for name in vms: if name in names: vms_to_destroy.add((alias, driver, name)) if self.opts['parallel']: parallel_data.append({ 'opts': self.opts, 'name': name, 'alias': alias, 'driver': driver, }) # destroying in parallel if self.opts['parallel'] and parallel_data: # set the pool size based on configuration or default to # the number of machines we're destroying if 'pool_size' in self.opts: pool_size = self.opts['pool_size'] else: pool_size = len(parallel_data) log.info('Destroying in parallel mode; ' 'Cloud pool size: %s', pool_size) # kick off the parallel destroy output_multip = enter_mainloop( _destroy_multiprocessing, parallel_data, pool_size=pool_size) # massage the multiprocessing output a bit ret_multip = {} for obj in output_multip: ret_multip.update(obj) # build up a data structure similar to what the non-parallel # destroy uses for obj in parallel_data: alias = obj['alias'] driver = obj['driver'] name = obj['name'] if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret_multip[name] if name in names: names.remove(name) # not destroying in parallel else: log.info('Destroying in non-parallel mode.') for alias, driver, name in vms_to_destroy: fun = '{0}.destroy'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): ret = self.clouds[fun](name) if alias not in processed: processed[alias] = {} if driver not in processed[alias]: processed[alias][driver] = {} processed[alias][driver][name] = ret if name in names: names.remove(name) # now the processed data structure contains the output from either # the parallel or non-parallel destroy and we should finish up # with removing minion keys if necessary for alias, driver, name in vms_to_destroy: ret = processed[alias][driver][name] if not ret: continue vm_ = { 'name': name, 'profile': None, 'provider': ':'.join([alias, driver]), 'driver': driver } minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) key_file = os.path.join( self.opts['pki_dir'], 'minions', minion_dict.get('id', name) ) globbed_key_file = glob.glob('{0}.*'.format(key_file)) if not os.path.isfile(key_file) and not globbed_key_file: # There's no such key file!? It might have been renamed if isinstance(ret, dict) and 'newname' in ret: salt.utils.cloud.remove_key( self.opts['pki_dir'], ret['newname'] ) continue if os.path.isfile(key_file) and not globbed_key_file: # Single key entry. Remove it! salt.utils.cloud.remove_key(self.opts['pki_dir'], os.path.basename(key_file)) continue # Since we have globbed matches, there are probably some keys for which their minion # configuration has append_domain set. if not os.path.isfile(key_file) and globbed_key_file and len(globbed_key_file) == 1: # Single entry, let's remove it! salt.utils.cloud.remove_key( self.opts['pki_dir'], os.path.basename(globbed_key_file[0]) ) continue # Since we can't get the profile or map entry used to create # the VM, we can't also get the append_domain setting. # And if we reached this point, we have several minion keys # who's name starts with the machine name we're deleting. # We need to ask one by one!? print( 'There are several minion keys who\'s name starts ' 'with \'{0}\'. We need to ask you which one should be ' 'deleted:'.format( name ) ) while True: for idx, filename in enumerate(globbed_key_file): print(' {0}: {1}'.format( idx, os.path.basename(filename) )) selection = input( 'Which minion key should be deleted(number)? ' ) try: selection = int(selection) except ValueError: print( '\'{0}\' is not a valid selection.'.format(selection) ) try: filename = os.path.basename( globbed_key_file.pop(selection) ) except Exception: continue delete = input( 'Delete \'{0}\'? [Y/n]? '.format(filename) ) if delete == '' or delete.lower().startswith('y'): salt.utils.cloud.remove_key( self.opts['pki_dir'], filename ) print('Deleted \'{0}\''.format(filename)) break print('Did not delete \'{0}\''.format(filename)) break if names and not processed: # These machines were asked to be destroyed but could not be found raise SaltCloudSystemExit( 'The following VM\'s were not found: {0}'.format( ', '.join(names) ) ) elif names and processed: processed['Not Found'] = names elif not processed: raise SaltCloudSystemExit('No machines were destroyed!') return processed
[ "def", "destroy", "(", "self", ",", "names", ",", "cached", "=", "False", ")", ":", "processed", "=", "{", "}", "names", "=", "set", "(", "names", ")", "matching", "=", "self", ".", "get_running_by_names", "(", "names", ",", "cached", "=", "cached", ...
Destroy the named VMs
[ "Destroy", "the", "named", "VMs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L958-L1138
train
saltstack/salt
salt/cloud/__init__.py
Cloud.reboot
def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret
python
def reboot(self, names): ''' Reboot the named VMs ''' ret = [] pmap = self.map_providers_parallel() acts = {} for prov, nodes in six.iteritems(pmap): acts[prov] = [] for node in nodes: if node in names: acts[prov].append(node) for prov, names_ in six.iteritems(acts): fun = '{0}.reboot'.format(prov) for name in names_: ret.append({ name: self.clouds[fun](name) }) return ret
[ "def", "reboot", "(", "self", ",", "names", ")", ":", "ret", "=", "[", "]", "pmap", "=", "self", ".", "map_providers_parallel", "(", ")", "acts", "=", "{", "}", "for", "prov", ",", "nodes", "in", "six", ".", "iteritems", "(", "pmap", ")", ":", "a...
Reboot the named VMs
[ "Reboot", "the", "named", "VMs" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L1140-L1159
train
saltstack/salt
salt/cloud/__init__.py
Cloud.create
def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output
python
def create(self, vm_, local_master=True): ''' Create a single VM ''' output = {} minion_dict = salt.config.get_cloud_config_value( 'minion', vm_, self.opts, default={} ) alias, driver = vm_['provider'].split(':') fun = '{0}.create'.format(driver) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', vm_['name'], vm_['provider'], driver ) return deploy = salt.config.get_cloud_config_value('deploy', vm_, self.opts) make_master = salt.config.get_cloud_config_value( 'make_master', vm_, self.opts ) if deploy: if not make_master and 'master' not in minion_dict: log.warning( 'There\'s no master defined on the \'%s\' VM settings.', vm_['name'] ) if 'pub_key' not in vm_ and 'priv_key' not in vm_: log.debug('Generating minion keys for \'%s\'', vm_['name']) priv, pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['pub_key'] = pub vm_['priv_key'] = priv else: # Note(pabelanger): We still reference pub_key and priv_key when # deploy is disabled. vm_['pub_key'] = None vm_['priv_key'] = None key_id = minion_dict.get('id', vm_['name']) domain = vm_.get('domain') if vm_.get('use_fqdn') and domain: minion_dict['append_domain'] = domain if 'append_domain' in minion_dict: key_id = '.'.join([key_id, minion_dict['append_domain']]) if make_master is True and 'master_pub' not in vm_ and 'master_pem' not in vm_: log.debug('Generating the master keys for \'%s\'', vm_['name']) master_priv, master_pub = salt.utils.cloud.gen_keys( salt.config.get_cloud_config_value( 'keysize', vm_, self.opts ) ) vm_['master_pub'] = master_pub vm_['master_pem'] = master_priv if local_master is True and deploy is True: # Accept the key on the local master salt.utils.cloud.accept_key( self.opts['pki_dir'], vm_['pub_key'], key_id ) vm_['os'] = salt.config.get_cloud_config_value( 'script', vm_, self.opts ) try: vm_['inline_script'] = salt.config.get_cloud_config_value( 'inline_script', vm_, self.opts ) except KeyError: pass try: alias, driver = vm_['provider'].split(':') func = '{0}.create'.format(driver) with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): output = self.clouds[func](vm_) if output is not False and 'sync_after_install' in self.opts: if self.opts['sync_after_install'] not in ( 'all', 'modules', 'states', 'grains'): log.error('Bad option for sync_after_install') return output # A small pause helps the sync work more reliably time.sleep(3) start = int(time.time()) while int(time.time()) < start + 60: # We'll try every <timeout> seconds, up to a minute mopts_ = salt.config.DEFAULT_MASTER_OPTS conf_path = '/'.join(self.opts['conf_file'].split('/')[:-1]) mopts_.update( salt.config.master_config( os.path.join(conf_path, 'master') ) ) client = salt.client.get_local_client(mopts=mopts_) ret = client.cmd( vm_['name'], 'saltutil.sync_{0}'.format(self.opts['sync_after_install']), timeout=self.opts['timeout'] ) if ret: log.info( six.u('Synchronized the following dynamic modules: ' ' {0}').format(ret) ) break except KeyError as exc: log.exception( 'Failed to create VM %s. Configuration value %s needs ' 'to be set', vm_['name'], exc ) # If it's a map then we need to respect the 'requires' # so we do it later try: opt_map = self.opts['map'] except KeyError: opt_map = False if self.opts['parallel'] and self.opts['start_action'] and not opt_map: log.info('Running %s on %s', self.opts['start_action'], vm_['name']) client = salt.client.get_local_client(mopts=self.opts) action_out = client.cmd( vm_['name'], self.opts['start_action'], timeout=self.opts['timeout'] * 60 ) output['ret'] = action_out return output
[ "def", "create", "(", "self", ",", "vm_", ",", "local_master", "=", "True", ")", ":", "output", "=", "{", "}", "minion_dict", "=", "salt", ".", "config", ".", "get_cloud_config_value", "(", "'minion'", ",", "vm_", ",", "self", ".", "opts", ",", "defaul...
Create a single VM
[ "Create", "a", "single", "VM" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L1161-L1316
train
saltstack/salt
salt/cloud/__init__.py
Cloud.vm_config
def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm
python
def vm_config(name, main, provider, profile, overrides): ''' Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides ''' vm = main.copy() vm = salt.utils.dictupdate.update(vm, provider) vm = salt.utils.dictupdate.update(vm, profile) vm.update(overrides) vm['name'] = name return vm
[ "def", "vm_config", "(", "name", ",", "main", ",", "provider", ",", "profile", ",", "overrides", ")", ":", "vm", "=", "main", ".", "copy", "(", ")", "vm", "=", "salt", ".", "utils", ".", "dictupdate", ".", "update", "(", "vm", ",", "provider", ")",...
Create vm config. :param str name: The name of the vm :param dict main: The main cloud config :param dict provider: The provider config :param dict profile: The profile config :param dict overrides: The vm's config overrides
[ "Create", "vm", "config", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L1319-L1334
train
saltstack/salt
salt/cloud/__init__.py
Cloud.extras
def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output
python
def extras(self, extra_): ''' Extra actions ''' output = {} alias, driver = extra_['provider'].split(':') fun = '{0}.{1}'.format(driver, extra_['action']) if fun not in self.clouds: log.error( 'Creating \'%s\' using \'%s\' as the provider ' 'cannot complete since \'%s\' is not available', extra_['name'], extra_['provider'], driver ) return try: with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=extra_['provider'] ): output = self.clouds[fun](**extra_) except KeyError as exc: log.exception( 'Failed to perform %s.%s on %s. ' 'Configuration value %s needs to be set', extra_['provider'], extra_['action'], extra_['name'], exc ) return output
[ "def", "extras", "(", "self", ",", "extra_", ")", ":", "output", "=", "{", "}", "alias", ",", "driver", "=", "extra_", "[", "'provider'", "]", ".", "split", "(", "':'", ")", "fun", "=", "'{0}.{1}'", ".", "format", "(", "driver", ",", "extra_", "[",...
Extra actions
[ "Extra", "actions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L1336-L1364
train
saltstack/salt
salt/cloud/__init__.py
Cloud.run_profile
def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret
python
def run_profile(self, profile, names, vm_overrides=None): ''' Parse over the options passed on the command line and determine how to handle them ''' if profile not in self.opts['profiles']: msg = 'Profile {0} is not defined'.format(profile) log.error(msg) return {'Error': msg} ret = {} if not vm_overrides: vm_overrides = {} try: with salt.utils.files.fopen(self.opts['conf_file'], 'r') as mcc: main_cloud_config = salt.utils.yaml.safe_load(mcc) if not main_cloud_config: main_cloud_config = {} except KeyError: main_cloud_config = {} except IOError: main_cloud_config = {} if main_cloud_config is None: main_cloud_config = {} mapped_providers = self.map_providers_parallel() profile_details = self.opts['profiles'][profile] vms = {} for prov, val in six.iteritems(mapped_providers): prov_name = next(iter(val)) for node in mapped_providers[prov][prov_name]: vms[node] = mapped_providers[prov][prov_name][node] vms[node]['provider'] = prov vms[node]['driver'] = prov_name alias, driver = profile_details['provider'].split(':') provider_details = self.opts['providers'][alias][driver].copy() del provider_details['profiles'] for name in names: if name in vms: prov = vms[name]['provider'] driv = vms[name]['driver'] msg = '{0} already exists under {1}:{2}'.format( name, prov, driv ) log.error(msg) ret[name] = {'Error': msg} continue vm_ = self.vm_config( name, main_cloud_config, provider_details, profile_details, vm_overrides, ) if self.opts['parallel']: process = multiprocessing.Process( target=self.create, args=(vm_,) ) process.start() ret[name] = { 'Provisioning': 'VM being provisioned in parallel. ' 'PID: {0}'.format(process.pid) } continue try: # No need to inject __active_provider_name__ into the context # here because self.create takes care of that ret[name] = self.create(vm_) if not ret[name]: ret[name] = {'Error': 'Failed to deploy VM'} if len(names) == 1: raise SaltCloudSystemExit('Failed to deploy VM') continue if self.opts.get('show_deploy_args', False) is False: ret[name].pop('deploy_kwargs', None) except (SaltCloudSystemExit, SaltCloudConfigError) as exc: if len(names) == 1: raise ret[name] = {'Error': str(exc)} return ret
[ "def", "run_profile", "(", "self", ",", "profile", ",", "names", ",", "vm_overrides", "=", "None", ")", ":", "if", "profile", "not", "in", "self", ".", "opts", "[", "'profiles'", "]", ":", "msg", "=", "'Profile {0} is not defined'", ".", "format", "(", "...
Parse over the options passed on the command line and determine how to handle them
[ "Parse", "over", "the", "options", "passed", "on", "the", "command", "line", "and", "determine", "how", "to", "handle", "them" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L1366-L1453
train
saltstack/salt
salt/cloud/__init__.py
Cloud.do_action
def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret
python
def do_action(self, names, kwargs): ''' Perform an action on a VM which may be specific to this cloud provider ''' ret = {} invalid_functions = {} names = set(names) for alias, drivers in six.iteritems(self.map_providers_parallel()): if not names: break for driver, vms in six.iteritems(drivers): if not names: break valid_function = True fun = '{0}.{1}'.format(driver, self.opts['action']) if fun not in self.clouds: log.info('\'%s()\' is not available. Not actioning...', fun) valid_function = False for vm_name, vm_details in six.iteritems(vms): if not names: break if vm_name not in names: if not isinstance(vm_details, dict): vm_details = {} if 'id' in vm_details and vm_details['id'] in names: vm_name = vm_details['id'] else: log.debug( 'vm:%s in provider:%s is not in name ' 'list:\'%s\'', vm_name, driver, names ) continue # Build the dictionary of invalid functions with their associated VMs. if valid_function is False: if invalid_functions.get(fun) is None: invalid_functions.update({fun: []}) invalid_functions[fun].append(vm_name) continue with salt.utils.context.func_globals_inject( self.clouds[fun], __active_provider_name__=':'.join([alias, driver]) ): if alias not in ret: ret[alias] = {} if driver not in ret[alias]: ret[alias][driver] = {} # Clean kwargs of "__pub_*" data before running the cloud action call. # Prevents calling positional "kwarg" arg before "call" when no kwarg # argument is present in the cloud driver function's arg spec. kwargs = salt.utils.args.clean_kwargs(**kwargs) if kwargs: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, kwargs, call='action' ) else: ret[alias][driver][vm_name] = self.clouds[fun]( vm_name, call='action' ) names.remove(vm_name) # Set the return information for the VMs listed in the invalid_functions dict. missing_vms = set() if invalid_functions: ret['Invalid Actions'] = invalid_functions invalid_func_vms = set() for key, val in six.iteritems(invalid_functions): invalid_func_vms = invalid_func_vms.union(set(val)) # Find the VMs that are in names, but not in set of invalid functions. missing_vms = names.difference(invalid_func_vms) if missing_vms: ret['Not Found'] = list(missing_vms) ret['Not Actioned/Not Running'] = list(names) if not names: return ret # Don't return missing VM information for invalid functions until after we've had a # Chance to return successful actions. If a function is valid for one driver, but # Not another, we want to make sure the successful action is returned properly. if missing_vms: return ret # If we reach this point, the Not Actioned and Not Found lists will be the same, # But we want to list both for clarity/consistency with the invalid functions lists. ret['Not Actioned/Not Running'] = list(names) ret['Not Found'] = list(names) return ret
[ "def", "do_action", "(", "self", ",", "names", ",", "kwargs", ")", ":", "ret", "=", "{", "}", "invalid_functions", "=", "{", "}", "names", "=", "set", "(", "names", ")", "for", "alias", ",", "drivers", "in", "six", ".", "iteritems", "(", "self", "....
Perform an action on a VM which may be specific to this cloud provider
[ "Perform", "an", "action", "on", "a", "VM", "which", "may", "be", "specific", "to", "this", "cloud", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/__init__.py#L1455-L1547
train