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/states/boto3_elasticache.py | cache_subnet_group_present | def cache_subnet_group_present(name, subnets=None, region=None, key=None, keyid=None, profile=None,
**args):
'''
Ensure cache subnet group exists.
name
A name for the cache subnet group. This value is stored as a lowercase string.
Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
subnets
A list of VPC subnets (IDs, Names, or a mix) for the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group. This value is stored as a lowercase string.
Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
CacheSubnetGroupDescription
A description for the cache subnet group.
SubnetIds
A list of VPC subnet IDs for the cache subnet group. This is ADDITIVE with 'subnets' above.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
current = __salt__['boto3_elasticache.'
'describe_cache_subnet_groups'](name, region=region, key=key,
keyid=keyid, profile=profile)
if current:
check_update = True
else:
check_update = False
if __opts__['test']:
ret['comment'] = 'Cache subnet group {0} would be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto3_elasticache.'
'create_cache_subnet_group'](name, subnets=subnets,
region=region, key=key, keyid=keyid,
profile=profile, **args)
if created:
new = __salt__['boto3_elasticache.'
'describe_cache_subnet_groups'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['comment'] = 'Cache subnet group {0} was created.'.format(name)
ret['changes']['old'] = None
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} cache subnet group.'.format(name)
if check_update:
need_update = _diff_cache_subnet_group(current, args)
if need_update:
if __opts__['test']:
ret['comment'] = 'Cache subnet group {0} would be modified.'.format(name)
ret['result'] = None
return ret
modified = __salt__['boto3_elasticache.'
'modify_cache_subnet_group'](name, subnets=subnets,
region=region, key=key, keyid=keyid,
profile=profile, **need_update)
if modified:
new = __salt__['boto3_elasticache.'
'describe_cache_subnet_groups'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['comment'] = 'Cache subnet group {0} was modified.'.format(name)
ret['changes']['old'] = current['CacheSubetGroups'][0]
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to modify cache subnet group {0}.'.format(name)
else:
ret['comment'] = 'Cache subnet group {0} is in the desired state.'.format(name)
return ret | python | def cache_subnet_group_present(name, subnets=None, region=None, key=None, keyid=None, profile=None,
**args):
'''
Ensure cache subnet group exists.
name
A name for the cache subnet group. This value is stored as a lowercase string.
Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
subnets
A list of VPC subnets (IDs, Names, or a mix) for the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group. This value is stored as a lowercase string.
Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
CacheSubnetGroupDescription
A description for the cache subnet group.
SubnetIds
A list of VPC subnet IDs for the cache subnet group. This is ADDITIVE with 'subnets' above.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
current = __salt__['boto3_elasticache.'
'describe_cache_subnet_groups'](name, region=region, key=key,
keyid=keyid, profile=profile)
if current:
check_update = True
else:
check_update = False
if __opts__['test']:
ret['comment'] = 'Cache subnet group {0} would be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto3_elasticache.'
'create_cache_subnet_group'](name, subnets=subnets,
region=region, key=key, keyid=keyid,
profile=profile, **args)
if created:
new = __salt__['boto3_elasticache.'
'describe_cache_subnet_groups'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['comment'] = 'Cache subnet group {0} was created.'.format(name)
ret['changes']['old'] = None
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} cache subnet group.'.format(name)
if check_update:
need_update = _diff_cache_subnet_group(current, args)
if need_update:
if __opts__['test']:
ret['comment'] = 'Cache subnet group {0} would be modified.'.format(name)
ret['result'] = None
return ret
modified = __salt__['boto3_elasticache.'
'modify_cache_subnet_group'](name, subnets=subnets,
region=region, key=key, keyid=keyid,
profile=profile, **need_update)
if modified:
new = __salt__['boto3_elasticache.'
'describe_cache_subnet_groups'](name, region=region, key=key,
keyid=keyid, profile=profile)
ret['comment'] = 'Cache subnet group {0} was modified.'.format(name)
ret['changes']['old'] = current['CacheSubetGroups'][0]
ret['changes']['new'] = new[0]
else:
ret['result'] = False
ret['comment'] = 'Failed to modify cache subnet group {0}.'.format(name)
else:
ret['comment'] = 'Cache subnet group {0} is in the desired state.'.format(name)
return ret | [
"def",
"cache_subnet_group_present",
"(",
"name",
",",
"subnets",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"ret",
"=",
"{",
"'name'",
... | Ensure cache subnet group exists.
name
A name for the cache subnet group. This value is stored as a lowercase string.
Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
subnets
A list of VPC subnets (IDs, Names, or a mix) for the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group. This value is stored as a lowercase string.
Constraints: Must contain no more than 255 alphanumeric characters or hyphens.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
CacheSubnetGroupDescription
A description for the cache subnet group.
SubnetIds
A list of VPC subnet IDs for the cache subnet group. This is ADDITIVE with 'subnets' above.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"cache",
"subnet",
"group",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L1014-L1101 | train |
saltstack/salt | salt/states/boto3_elasticache.py | cache_subnet_group_absent | def cache_subnet_group_absent(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Ensure a given cache subnet group is deleted.
name
Name of the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
exists = __salt__['boto3_elasticache.'
'cache_subnet_group_exists'](name, region=region, key=key,
keyid=keyid, profile=profile)
if exists:
if __opts__['test']:
ret['comment'] = 'Cache subnet group {0} would be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto3_elasticache.'
'delete_cache_subnet_group'](name, region=region, key=key,
keyid=keyid, profile=profile, **args)
if deleted:
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} cache_subnet group.'.format(name)
else:
ret['comment'] = 'Cache subnet group {0} already absent.'.format(name)
return ret | python | def cache_subnet_group_absent(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Ensure a given cache subnet group is deleted.
name
Name of the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
exists = __salt__['boto3_elasticache.'
'cache_subnet_group_exists'](name, region=region, key=key,
keyid=keyid, profile=profile)
if exists:
if __opts__['test']:
ret['comment'] = 'Cache subnet group {0} would be removed.'.format(name)
ret['result'] = None
return ret
deleted = __salt__['boto3_elasticache.'
'delete_cache_subnet_group'](name, region=region, key=key,
keyid=keyid, profile=profile, **args)
if deleted:
ret['changes']['old'] = name
ret['changes']['new'] = None
else:
ret['result'] = False
ret['comment'] = 'Failed to delete {0} cache_subnet group.'.format(name)
else:
ret['comment'] = 'Cache subnet group {0} already absent.'.format(name)
return ret | [
"def",
"cache_subnet_group_absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
... | Ensure a given cache subnet group is deleted.
name
Name of the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid. | [
"Ensure",
"a",
"given",
"cache",
"subnet",
"group",
"is",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L1104-L1149 | train |
saltstack/salt | salt/states/boto3_elasticache.py | cache_parameter_group_present | def cache_parameter_group_present(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Ensure cache parameter group exists.
name
A name for the cache parameter group.
CacheParameterGroupName
A name for the cache parameter group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
CacheParameterGroupFamily
The name of the cache parameter group family that the cache parameter group can be used with.
Valid values are:
- memcached1.4
- redis2.6
- redis2.8
- redis3.2
Description
A description for the cache parameter group.
ParameterNameValues
A newly created CacheParameterGroup is an exact duplicate of the default parameter group
of the requested CacheParameterGroupFamily. This option provides a way to fine-tune
these settings. It is formatted as [list] of {dicts}, each composed of a parameter name
and a value.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
tunables = args.pop('ParameterNameValues', None)
current = __salt__['boto3_elasticache.describe_cache_parameter_groups'](name, region=region,
key=key, keyid=keyid, profile=profile)
if not current:
if __opts__['test']:
ret['comment'] = 'Cache parameter group `{}` would be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto3_elasticache.create_cache_parameter_group'](name, region=region,
key=key, keyid=keyid, profile=profile, **args)
if not created:
ret['result'] = False
ret['comment'] = 'Failed to create cache parameter group `{}`.'.format(name)
return ret
new = __salt__['boto3_elasticache.describe_cache_parameter_groups'](name, region=region,
key=key, keyid=keyid, profile=profile)
new = new[0]
# Set any custom cache parameters requested...
if tunables:
kwargs = {'ParameterNameValues': tunables}
updated = __salt__['boto3_elasticache.modify_cache_parameter_groups'](name,
region=region, key=key, keyid=keyid, profile=profile, **kwargs)
if not updated:
ret['result'] = False
ret['comment'] = 'Failed to update new cache parameter group `{}`.'.format(name)
return ret
kwargs = {'Source': 'user'}
new['ParameterNameValues'] = __salt__['boto3_elasticache.describe_cache_parameters'](
name, region=region, key=key, keyid=keyid, profile=profile, **kwargs)
ret['comment'] = 'Cache parameter group `{}` was created.'.format(name)
ret['changes']['old'] = None
ret['changes']['new'] = new
else:
if not tunables:
ret['comment'] = 'Cache parameter group `{}` exists.'.format(name)
else:
oldvals = []
newvals = []
curr_params = __salt__['boto3_elasticache.describe_cache_parameters'](name,
region=region, key=key, keyid=keyid, profile=profile)
# Note that the items under CacheNodeTypeSpecificParameters are never modifiable, so
# we ignore them completely.
curr_kvs = {p['ParameterName']: p['ParameterValue'] for p in curr_params['Parameters']}
req_kvs = {p['ParameterName']: p['ParameterValue'] for p in tunables}
for pname, pval in req_kvs.items():
if pname in curr_kvs and pval != curr_kvs[pname]:
oldvals += [{'ParameterName': pname, 'ParameterValue': curr_kvs[pname]}]
newvals += [{'ParameterName': pname, 'ParameterValue': pval}]
if newvals:
if __opts__['test']:
ret['comment'] = 'Cache parameter group `{}` would be updated.'.format(name)
ret['result'] = None
ret['changes']['old'] = current[0]
ret['changes']['old']['ParameterNameValues'] = oldvals
ret['changes']['new'] = deepcopy(current[0])
ret['changes']['new']['ParameterNameValues'] = newvals
return ret
kwargs = {'ParameterNameValues': newvals}
if not __salt__['boto3_elasticache.modify_cache_parameter_groups'](name,
region=region, key=key, keyid=keyid, profile=profile, **kwargs):
ret['result'] = False
ret['comment'] = 'Failed to update cache parameter group `{}`.'.format(name)
return ret
ret['changes']['old'] = current[0]
ret['changes']['old']['ParameterNameValues'] = oldvals
ret['changes']['new'] = deepcopy(current[0])
ret['changes']['new']['ParameterNameValues'] = newvals
else:
ret['comment'] = 'Cache parameter group `{}` is in the desired state.'.format(name)
return ret | python | def cache_parameter_group_present(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Ensure cache parameter group exists.
name
A name for the cache parameter group.
CacheParameterGroupName
A name for the cache parameter group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
CacheParameterGroupFamily
The name of the cache parameter group family that the cache parameter group can be used with.
Valid values are:
- memcached1.4
- redis2.6
- redis2.8
- redis3.2
Description
A description for the cache parameter group.
ParameterNameValues
A newly created CacheParameterGroup is an exact duplicate of the default parameter group
of the requested CacheParameterGroupFamily. This option provides a way to fine-tune
these settings. It is formatted as [list] of {dicts}, each composed of a parameter name
and a value.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
args = dict([(k, v) for k, v in args.items() if not k.startswith('_')])
tunables = args.pop('ParameterNameValues', None)
current = __salt__['boto3_elasticache.describe_cache_parameter_groups'](name, region=region,
key=key, keyid=keyid, profile=profile)
if not current:
if __opts__['test']:
ret['comment'] = 'Cache parameter group `{}` would be created.'.format(name)
ret['result'] = None
return ret
created = __salt__['boto3_elasticache.create_cache_parameter_group'](name, region=region,
key=key, keyid=keyid, profile=profile, **args)
if not created:
ret['result'] = False
ret['comment'] = 'Failed to create cache parameter group `{}`.'.format(name)
return ret
new = __salt__['boto3_elasticache.describe_cache_parameter_groups'](name, region=region,
key=key, keyid=keyid, profile=profile)
new = new[0]
# Set any custom cache parameters requested...
if tunables:
kwargs = {'ParameterNameValues': tunables}
updated = __salt__['boto3_elasticache.modify_cache_parameter_groups'](name,
region=region, key=key, keyid=keyid, profile=profile, **kwargs)
if not updated:
ret['result'] = False
ret['comment'] = 'Failed to update new cache parameter group `{}`.'.format(name)
return ret
kwargs = {'Source': 'user'}
new['ParameterNameValues'] = __salt__['boto3_elasticache.describe_cache_parameters'](
name, region=region, key=key, keyid=keyid, profile=profile, **kwargs)
ret['comment'] = 'Cache parameter group `{}` was created.'.format(name)
ret['changes']['old'] = None
ret['changes']['new'] = new
else:
if not tunables:
ret['comment'] = 'Cache parameter group `{}` exists.'.format(name)
else:
oldvals = []
newvals = []
curr_params = __salt__['boto3_elasticache.describe_cache_parameters'](name,
region=region, key=key, keyid=keyid, profile=profile)
# Note that the items under CacheNodeTypeSpecificParameters are never modifiable, so
# we ignore them completely.
curr_kvs = {p['ParameterName']: p['ParameterValue'] for p in curr_params['Parameters']}
req_kvs = {p['ParameterName']: p['ParameterValue'] for p in tunables}
for pname, pval in req_kvs.items():
if pname in curr_kvs and pval != curr_kvs[pname]:
oldvals += [{'ParameterName': pname, 'ParameterValue': curr_kvs[pname]}]
newvals += [{'ParameterName': pname, 'ParameterValue': pval}]
if newvals:
if __opts__['test']:
ret['comment'] = 'Cache parameter group `{}` would be updated.'.format(name)
ret['result'] = None
ret['changes']['old'] = current[0]
ret['changes']['old']['ParameterNameValues'] = oldvals
ret['changes']['new'] = deepcopy(current[0])
ret['changes']['new']['ParameterNameValues'] = newvals
return ret
kwargs = {'ParameterNameValues': newvals}
if not __salt__['boto3_elasticache.modify_cache_parameter_groups'](name,
region=region, key=key, keyid=keyid, profile=profile, **kwargs):
ret['result'] = False
ret['comment'] = 'Failed to update cache parameter group `{}`.'.format(name)
return ret
ret['changes']['old'] = current[0]
ret['changes']['old']['ParameterNameValues'] = oldvals
ret['changes']['new'] = deepcopy(current[0])
ret['changes']['new']['ParameterNameValues'] = newvals
else:
ret['comment'] = 'Cache parameter group `{}` is in the desired state.'.format(name)
return ret | [
"def",
"cache_parameter_group_present",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'"... | Ensure cache parameter group exists.
name
A name for the cache parameter group.
CacheParameterGroupName
A name for the cache parameter group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
CacheParameterGroupFamily
The name of the cache parameter group family that the cache parameter group can be used with.
Valid values are:
- memcached1.4
- redis2.6
- redis2.8
- redis3.2
Description
A description for the cache parameter group.
ParameterNameValues
A newly created CacheParameterGroup is an exact duplicate of the default parameter group
of the requested CacheParameterGroupFamily. This option provides a way to fine-tune
these settings. It is formatted as [list] of {dicts}, each composed of a parameter name
and a value.
.. code-block:: yaml
ParameterNameValues:
- ParameterName: timeout
# Amazon requires ALL VALUES to be strings...
ParameterValue: "30"
- ParameterName: appendonly
# The YAML parser will turn a bare `yes` into a bool, which Amazon will then throw on...
ParameterValue: "yes"
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyid. | [
"Ensure",
"cache",
"parameter",
"group",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto3_elasticache.py#L1152-L1277 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | _find_identity_pool_ids | def _find_identity_pool_ids(name, pool_id, conn):
'''
Given identity pool name (or optionally a pool_id and name will be ignored),
find and return list of matching identity pool id's.
'''
ids = []
if pool_id is None:
for pools in __utils__['boto3.paged_call'](conn.list_identity_pools,
marker_flag='NextToken', marker_arg='NextToken', MaxResults=25):
for pool in pools['IdentityPools']:
if pool['IdentityPoolName'] == name:
ids.append(pool['IdentityPoolId'])
else:
ids.append(pool_id)
return ids | python | def _find_identity_pool_ids(name, pool_id, conn):
'''
Given identity pool name (or optionally a pool_id and name will be ignored),
find and return list of matching identity pool id's.
'''
ids = []
if pool_id is None:
for pools in __utils__['boto3.paged_call'](conn.list_identity_pools,
marker_flag='NextToken', marker_arg='NextToken', MaxResults=25):
for pool in pools['IdentityPools']:
if pool['IdentityPoolName'] == name:
ids.append(pool['IdentityPoolId'])
else:
ids.append(pool_id)
return ids | [
"def",
"_find_identity_pool_ids",
"(",
"name",
",",
"pool_id",
",",
"conn",
")",
":",
"ids",
"=",
"[",
"]",
"if",
"pool_id",
"is",
"None",
":",
"for",
"pools",
"in",
"__utils__",
"[",
"'boto3.paged_call'",
"]",
"(",
"conn",
".",
"list_identity_pools",
",",... | Given identity pool name (or optionally a pool_id and name will be ignored),
find and return list of matching identity pool id's. | [
"Given",
"identity",
"pool",
"name",
"(",
"or",
"optionally",
"a",
"pool_id",
"and",
"name",
"will",
"be",
"ignored",
")",
"find",
"and",
"return",
"list",
"of",
"matching",
"identity",
"pool",
"id",
"s",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L126-L141 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | describe_identity_pools | def describe_identity_pools(IdentityPoolName, IdentityPoolId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Returns a list of matched identity pool name's pool properties
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.describe_identity_pools my_id_pool_name
salt myminion boto_cognitoidentity.describe_identity_pools '' IdentityPoolId=my_id_pool_id
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ids = _find_identity_pool_ids(IdentityPoolName, IdentityPoolId, conn)
if ids:
results = []
for pool_id in ids:
response = conn.describe_identity_pool(IdentityPoolId=pool_id)
response.pop('ResponseMetadata', None)
results.append(response)
return {'identity_pools': results}
else:
return {'identity_pools': None}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def describe_identity_pools(IdentityPoolName, IdentityPoolId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Returns a list of matched identity pool name's pool properties
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.describe_identity_pools my_id_pool_name
salt myminion boto_cognitoidentity.describe_identity_pools '' IdentityPoolId=my_id_pool_id
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ids = _find_identity_pool_ids(IdentityPoolName, IdentityPoolId, conn)
if ids:
results = []
for pool_id in ids:
response = conn.describe_identity_pool(IdentityPoolId=pool_id)
response.pop('ResponseMetadata', None)
results.append(response)
return {'identity_pools': results}
else:
return {'identity_pools': None}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe_identity_pools",
"(",
"IdentityPoolName",
",",
"IdentityPoolId",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
... | Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Returns a list of matched identity pool name's pool properties
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.describe_identity_pools my_id_pool_name
salt myminion boto_cognitoidentity.describe_identity_pools '' IdentityPoolId=my_id_pool_id | [
"Given",
"an",
"identity",
"pool",
"name",
"(",
"optionally",
"if",
"an",
"identity",
"pool",
"id",
"is",
"given",
"the",
"given",
"name",
"will",
"be",
"ignored",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L144-L176 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | create_identity_pool | def create_identity_pool(IdentityPoolName,
AllowUnauthenticatedIdentities=False,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, keyid=None, profile=None):
'''
Creates a new identity pool. All parameters except for IdentityPoolName is optional.
SupportedLoginProviders should be a dictionary mapping provider names to provider app
IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider ARNs.
Returns the created identity pool if successful
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.create_identity_pool my_id_pool_name \
DeveloperProviderName=custom_developer_provider
'''
SupportedLoginProviders = dict() if SupportedLoginProviders is None else SupportedLoginProviders
OpenIdConnectProviderARNs = list() if OpenIdConnectProviderARNs is None else OpenIdConnectProviderARNs
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
request_params = dict(IdentityPoolName=IdentityPoolName,
AllowUnauthenticatedIdentities=AllowUnauthenticatedIdentities,
SupportedLoginProviders=SupportedLoginProviders,
OpenIdConnectProviderARNs=OpenIdConnectProviderARNs)
if DeveloperProviderName:
request_params['DeveloperProviderName'] = DeveloperProviderName
response = conn.create_identity_pool(**request_params)
response.pop('ResponseMetadata', None)
return {'created': True, 'identity_pool': response}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | python | def create_identity_pool(IdentityPoolName,
AllowUnauthenticatedIdentities=False,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, keyid=None, profile=None):
'''
Creates a new identity pool. All parameters except for IdentityPoolName is optional.
SupportedLoginProviders should be a dictionary mapping provider names to provider app
IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider ARNs.
Returns the created identity pool if successful
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.create_identity_pool my_id_pool_name \
DeveloperProviderName=custom_developer_provider
'''
SupportedLoginProviders = dict() if SupportedLoginProviders is None else SupportedLoginProviders
OpenIdConnectProviderARNs = list() if OpenIdConnectProviderARNs is None else OpenIdConnectProviderARNs
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
request_params = dict(IdentityPoolName=IdentityPoolName,
AllowUnauthenticatedIdentities=AllowUnauthenticatedIdentities,
SupportedLoginProviders=SupportedLoginProviders,
OpenIdConnectProviderARNs=OpenIdConnectProviderARNs)
if DeveloperProviderName:
request_params['DeveloperProviderName'] = DeveloperProviderName
response = conn.create_identity_pool(**request_params)
response.pop('ResponseMetadata', None)
return {'created': True, 'identity_pool': response}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_identity_pool",
"(",
"IdentityPoolName",
",",
"AllowUnauthenticatedIdentities",
"=",
"False",
",",
"SupportedLoginProviders",
"=",
"None",
",",
"DeveloperProviderName",
"=",
"None",
",",
"OpenIdConnectProviderARNs",
"=",
"None",
",",
"region",
"=",
"None"... | Creates a new identity pool. All parameters except for IdentityPoolName is optional.
SupportedLoginProviders should be a dictionary mapping provider names to provider app
IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider ARNs.
Returns the created identity pool if successful
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.create_identity_pool my_id_pool_name \
DeveloperProviderName=custom_developer_provider | [
"Creates",
"a",
"new",
"identity",
"pool",
".",
"All",
"parameters",
"except",
"for",
"IdentityPoolName",
"is",
"optional",
".",
"SupportedLoginProviders",
"should",
"be",
"a",
"dictionary",
"mapping",
"provider",
"names",
"to",
"provider",
"app",
"IDs",
".",
"O... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L179-L218 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | delete_identity_pools | def delete_identity_pools(IdentityPoolName, IdentityPoolId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Deletes all identity pools matching the given name, or the specific identity pool with
the given identity pool id.
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.delete_identity_pools my_id_pool_name
salt myminion boto_cognitoidentity.delete_identity_pools '' IdentityPoolId=my_id_pool_id
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ids = _find_identity_pool_ids(IdentityPoolName, IdentityPoolId, conn)
count = 0
if ids:
for pool_id in ids:
conn.delete_identity_pool(IdentityPoolId=pool_id)
count += 1
return {'deleted': True, 'count': count}
else:
return {'deleted': False, 'count': count}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_identity_pools(IdentityPoolName, IdentityPoolId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Deletes all identity pools matching the given name, or the specific identity pool with
the given identity pool id.
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.delete_identity_pools my_id_pool_name
salt myminion boto_cognitoidentity.delete_identity_pools '' IdentityPoolId=my_id_pool_id
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
ids = _find_identity_pool_ids(IdentityPoolName, IdentityPoolId, conn)
count = 0
if ids:
for pool_id in ids:
conn.delete_identity_pool(IdentityPoolId=pool_id)
count += 1
return {'deleted': True, 'count': count}
else:
return {'deleted': False, 'count': count}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_identity_pools",
"(",
"IdentityPoolName",
",",
"IdentityPoolId",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"... | Given an identity pool name, (optionally if an identity pool id is given,
the given name will be ignored)
Deletes all identity pools matching the given name, or the specific identity pool with
the given identity pool id.
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.delete_identity_pools my_id_pool_name
salt myminion boto_cognitoidentity.delete_identity_pools '' IdentityPoolId=my_id_pool_id | [
"Given",
"an",
"identity",
"pool",
"name",
"(",
"optionally",
"if",
"an",
"identity",
"pool",
"id",
"is",
"given",
"the",
"given",
"name",
"will",
"be",
"ignored",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L221-L252 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | _get_role_arn | def _get_role_arn(name, **conn_params):
'''
Helper function to turn a name into an arn string,
returns None if not able to resolve
'''
if name.startswith('arn:aws:iam'):
return name
role = __salt__['boto_iam.describe_role'](name, **conn_params)
rolearn = role.get('arn') if role else None
return rolearn | python | def _get_role_arn(name, **conn_params):
'''
Helper function to turn a name into an arn string,
returns None if not able to resolve
'''
if name.startswith('arn:aws:iam'):
return name
role = __salt__['boto_iam.describe_role'](name, **conn_params)
rolearn = role.get('arn') if role else None
return rolearn | [
"def",
"_get_role_arn",
"(",
"name",
",",
"*",
"*",
"conn_params",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'arn:aws:iam'",
")",
":",
"return",
"name",
"role",
"=",
"__salt__",
"[",
"'boto_iam.describe_role'",
"]",
"(",
"name",
",",
"*",
"*",
"co... | Helper function to turn a name into an arn string,
returns None if not able to resolve | [
"Helper",
"function",
"to",
"turn",
"a",
"name",
"into",
"an",
"arn",
"string",
"returns",
"None",
"if",
"not",
"able",
"to",
"resolve"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L289-L299 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | set_identity_pool_roles | def set_identity_pool_roles(IdentityPoolId, AuthenticatedRole=None, UnauthenticatedRole=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) If AuthenticatedRole or UnauthenticatedRole is not given,
the authenticated and/or the unauthenticated role associated previously with the pool will be
cleared.
Returns set True if successful, set False if unsuccessful with the associated errors.
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_roles # this clears the roles
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
AuthenticatedRole=my_auth_role UnauthenticatedRole=my_unauth_role # this set both roles
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
AuthenticatedRole=my_auth_role # this will set the auth role and clear the unauth role
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
UnauthenticatedRole=my_unauth_role # this will set the unauth role and clear the auth role
'''
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
conn = _get_conn(**conn_params)
try:
if AuthenticatedRole:
role_arn = _get_role_arn(AuthenticatedRole, **conn_params)
if role_arn is None:
return {'set': False, 'error': 'invalid AuthenticatedRole {0}'.format(AuthenticatedRole)}
AuthenticatedRole = role_arn
if UnauthenticatedRole:
role_arn = _get_role_arn(UnauthenticatedRole, **conn_params)
if role_arn is None:
return {'set': False, 'error': 'invalid UnauthenticatedRole {0}'.format(UnauthenticatedRole)}
UnauthenticatedRole = role_arn
Roles = dict()
if AuthenticatedRole:
Roles['authenticated'] = AuthenticatedRole
if UnauthenticatedRole:
Roles['unauthenticated'] = UnauthenticatedRole
conn.set_identity_pool_roles(IdentityPoolId=IdentityPoolId, Roles=Roles)
return {'set': True, 'roles': Roles}
except ClientError as e:
return {'set': False, 'error': __utils__['boto3.get_error'](e)} | python | def set_identity_pool_roles(IdentityPoolId, AuthenticatedRole=None, UnauthenticatedRole=None,
region=None, key=None, keyid=None, profile=None):
'''
Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) If AuthenticatedRole or UnauthenticatedRole is not given,
the authenticated and/or the unauthenticated role associated previously with the pool will be
cleared.
Returns set True if successful, set False if unsuccessful with the associated errors.
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_roles # this clears the roles
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
AuthenticatedRole=my_auth_role UnauthenticatedRole=my_unauth_role # this set both roles
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
AuthenticatedRole=my_auth_role # this will set the auth role and clear the unauth role
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
UnauthenticatedRole=my_unauth_role # this will set the unauth role and clear the auth role
'''
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
conn = _get_conn(**conn_params)
try:
if AuthenticatedRole:
role_arn = _get_role_arn(AuthenticatedRole, **conn_params)
if role_arn is None:
return {'set': False, 'error': 'invalid AuthenticatedRole {0}'.format(AuthenticatedRole)}
AuthenticatedRole = role_arn
if UnauthenticatedRole:
role_arn = _get_role_arn(UnauthenticatedRole, **conn_params)
if role_arn is None:
return {'set': False, 'error': 'invalid UnauthenticatedRole {0}'.format(UnauthenticatedRole)}
UnauthenticatedRole = role_arn
Roles = dict()
if AuthenticatedRole:
Roles['authenticated'] = AuthenticatedRole
if UnauthenticatedRole:
Roles['unauthenticated'] = UnauthenticatedRole
conn.set_identity_pool_roles(IdentityPoolId=IdentityPoolId, Roles=Roles)
return {'set': True, 'roles': Roles}
except ClientError as e:
return {'set': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"set_identity_pool_roles",
"(",
"IdentityPoolId",
",",
"AuthenticatedRole",
"=",
"None",
",",
"UnauthenticatedRole",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
... | Given an identity pool id, set the given AuthenticatedRole and UnauthenticatedRole (the Role
can be an iam arn, or a role name) If AuthenticatedRole or UnauthenticatedRole is not given,
the authenticated and/or the unauthenticated role associated previously with the pool will be
cleared.
Returns set True if successful, set False if unsuccessful with the associated errors.
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_roles # this clears the roles
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
AuthenticatedRole=my_auth_role UnauthenticatedRole=my_unauth_role # this set both roles
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
AuthenticatedRole=my_auth_role # this will set the auth role and clear the unauth role
salt myminion boto_cognitoidentity.set_identity_pool_roles my_id_pool_id \
UnauthenticatedRole=my_unauth_role # this will set the unauth role and clear the auth role | [
"Given",
"an",
"identity",
"pool",
"id",
"set",
"the",
"given",
"AuthenticatedRole",
"and",
"UnauthenticatedRole",
"(",
"the",
"Role",
"can",
"be",
"an",
"iam",
"arn",
"or",
"a",
"role",
"name",
")",
"If",
"AuthenticatedRole",
"or",
"UnauthenticatedRole",
"is"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L302-L351 | train |
saltstack/salt | salt/modules/boto_cognitoidentity.py | update_identity_pool | def update_identity_pool(IdentityPoolId,
IdentityPoolName=None,
AllowUnauthenticatedIdentities=False,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, keyid=None, profile=None):
'''
Updates the given IdentityPoolId's properties. All parameters except for IdentityPoolId,
is optional. SupportedLoginProviders should be a dictionary mapping provider names to
provider app IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider
ARNs.
To clear SupportedLoginProviders pass '{}'
To clear OpenIdConnectProviderARNs pass '[]'
boto3 api prevents DeveloperProviderName to be updated after it has been set for the first time.
Returns the updated identity pool if successful
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.update_identity_pool my_id_pool_id my_id_pool_name \
DeveloperProviderName=custom_developer_provider
'''
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
response = describe_identity_pools('', IdentityPoolId=IdentityPoolId, **conn_params)
error = response.get('error')
if error is None:
error = 'No matching pool' if response.get('identity_pools') is None else None
if error:
return {'updated': False, 'error': error}
id_pool = response.get('identity_pools')[0]
request_params = id_pool.copy()
# IdentityPoolName and AllowUnauthenticatedIdentities are required for the call to update_identity_pool
if IdentityPoolName is not None and IdentityPoolName != request_params.get('IdentityPoolName'):
request_params['IdentityPoolName'] = IdentityPoolName
if AllowUnauthenticatedIdentities != request_params.get('AllowUnauthenticatedIdentities'):
request_params['AllowUnauthenticatedIdentities'] = AllowUnauthenticatedIdentities
current_val = request_params.pop('SupportedLoginProviders', None)
if SupportedLoginProviders is not None and SupportedLoginProviders != current_val:
request_params['SupportedLoginProviders'] = SupportedLoginProviders
# we can only set DeveloperProviderName one time per AWS.
current_val = request_params.pop('DeveloperProviderName', None)
if current_val is None and DeveloperProviderName is not None:
request_params['DeveloperProviderName'] = DeveloperProviderName
current_val = request_params.pop('OpenIdConnectProviderARNs', None)
if OpenIdConnectProviderARNs is not None and OpenIdConnectProviderARNs != current_val:
request_params['OpenIdConnectProviderARNs'] = OpenIdConnectProviderARNs
conn = _get_conn(**conn_params)
try:
response = conn.update_identity_pool(**request_params)
response.pop('ResponseMetadata', None)
return {'updated': True, 'identity_pool': response}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def update_identity_pool(IdentityPoolId,
IdentityPoolName=None,
AllowUnauthenticatedIdentities=False,
SupportedLoginProviders=None,
DeveloperProviderName=None,
OpenIdConnectProviderARNs=None,
region=None, key=None, keyid=None, profile=None):
'''
Updates the given IdentityPoolId's properties. All parameters except for IdentityPoolId,
is optional. SupportedLoginProviders should be a dictionary mapping provider names to
provider app IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider
ARNs.
To clear SupportedLoginProviders pass '{}'
To clear OpenIdConnectProviderARNs pass '[]'
boto3 api prevents DeveloperProviderName to be updated after it has been set for the first time.
Returns the updated identity pool if successful
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.update_identity_pool my_id_pool_id my_id_pool_name \
DeveloperProviderName=custom_developer_provider
'''
conn_params = dict(region=region, key=key, keyid=keyid, profile=profile)
response = describe_identity_pools('', IdentityPoolId=IdentityPoolId, **conn_params)
error = response.get('error')
if error is None:
error = 'No matching pool' if response.get('identity_pools') is None else None
if error:
return {'updated': False, 'error': error}
id_pool = response.get('identity_pools')[0]
request_params = id_pool.copy()
# IdentityPoolName and AllowUnauthenticatedIdentities are required for the call to update_identity_pool
if IdentityPoolName is not None and IdentityPoolName != request_params.get('IdentityPoolName'):
request_params['IdentityPoolName'] = IdentityPoolName
if AllowUnauthenticatedIdentities != request_params.get('AllowUnauthenticatedIdentities'):
request_params['AllowUnauthenticatedIdentities'] = AllowUnauthenticatedIdentities
current_val = request_params.pop('SupportedLoginProviders', None)
if SupportedLoginProviders is not None and SupportedLoginProviders != current_val:
request_params['SupportedLoginProviders'] = SupportedLoginProviders
# we can only set DeveloperProviderName one time per AWS.
current_val = request_params.pop('DeveloperProviderName', None)
if current_val is None and DeveloperProviderName is not None:
request_params['DeveloperProviderName'] = DeveloperProviderName
current_val = request_params.pop('OpenIdConnectProviderARNs', None)
if OpenIdConnectProviderARNs is not None and OpenIdConnectProviderARNs != current_val:
request_params['OpenIdConnectProviderARNs'] = OpenIdConnectProviderARNs
conn = _get_conn(**conn_params)
try:
response = conn.update_identity_pool(**request_params)
response.pop('ResponseMetadata', None)
return {'updated': True, 'identity_pool': response}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"update_identity_pool",
"(",
"IdentityPoolId",
",",
"IdentityPoolName",
"=",
"None",
",",
"AllowUnauthenticatedIdentities",
"=",
"False",
",",
"SupportedLoginProviders",
"=",
"None",
",",
"DeveloperProviderName",
"=",
"None",
",",
"OpenIdConnectProviderARNs",
"=",
... | Updates the given IdentityPoolId's properties. All parameters except for IdentityPoolId,
is optional. SupportedLoginProviders should be a dictionary mapping provider names to
provider app IDs. OpenIdConnectProviderARNs should be a list of OpenID Connect provider
ARNs.
To clear SupportedLoginProviders pass '{}'
To clear OpenIdConnectProviderARNs pass '[]'
boto3 api prevents DeveloperProviderName to be updated after it has been set for the first time.
Returns the updated identity pool if successful
CLI Example:
.. code-block:: bash
salt myminion boto_cognitoidentity.update_identity_pool my_id_pool_id my_id_pool_name \
DeveloperProviderName=custom_developer_provider | [
"Updates",
"the",
"given",
"IdentityPoolId",
"s",
"properties",
".",
"All",
"parameters",
"except",
"for",
"IdentityPoolId",
"is",
"optional",
".",
"SupportedLoginProviders",
"should",
"be",
"a",
"dictionary",
"mapping",
"provider",
"names",
"to",
"provider",
"app",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cognitoidentity.py#L354-L422 | train |
saltstack/salt | salt/modules/state.py | _filter_running | def _filter_running(runnings):
'''
Filter out the result: True + no changes data
'''
ret = dict((tag, value) for tag, value in six.iteritems(runnings)
if not value['result'] or value['changes'])
return ret | python | def _filter_running(runnings):
'''
Filter out the result: True + no changes data
'''
ret = dict((tag, value) for tag, value in six.iteritems(runnings)
if not value['result'] or value['changes'])
return ret | [
"def",
"_filter_running",
"(",
"runnings",
")",
":",
"ret",
"=",
"dict",
"(",
"(",
"tag",
",",
"value",
")",
"for",
"tag",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"runnings",
")",
"if",
"not",
"value",
"[",
"'result'",
"]",
"or",
"value",
... | Filter out the result: True + no changes data | [
"Filter",
"out",
"the",
"result",
":",
"True",
"+",
"no",
"changes",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L87-L93 | train |
saltstack/salt | salt/modules/state.py | _set_retcode | def _set_retcode(ret, highstate=None):
'''
Set the return code based on the data back from the state system
'''
# Set default retcode to 0
__context__['retcode'] = salt.defaults.exitcodes.EX_OK
if isinstance(ret, list):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return
if not __utils__['state.check_result'](ret, highstate=highstate):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_FAILURE | python | def _set_retcode(ret, highstate=None):
'''
Set the return code based on the data back from the state system
'''
# Set default retcode to 0
__context__['retcode'] = salt.defaults.exitcodes.EX_OK
if isinstance(ret, list):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return
if not __utils__['state.check_result'](ret, highstate=highstate):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_FAILURE | [
"def",
"_set_retcode",
"(",
"ret",
",",
"highstate",
"=",
"None",
")",
":",
"# Set default retcode to 0",
"__context__",
"[",
"'retcode'",
"]",
"=",
"salt",
".",
"defaults",
".",
"exitcodes",
".",
"EX_OK",
"if",
"isinstance",
"(",
"ret",
",",
"list",
")",
... | Set the return code based on the data back from the state system | [
"Set",
"the",
"return",
"code",
"based",
"on",
"the",
"data",
"back",
"from",
"the",
"state",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L96-L108 | train |
saltstack/salt | salt/modules/state.py | _snapper_pre | def _snapper_pre(opts, jid):
'''
Create a snapper pre snapshot
'''
snapper_pre = None
try:
if not opts['test'] and __opts__.get('snapper_states'):
# Run the snapper pre snapshot
snapper_pre = __salt__['snapper.create_snapshot'](
config=__opts__.get('snapper_states_config', 'root'),
snapshot_type='pre',
description='Salt State run for jid {0}'.format(jid),
__pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: %s', jid)
return snapper_pre | python | def _snapper_pre(opts, jid):
'''
Create a snapper pre snapshot
'''
snapper_pre = None
try:
if not opts['test'] and __opts__.get('snapper_states'):
# Run the snapper pre snapshot
snapper_pre = __salt__['snapper.create_snapshot'](
config=__opts__.get('snapper_states_config', 'root'),
snapshot_type='pre',
description='Salt State run for jid {0}'.format(jid),
__pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: %s', jid)
return snapper_pre | [
"def",
"_snapper_pre",
"(",
"opts",
",",
"jid",
")",
":",
"snapper_pre",
"=",
"None",
"try",
":",
"if",
"not",
"opts",
"[",
"'test'",
"]",
"and",
"__opts__",
".",
"get",
"(",
"'snapper_states'",
")",
":",
"# Run the snapper pre snapshot",
"snapper_pre",
"=",... | Create a snapper pre snapshot | [
"Create",
"a",
"snapper",
"pre",
"snapshot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L135-L150 | train |
saltstack/salt | salt/modules/state.py | _snapper_post | def _snapper_post(opts, jid, pre_num):
'''
Create the post states snapshot
'''
try:
if not opts['test'] and __opts__.get('snapper_states') and pre_num:
# Run the snapper pre snapshot
__salt__['snapper.create_snapshot'](
config=__opts__.get('snapper_states_config', 'root'),
snapshot_type='post',
pre_number=pre_num,
description='Salt State run for jid {0}'.format(jid),
__pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: %s', jid) | python | def _snapper_post(opts, jid, pre_num):
'''
Create the post states snapshot
'''
try:
if not opts['test'] and __opts__.get('snapper_states') and pre_num:
# Run the snapper pre snapshot
__salt__['snapper.create_snapshot'](
config=__opts__.get('snapper_states_config', 'root'),
snapshot_type='post',
pre_number=pre_num,
description='Salt State run for jid {0}'.format(jid),
__pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: %s', jid) | [
"def",
"_snapper_post",
"(",
"opts",
",",
"jid",
",",
"pre_num",
")",
":",
"try",
":",
"if",
"not",
"opts",
"[",
"'test'",
"]",
"and",
"__opts__",
".",
"get",
"(",
"'snapper_states'",
")",
"and",
"pre_num",
":",
"# Run the snapper pre snapshot",
"__salt__",
... | Create the post states snapshot | [
"Create",
"the",
"post",
"states",
"snapshot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L153-L167 | train |
saltstack/salt | salt/modules/state.py | _get_pause | def _get_pause(jid, state_id=None):
'''
Return the pause information for a given jid
'''
pause_dir = os.path.join(__opts__['cachedir'], 'state_pause')
pause_path = os.path.join(pause_dir, jid)
if not os.path.exists(pause_dir):
try:
os.makedirs(pause_dir)
except OSError:
# File created in the gap
pass
data = {}
if state_id is not None:
if state_id not in data:
data[state_id] = {}
if os.path.exists(pause_path):
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
data = salt.utils.msgpack.loads(fp_.read())
return data, pause_path | python | def _get_pause(jid, state_id=None):
'''
Return the pause information for a given jid
'''
pause_dir = os.path.join(__opts__['cachedir'], 'state_pause')
pause_path = os.path.join(pause_dir, jid)
if not os.path.exists(pause_dir):
try:
os.makedirs(pause_dir)
except OSError:
# File created in the gap
pass
data = {}
if state_id is not None:
if state_id not in data:
data[state_id] = {}
if os.path.exists(pause_path):
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
data = salt.utils.msgpack.loads(fp_.read())
return data, pause_path | [
"def",
"_get_pause",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"pause_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'state_pause'",
")",
"pause_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pa... | Return the pause information for a given jid | [
"Return",
"the",
"pause",
"information",
"for",
"a",
"given",
"jid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L170-L189 | train |
saltstack/salt | salt/modules/state.py | get_pauses | def get_pauses(jid=None):
'''
Get a report on all of the currently paused state runs and pause
run settings.
Optionally send in a jid if you only desire to see a single pause
data set.
'''
ret = {}
active = __salt__['saltutil.is_running']('state.*')
pause_dir = os.path.join(__opts__['cachedir'], 'state_pause')
if not os.path.exists(pause_dir):
return ret
if jid is None:
jids = os.listdir(pause_dir)
elif isinstance(jid, list):
jids = salt.utils.data.stringify(jid)
else:
jids = [six.text_type(jid)]
for scan_jid in jids:
is_active = False
for active_data in active:
if active_data['jid'] == scan_jid:
is_active = True
if not is_active:
try:
pause_path = os.path.join(pause_dir, scan_jid)
os.remove(pause_path)
except OSError:
# Already gone
pass
continue
data, pause_path = _get_pause(scan_jid)
ret[scan_jid] = data
return ret | python | def get_pauses(jid=None):
'''
Get a report on all of the currently paused state runs and pause
run settings.
Optionally send in a jid if you only desire to see a single pause
data set.
'''
ret = {}
active = __salt__['saltutil.is_running']('state.*')
pause_dir = os.path.join(__opts__['cachedir'], 'state_pause')
if not os.path.exists(pause_dir):
return ret
if jid is None:
jids = os.listdir(pause_dir)
elif isinstance(jid, list):
jids = salt.utils.data.stringify(jid)
else:
jids = [six.text_type(jid)]
for scan_jid in jids:
is_active = False
for active_data in active:
if active_data['jid'] == scan_jid:
is_active = True
if not is_active:
try:
pause_path = os.path.join(pause_dir, scan_jid)
os.remove(pause_path)
except OSError:
# Already gone
pass
continue
data, pause_path = _get_pause(scan_jid)
ret[scan_jid] = data
return ret | [
"def",
"get_pauses",
"(",
"jid",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"active",
"=",
"__salt__",
"[",
"'saltutil.is_running'",
"]",
"(",
"'state.*'",
")",
"pause_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]"... | Get a report on all of the currently paused state runs and pause
run settings.
Optionally send in a jid if you only desire to see a single pause
data set. | [
"Get",
"a",
"report",
"on",
"all",
"of",
"the",
"currently",
"paused",
"state",
"runs",
"and",
"pause",
"run",
"settings",
".",
"Optionally",
"send",
"in",
"a",
"jid",
"if",
"you",
"only",
"desire",
"to",
"see",
"a",
"single",
"pause",
"data",
"set",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L192-L225 | train |
saltstack/salt | salt/modules/state.py | soft_kill | def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run.
The given state id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `soft_kill` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.soft_kill 20171130110407769519
salt '*' state.soft_kill 20171130110407769519 vim
'''
jid = six.text_type(jid)
if state_id is None:
state_id = '__all__'
data, pause_path = _get_pause(jid, state_id)
data[state_id]['kill'] = True
with salt.utils.files.fopen(pause_path, 'wb') as fp_:
fp_.write(salt.utils.msgpack.dumps(data)) | python | def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run.
The given state id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `soft_kill` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.soft_kill 20171130110407769519
salt '*' state.soft_kill 20171130110407769519 vim
'''
jid = six.text_type(jid)
if state_id is None:
state_id = '__all__'
data, pause_path = _get_pause(jid, state_id)
data[state_id]['kill'] = True
with salt.utils.files.fopen(pause_path, 'wb') as fp_:
fp_.write(salt.utils.msgpack.dumps(data)) | [
"def",
"soft_kill",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"jid",
"=",
"six",
".",
"text_type",
"(",
"jid",
")",
"if",
"state_id",
"is",
"None",
":",
"state_id",
"=",
"'__all__'",
"data",
",",
"pause_path",
"=",
"_get_pause",
"(",
"jid",
... | Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run.
The given state id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `soft_kill` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.soft_kill 20171130110407769519
salt '*' state.soft_kill 20171130110407769519 vim | [
"Set",
"up",
"a",
"state",
"run",
"to",
"die",
"before",
"executing",
"the",
"given",
"state",
"id",
"this",
"instructs",
"a",
"running",
"state",
"to",
"safely",
"exit",
"at",
"a",
"given",
"state",
"id",
".",
"This",
"needs",
"to",
"pass",
"in",
"the... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L228-L259 | train |
saltstack/salt | salt/modules/state.py | pause | def pause(jid, state_id=None, duration=None):
'''
Set up a state id pause, this instructs a running state to pause at a given
state id. This needs to pass in the jid of the running state and can
optionally pass in a duration in seconds. If a state_id is not passed then
the jid referenced will be paused at the beginning of the next state run.
The given state id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `pause` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.pause 20171130110407769519
salt '*' state.pause 20171130110407769519 vim
salt '*' state.pause 20171130110407769519 vim 20
'''
jid = six.text_type(jid)
if state_id is None:
state_id = '__all__'
data, pause_path = _get_pause(jid, state_id)
if duration:
data[state_id]['duration'] = int(duration)
with salt.utils.files.fopen(pause_path, 'wb') as fp_:
fp_.write(salt.utils.msgpack.dumps(data)) | python | def pause(jid, state_id=None, duration=None):
'''
Set up a state id pause, this instructs a running state to pause at a given
state id. This needs to pass in the jid of the running state and can
optionally pass in a duration in seconds. If a state_id is not passed then
the jid referenced will be paused at the beginning of the next state run.
The given state id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `pause` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.pause 20171130110407769519
salt '*' state.pause 20171130110407769519 vim
salt '*' state.pause 20171130110407769519 vim 20
'''
jid = six.text_type(jid)
if state_id is None:
state_id = '__all__'
data, pause_path = _get_pause(jid, state_id)
if duration:
data[state_id]['duration'] = int(duration)
with salt.utils.files.fopen(pause_path, 'wb') as fp_:
fp_.write(salt.utils.msgpack.dumps(data)) | [
"def",
"pause",
"(",
"jid",
",",
"state_id",
"=",
"None",
",",
"duration",
"=",
"None",
")",
":",
"jid",
"=",
"six",
".",
"text_type",
"(",
"jid",
")",
"if",
"state_id",
"is",
"None",
":",
"state_id",
"=",
"'__all__'",
"data",
",",
"pause_path",
"=",... | Set up a state id pause, this instructs a running state to pause at a given
state id. This needs to pass in the jid of the running state and can
optionally pass in a duration in seconds. If a state_id is not passed then
the jid referenced will be paused at the beginning of the next state run.
The given state id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `pause` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.pause 20171130110407769519
salt '*' state.pause 20171130110407769519 vim
salt '*' state.pause 20171130110407769519 vim 20 | [
"Set",
"up",
"a",
"state",
"id",
"pause",
"this",
"instructs",
"a",
"running",
"state",
"to",
"pause",
"at",
"a",
"given",
"state",
"id",
".",
"This",
"needs",
"to",
"pass",
"in",
"the",
"jid",
"of",
"the",
"running",
"state",
"and",
"can",
"optionally... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L262-L294 | train |
saltstack/salt | salt/modules/state.py | resume | def resume(jid, state_id=None):
'''
Remove a pause from a jid, allowing it to continue. If the state_id is
not specified then the a general pause will be resumed.
The given state_id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `rm_pause` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.resume 20171130110407769519
salt '*' state.resume 20171130110407769519 vim
'''
jid = six.text_type(jid)
if state_id is None:
state_id = '__all__'
data, pause_path = _get_pause(jid, state_id)
if state_id in data:
data.pop(state_id)
if state_id == '__all__':
data = {}
with salt.utils.files.fopen(pause_path, 'wb') as fp_:
fp_.write(salt.utils.msgpack.dumps(data)) | python | def resume(jid, state_id=None):
'''
Remove a pause from a jid, allowing it to continue. If the state_id is
not specified then the a general pause will be resumed.
The given state_id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `rm_pause` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.resume 20171130110407769519
salt '*' state.resume 20171130110407769519 vim
'''
jid = six.text_type(jid)
if state_id is None:
state_id = '__all__'
data, pause_path = _get_pause(jid, state_id)
if state_id in data:
data.pop(state_id)
if state_id == '__all__':
data = {}
with salt.utils.files.fopen(pause_path, 'wb') as fp_:
fp_.write(salt.utils.msgpack.dumps(data)) | [
"def",
"resume",
"(",
"jid",
",",
"state_id",
"=",
"None",
")",
":",
"jid",
"=",
"six",
".",
"text_type",
"(",
"jid",
")",
"if",
"state_id",
"is",
"None",
":",
"state_id",
"=",
"'__all__'",
"data",
",",
"pause_path",
"=",
"_get_pause",
"(",
"jid",
",... | Remove a pause from a jid, allowing it to continue. If the state_id is
not specified then the a general pause will be resumed.
The given state_id is the id got a given state execution, so given a state
that looks like this:
.. code-block:: yaml
vim:
pkg.installed: []
The state_id to pass to `rm_pause` is `vim`
CLI Examples:
.. code-block:: bash
salt '*' state.resume 20171130110407769519
salt '*' state.resume 20171130110407769519 vim | [
"Remove",
"a",
"pause",
"from",
"a",
"jid",
"allowing",
"it",
"to",
"continue",
".",
"If",
"the",
"state_id",
"is",
"not",
"specified",
"then",
"the",
"a",
"general",
"pause",
"will",
"be",
"resumed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L297-L328 | train |
saltstack/salt | salt/modules/state.py | orchestrate | def orchestrate(mods,
saltenv='base',
test=None,
exclude=None,
pillar=None,
pillarenv=None):
'''
.. versionadded:: 2016.11.0
Execute the orchestrate runner from a masterless minion.
.. seealso:: More Orchestrate documentation
* :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
* :py:mod:`Docs for the ``salt`` state module <salt.states.saltmod>`
CLI Examples:
.. code-block:: bash
salt-call --local state.orchestrate webserver
salt-call --local state.orchestrate webserver saltenv=dev test=True
salt-call --local state.orchestrate webserver saltenv=dev pillarenv=aws
'''
return _orchestrate(mods=mods,
saltenv=saltenv,
test=test,
exclude=exclude,
pillar=pillar,
pillarenv=pillarenv) | python | def orchestrate(mods,
saltenv='base',
test=None,
exclude=None,
pillar=None,
pillarenv=None):
'''
.. versionadded:: 2016.11.0
Execute the orchestrate runner from a masterless minion.
.. seealso:: More Orchestrate documentation
* :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
* :py:mod:`Docs for the ``salt`` state module <salt.states.saltmod>`
CLI Examples:
.. code-block:: bash
salt-call --local state.orchestrate webserver
salt-call --local state.orchestrate webserver saltenv=dev test=True
salt-call --local state.orchestrate webserver saltenv=dev pillarenv=aws
'''
return _orchestrate(mods=mods,
saltenv=saltenv,
test=test,
exclude=exclude,
pillar=pillar,
pillarenv=pillarenv) | [
"def",
"orchestrate",
"(",
"mods",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"pillar",
"=",
"None",
",",
"pillarenv",
"=",
"None",
")",
":",
"return",
"_orchestrate",
"(",
"mods",
"=",
"mods",
",",
"sa... | .. versionadded:: 2016.11.0
Execute the orchestrate runner from a masterless minion.
.. seealso:: More Orchestrate documentation
* :ref:`Full Orchestrate Tutorial <orchestrate-runner>`
* :py:mod:`Docs for the ``salt`` state module <salt.states.saltmod>`
CLI Examples:
.. code-block:: bash
salt-call --local state.orchestrate webserver
salt-call --local state.orchestrate webserver saltenv=dev test=True
salt-call --local state.orchestrate webserver saltenv=dev pillarenv=aws | [
"..",
"versionadded",
"::",
"2016",
".",
"11",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L331-L360 | train |
saltstack/salt | salt/modules/state.py | _check_queue | def _check_queue(queue, kwargs):
'''
Utility function to queue the state run if requested
and to check for conflicts in currently running states
'''
if queue:
_wait(kwargs.get('__pub_jid'))
else:
conflict = running(concurrent=kwargs.get('concurrent', False))
if conflict:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return conflict | python | def _check_queue(queue, kwargs):
'''
Utility function to queue the state run if requested
and to check for conflicts in currently running states
'''
if queue:
_wait(kwargs.get('__pub_jid'))
else:
conflict = running(concurrent=kwargs.get('concurrent', False))
if conflict:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return conflict | [
"def",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
":",
"if",
"queue",
":",
"_wait",
"(",
"kwargs",
".",
"get",
"(",
"'__pub_jid'",
")",
")",
"else",
":",
"conflict",
"=",
"running",
"(",
"concurrent",
"=",
"kwargs",
".",
"get",
"(",
"'concurrent... | Utility function to queue the state run if requested
and to check for conflicts in currently running states | [
"Utility",
"function",
"to",
"queue",
"the",
"state",
"run",
"if",
"requested",
"and",
"to",
"check",
"for",
"conflicts",
"in",
"currently",
"running",
"states"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L411-L422 | train |
saltstack/salt | salt/modules/state.py | low | def low(data, queue=False, **kwargs):
'''
Execute a single low data call
This function is mostly intended for testing the state system and is not
likely to be needed in everyday usage.
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
try:
st_ = salt.state.State(__opts__, proxy=__proxy__)
except NameError:
st_ = salt.state.State(__opts__)
err = st_.verify_data(data)
if err:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return err
ret = st_.call(data)
if isinstance(ret, list):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
if __utils__['state.check_result'](ret):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_FAILURE
return ret | python | def low(data, queue=False, **kwargs):
'''
Execute a single low data call
This function is mostly intended for testing the state system and is not
likely to be needed in everyday usage.
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
try:
st_ = salt.state.State(__opts__, proxy=__proxy__)
except NameError:
st_ = salt.state.State(__opts__)
err = st_.verify_data(data)
if err:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return err
ret = st_.call(data)
if isinstance(ret, list):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
if __utils__['state.check_result'](ret):
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_FAILURE
return ret | [
"def",
"low",
"(",
"data",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
"try",
":",
"st_",
"=",
"... | Execute a single low data call
This function is mostly intended for testing the state system and is not
likely to be needed in everyday usage.
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}' | [
"Execute",
"a",
"single",
"low",
"data",
"call"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L431-L460 | train |
saltstack/salt | salt/modules/state.py | high | def high(data, test=None, queue=False, **kwargs):
'''
Execute the compound calls stored in a single set of high data
This function is mostly intended for testing the state system and is not
likely to be needed in everyday usage.
CLI Example:
.. code-block:: bash
salt '*' state.high '{"vim": {"pkg": ["installed"]}}'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
context=__context__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
ret = st_.call_high(data)
_set_retcode(ret, highstate=data)
return ret | python | def high(data, test=None, queue=False, **kwargs):
'''
Execute the compound calls stored in a single set of high data
This function is mostly intended for testing the state system and is not
likely to be needed in everyday usage.
CLI Example:
.. code-block:: bash
salt '*' state.high '{"vim": {"pkg": ["installed"]}}'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
context=__context__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
ret = st_.call_high(data)
_set_retcode(ret, highstate=data)
return ret | [
"def",
"high",
"(",
"data",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
... | Execute the compound calls stored in a single set of high data
This function is mostly intended for testing the state system and is not
likely to be needed in everyday usage.
CLI Example:
.. code-block:: bash
salt '*' state.high '{"vim": {"pkg": ["installed"]}}' | [
"Execute",
"the",
"compound",
"calls",
"stored",
"in",
"a",
"single",
"set",
"of",
"high",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L480-L524 | train |
saltstack/salt | salt/modules/state.py | template | def template(tem, queue=False, **kwargs):
'''
Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: bash
salt '*' state.template '<Path to template on the minion>'
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
context=__context__,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
context=__context__,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
if not tem.endswith('.sls'):
tem = '{sls}.sls'.format(sls=tem)
high_state, errors = st_.render_state(tem,
kwargs.get('saltenv', ''),
'',
None,
local=True)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
ret = st_.state.call_high(high_state)
_set_retcode(ret, highstate=high_state)
return ret | python | def template(tem, queue=False, **kwargs):
'''
Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: bash
salt '*' state.template '<Path to template on the minion>'
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
context=__context__,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
context=__context__,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
if not tem.endswith('.sls'):
tem = '{sls}.sls'.format(sls=tem)
high_state, errors = st_.render_state(tem,
kwargs.get('saltenv', ''),
'',
None,
local=True)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
ret = st_.state.call_high(high_state)
_set_retcode(ret, highstate=high_state)
return ret | [
"def",
"template",
"(",
"tem",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'env'",
"in",
"kwargs",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"kwargs",
".",
"pop",
"(",
"'env'",
")",
"conflict",
"=",
"_check_queue",
"(",
... | Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: bash
salt '*' state.template '<Path to template on the minion>' | [
"Execute",
"the",
"information",
"stored",
"in",
"a",
"template",
"file",
"on",
"the",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L527-L576 | train |
saltstack/salt | salt/modules/state.py | template_str | def template_str(tem, queue=False, **kwargs):
'''
Execute the information stored in a string from an sls template
CLI Example:
.. code-block:: bash
salt '*' state.template_str '<Template String>'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.State(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.State(opts, initial_pillar=_get_initial_pillar(opts))
ret = st_.call_template_str(tem)
_set_retcode(ret)
return ret | python | def template_str(tem, queue=False, **kwargs):
'''
Execute the information stored in a string from an sls template
CLI Example:
.. code-block:: bash
salt '*' state.template_str '<Template String>'
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.State(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.State(opts, initial_pillar=_get_initial_pillar(opts))
ret = st_.call_template_str(tem)
_set_retcode(ret)
return ret | [
"def",
"template_str",
"(",
"tem",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
"opts",
"=",
"salt",
... | Execute the information stored in a string from an sls template
CLI Example:
.. code-block:: bash
salt '*' state.template_str '<Template String>' | [
"Execute",
"the",
"information",
"stored",
"in",
"a",
"string",
"from",
"an",
"sls",
"template"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L579-L603 | train |
saltstack/salt | salt/modules/state.py | check_request | def check_request(name=None):
'''
.. versionadded:: 2015.5.0
Return the state request information, if any
CLI Example:
.. code-block:: bash
salt '*' state.check_request
'''
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Serial(__opts__)
if os.path.isfile(notify_path):
with salt.utils.files.fopen(notify_path, 'rb') as fp_:
req = serial.load(fp_)
if name:
return req[name]
return req
return {} | python | def check_request(name=None):
'''
.. versionadded:: 2015.5.0
Return the state request information, if any
CLI Example:
.. code-block:: bash
salt '*' state.check_request
'''
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Serial(__opts__)
if os.path.isfile(notify_path):
with salt.utils.files.fopen(notify_path, 'rb') as fp_:
req = serial.load(fp_)
if name:
return req[name]
return req
return {} | [
"def",
"check_request",
"(",
"name",
"=",
"None",
")",
":",
"notify_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'req_state.p'",
")",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"__opts__",
"... | .. versionadded:: 2015.5.0
Return the state request information, if any
CLI Example:
.. code-block:: bash
salt '*' state.check_request | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L825-L845 | train |
saltstack/salt | salt/modules/state.py | highstate | def highstate(test=None, queue=False, **kwargs):
'''
Retrieve the state data from the salt master for this minion and execute it
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.highstate stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
.. versionchanged:: 2016.3.0
GPG-encrypted CLI Pillar data is now supported via the GPG
renderer. See :ref:`here <encrypted-cli-pillar-data>` for details.
pillar_enc
Specify which renderer to use to decrypt encrypted data located within
the ``pillar`` value. Currently, only ``gpg`` is supported.
.. versionadded:: 2016.3.0
exclude
Exclude specific states from execution. Accepts a list of sls names, a
comma-separated string of sls names, or a list of dictionaries
containing ``sls`` or ``id`` keys. Glob-patterns may be used to match
multiple states.
.. code-block:: bash
salt '*' state.highstate exclude=bar,baz
salt '*' state.highstate exclude=foo*
salt '*' state.highstate exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
saltenv
Specify a salt fileserver environment to be used when applying states
.. versionchanged:: 0.17.0
Argument name changed from ``env`` to ``saltenv``.
.. versionchanged:: 2014.7.0
If no saltenv is specified, the minion config will be checked for a
``saltenv`` parameter and if found, it will be used. If none is
found, ``base`` will be used. In prior releases, the minion config
was not checked and ``base`` would always be assumed when the
saltenv was not explicitly set.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
localconfig
Optionally, instead of using the minion config, load minion opts from
the file specified by this argument, and then merge them with the
options from the minion config. This functionality allows for specific
states to be run with their own custom minion configuration, including
different pillars, file_roots, etc.
mock
The mock option allows for the state run to execute without actually
calling any states. This then returns a mocked return which will show
the requisite ordering as well as fully validate the state run.
.. versionadded:: 2015.8.4
CLI Examples:
.. code-block:: bash
salt '*' state.highstate
salt '*' state.highstate whitelist=sls1_to_run,sls2_to_run
salt '*' state.highstate exclude=sls_to_exclude
salt '*' state.highstate exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
salt '*' state.highstate pillar="{foo: 'Foo!', bar: 'Bar!'}"
'''
if _disabled(['highstate']):
log.debug('Salt highstate run is disabled. To re-enable, run state.enable highstate')
ret = {
'name': 'Salt highstate run is disabled. To re-enable, run state.enable highstate',
'result': 'False',
'comment': 'Disabled'
}
return ret
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
if 'saltenv' in kwargs:
opts['saltenv'] = kwargs['saltenv']
if 'pillarenv' in kwargs:
opts['pillarenv'] = kwargs['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
proxy=__proxy__,
context=__context__,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
st_.push_active()
orchestration_jid = kwargs.get('orchestration_jid')
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
try:
ret = st_.call_highstate(
exclude=kwargs.get('exclude', []),
cache=kwargs.get('cache', None),
cache_name=kwargs.get('cache_name', 'highstate'),
force=kwargs.get('force', False),
whitelist=kwargs.get('whitelist'),
orchestration_jid=orchestration_jid)
finally:
st_.pop_active()
if isinstance(ret, dict) and (__salt__['config.option']('state_data', '') == 'terse' or
kwargs.get('terse')):
ret = _filter_running(ret)
_set_retcode(ret, highstate=st_.building_highstate)
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
return ret | python | def highstate(test=None, queue=False, **kwargs):
'''
Retrieve the state data from the salt master for this minion and execute it
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.highstate stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
.. versionchanged:: 2016.3.0
GPG-encrypted CLI Pillar data is now supported via the GPG
renderer. See :ref:`here <encrypted-cli-pillar-data>` for details.
pillar_enc
Specify which renderer to use to decrypt encrypted data located within
the ``pillar`` value. Currently, only ``gpg`` is supported.
.. versionadded:: 2016.3.0
exclude
Exclude specific states from execution. Accepts a list of sls names, a
comma-separated string of sls names, or a list of dictionaries
containing ``sls`` or ``id`` keys. Glob-patterns may be used to match
multiple states.
.. code-block:: bash
salt '*' state.highstate exclude=bar,baz
salt '*' state.highstate exclude=foo*
salt '*' state.highstate exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
saltenv
Specify a salt fileserver environment to be used when applying states
.. versionchanged:: 0.17.0
Argument name changed from ``env`` to ``saltenv``.
.. versionchanged:: 2014.7.0
If no saltenv is specified, the minion config will be checked for a
``saltenv`` parameter and if found, it will be used. If none is
found, ``base`` will be used. In prior releases, the minion config
was not checked and ``base`` would always be assumed when the
saltenv was not explicitly set.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
localconfig
Optionally, instead of using the minion config, load minion opts from
the file specified by this argument, and then merge them with the
options from the minion config. This functionality allows for specific
states to be run with their own custom minion configuration, including
different pillars, file_roots, etc.
mock
The mock option allows for the state run to execute without actually
calling any states. This then returns a mocked return which will show
the requisite ordering as well as fully validate the state run.
.. versionadded:: 2015.8.4
CLI Examples:
.. code-block:: bash
salt '*' state.highstate
salt '*' state.highstate whitelist=sls1_to_run,sls2_to_run
salt '*' state.highstate exclude=sls_to_exclude
salt '*' state.highstate exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
salt '*' state.highstate pillar="{foo: 'Foo!', bar: 'Bar!'}"
'''
if _disabled(['highstate']):
log.debug('Salt highstate run is disabled. To re-enable, run state.enable highstate')
ret = {
'name': 'Salt highstate run is disabled. To re-enable, run state.enable highstate',
'result': 'False',
'comment': 'Disabled'
}
return ret
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
if 'saltenv' in kwargs:
opts['saltenv'] = kwargs['saltenv']
if 'pillarenv' in kwargs:
opts['pillarenv'] = kwargs['pillarenv']
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
proxy=__proxy__,
context=__context__,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
st_.push_active()
orchestration_jid = kwargs.get('orchestration_jid')
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
try:
ret = st_.call_highstate(
exclude=kwargs.get('exclude', []),
cache=kwargs.get('cache', None),
cache_name=kwargs.get('cache_name', 'highstate'),
force=kwargs.get('force', False),
whitelist=kwargs.get('whitelist'),
orchestration_jid=orchestration_jid)
finally:
st_.pop_active()
if isinstance(ret, dict) and (__salt__['config.option']('state_data', '') == 'terse' or
kwargs.get('terse')):
ret = _filter_running(ret)
_set_retcode(ret, highstate=st_.building_highstate)
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
return ret | [
"def",
"highstate",
"(",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_disabled",
"(",
"[",
"'highstate'",
"]",
")",
":",
"log",
".",
"debug",
"(",
"'Salt highstate run is disabled. To re-enable, run state.enable h... | Retrieve the state data from the salt master for this minion and execute it
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.highstate stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
.. versionchanged:: 2016.3.0
GPG-encrypted CLI Pillar data is now supported via the GPG
renderer. See :ref:`here <encrypted-cli-pillar-data>` for details.
pillar_enc
Specify which renderer to use to decrypt encrypted data located within
the ``pillar`` value. Currently, only ``gpg`` is supported.
.. versionadded:: 2016.3.0
exclude
Exclude specific states from execution. Accepts a list of sls names, a
comma-separated string of sls names, or a list of dictionaries
containing ``sls`` or ``id`` keys. Glob-patterns may be used to match
multiple states.
.. code-block:: bash
salt '*' state.highstate exclude=bar,baz
salt '*' state.highstate exclude=foo*
salt '*' state.highstate exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
saltenv
Specify a salt fileserver environment to be used when applying states
.. versionchanged:: 0.17.0
Argument name changed from ``env`` to ``saltenv``.
.. versionchanged:: 2014.7.0
If no saltenv is specified, the minion config will be checked for a
``saltenv`` parameter and if found, it will be used. If none is
found, ``base`` will be used. In prior releases, the minion config
was not checked and ``base`` would always be assumed when the
saltenv was not explicitly set.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
localconfig
Optionally, instead of using the minion config, load minion opts from
the file specified by this argument, and then merge them with the
options from the minion config. This functionality allows for specific
states to be run with their own custom minion configuration, including
different pillars, file_roots, etc.
mock
The mock option allows for the state run to execute without actually
calling any states. This then returns a mocked return which will show
the requisite ordering as well as fully validate the state run.
.. versionadded:: 2015.8.4
CLI Examples:
.. code-block:: bash
salt '*' state.highstate
salt '*' state.highstate whitelist=sls1_to_run,sls2_to_run
salt '*' state.highstate exclude=sls_to_exclude
salt '*' state.highstate exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
salt '*' state.highstate pillar="{foo: 'Foo!', bar: 'Bar!'}" | [
"Retrieve",
"the",
"state",
"data",
"from",
"the",
"salt",
"master",
"for",
"this",
"minion",
"and",
"execute",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L921-L1098 | train |
saltstack/salt | salt/modules/state.py | sls | def sls(mods, test=None, exclude=None, queue=False, sync_mods=None, **kwargs):
'''
Execute the states in one or more SLS files
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.sls stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override existing Pillar values set via
``pillar_roots`` or an external Pillar source. Pillar values that
are not included in the kwarg will not be overwritten.
.. versionchanged:: 2016.3.0
GPG-encrypted CLI Pillar data is now supported via the GPG
renderer. See :ref:`here <encrypted-cli-pillar-data>` for details.
pillar_enc
Specify which renderer to use to decrypt encrypted data located within
the ``pillar`` value. Currently, only ``gpg`` is supported.
.. versionadded:: 2016.3.0
exclude
Exclude specific states from execution. Accepts a list of sls names, a
comma-separated string of sls names, or a list of dictionaries
containing ``sls`` or ``id`` keys. Glob-patterns may be used to match
multiple states.
.. code-block:: bash
salt '*' state.sls foo,bar,baz exclude=bar,baz
salt '*' state.sls foo,bar,baz exclude=ba*
salt '*' state.sls foo,bar,baz exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
concurrent : False
Execute state runs concurrently instead of serially
.. warning::
This flag is potentially dangerous. It is designed for use when
multiple state runs can safely be run at the same time. Do *not*
use this flag for performance optimization.
saltenv
Specify a salt fileserver environment to be used when applying states
.. versionchanged:: 0.17.0
Argument name changed from ``env`` to ``saltenv``.
.. versionchanged:: 2014.7.0
If no saltenv is specified, the minion config will be checked for an
``environment`` parameter and if found, it will be used. If none is
found, ``base`` will be used. In prior releases, the minion config
was not checked and ``base`` would always be assumed when the
saltenv was not explicitly set.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
localconfig
Optionally, instead of using the minion config, load minion opts from
the file specified by this argument, and then merge them with the
options from the minion config. This functionality allows for specific
states to be run with their own custom minion configuration, including
different pillars, file_roots, etc.
mock:
The mock option allows for the state run to execute without actually
calling any states. This then returns a mocked return which will show
the requisite ordering as well as fully validate the state run.
.. versionadded:: 2015.8.4
sync_mods
If specified, the desired custom module types will be synced prior to
running the SLS files:
.. code-block:: bash
salt '*' state.sls stuff sync_mods=states,modules
salt '*' state.sls stuff sync_mods=all
.. versionadded:: 2017.7.8,2018.3.3,2019.2.0
CLI Example:
.. code-block:: bash
salt '*' state.sls core,edit.vim dev
salt '*' state.sls core exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
salt '*' state.sls myslsfile pillar="{foo: 'Foo!', bar: 'Bar!'}"
'''
concurrent = kwargs.get('concurrent', False)
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
# Modification to __opts__ lost after this if-else
if queue:
_wait(kwargs.get('__pub_jid'))
else:
conflict = running(concurrent)
if conflict:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return conflict
if isinstance(mods, list):
disabled = _disabled(mods)
else:
disabled = _disabled([mods])
if disabled:
for state in disabled:
log.debug(
'Salt state %s is disabled. To re-enable, run '
'state.enable %s', state, state
)
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return disabled
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is running a specific SLS file (or files), fall back to the
# 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
serial = salt.payload.Serial(__opts__)
cfn = os.path.join(
__opts__['cachedir'],
'{0}.cache.p'.format(kwargs.get('cache_name', 'highstate'))
)
if sync_mods is True:
sync_mods = ['all']
if sync_mods is not None:
sync_mods = salt.utils.args.split_input(sync_mods)
else:
sync_mods = []
if 'all' in sync_mods and sync_mods != ['all']:
# Prevent unnecessary extra syncing
sync_mods = ['all']
for module_type in sync_mods:
try:
__salt__['saltutil.sync_{0}'.format(module_type)](
saltenv=opts['saltenv']
)
except KeyError:
log.warning(
'Invalid custom module type \'%s\', ignoring',
module_type
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
proxy=__proxy__,
context=__context__,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
orchestration_jid = kwargs.get('orchestration_jid')
with salt.utils.files.set_umask(0o077):
if kwargs.get('cache'):
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high_ = serial.load(fp_)
return st_.state.call_high(high_, orchestration_jid)
# If the state file is an integer, convert to a string then to unicode
if isinstance(mods, six.integer_types):
mods = salt.utils.stringutils.to_unicode(str(mods)) # future lint: disable=blacklisted-function
mods = salt.utils.args.split_input(mods)
st_.push_active()
try:
high_, errors = st_.render_highstate({opts['saltenv']: mods})
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
if exclude:
exclude = salt.utils.args.split_input(exclude)
if '__exclude__' in high_:
high_['__exclude__'].extend(exclude)
else:
high_['__exclude__'] = exclude
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
ret = st_.state.call_high(high_, orchestration_jid)
finally:
st_.pop_active()
if __salt__['config.option']('state_data', '') == 'terse' or kwargs.get('terse'):
ret = _filter_running(ret)
cache_file = os.path.join(__opts__['cachedir'], 'sls.p')
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
__salt__['cmd.run'](['attrib', '-R', cache_file], python_shell=False)
with salt.utils.files.fopen(cache_file, 'w+b') as fp_:
serial.dump(ret, fp_)
except (IOError, OSError):
log.error(
'Unable to write to SLS cache file %s. Check permission.',
cache_file
)
_set_retcode(ret, high_)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
try:
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
serial.dump(high_, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error(
'Unable to write to highstate cache file %s. Do you have permissions?',
cfn
)
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
return ret | python | def sls(mods, test=None, exclude=None, queue=False, sync_mods=None, **kwargs):
'''
Execute the states in one or more SLS files
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.sls stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override existing Pillar values set via
``pillar_roots`` or an external Pillar source. Pillar values that
are not included in the kwarg will not be overwritten.
.. versionchanged:: 2016.3.0
GPG-encrypted CLI Pillar data is now supported via the GPG
renderer. See :ref:`here <encrypted-cli-pillar-data>` for details.
pillar_enc
Specify which renderer to use to decrypt encrypted data located within
the ``pillar`` value. Currently, only ``gpg`` is supported.
.. versionadded:: 2016.3.0
exclude
Exclude specific states from execution. Accepts a list of sls names, a
comma-separated string of sls names, or a list of dictionaries
containing ``sls`` or ``id`` keys. Glob-patterns may be used to match
multiple states.
.. code-block:: bash
salt '*' state.sls foo,bar,baz exclude=bar,baz
salt '*' state.sls foo,bar,baz exclude=ba*
salt '*' state.sls foo,bar,baz exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
concurrent : False
Execute state runs concurrently instead of serially
.. warning::
This flag is potentially dangerous. It is designed for use when
multiple state runs can safely be run at the same time. Do *not*
use this flag for performance optimization.
saltenv
Specify a salt fileserver environment to be used when applying states
.. versionchanged:: 0.17.0
Argument name changed from ``env`` to ``saltenv``.
.. versionchanged:: 2014.7.0
If no saltenv is specified, the minion config will be checked for an
``environment`` parameter and if found, it will be used. If none is
found, ``base`` will be used. In prior releases, the minion config
was not checked and ``base`` would always be assumed when the
saltenv was not explicitly set.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
localconfig
Optionally, instead of using the minion config, load minion opts from
the file specified by this argument, and then merge them with the
options from the minion config. This functionality allows for specific
states to be run with their own custom minion configuration, including
different pillars, file_roots, etc.
mock:
The mock option allows for the state run to execute without actually
calling any states. This then returns a mocked return which will show
the requisite ordering as well as fully validate the state run.
.. versionadded:: 2015.8.4
sync_mods
If specified, the desired custom module types will be synced prior to
running the SLS files:
.. code-block:: bash
salt '*' state.sls stuff sync_mods=states,modules
salt '*' state.sls stuff sync_mods=all
.. versionadded:: 2017.7.8,2018.3.3,2019.2.0
CLI Example:
.. code-block:: bash
salt '*' state.sls core,edit.vim dev
salt '*' state.sls core exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
salt '*' state.sls myslsfile pillar="{foo: 'Foo!', bar: 'Bar!'}"
'''
concurrent = kwargs.get('concurrent', False)
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
# Modification to __opts__ lost after this if-else
if queue:
_wait(kwargs.get('__pub_jid'))
else:
conflict = running(concurrent)
if conflict:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return conflict
if isinstance(mods, list):
disabled = _disabled(mods)
else:
disabled = _disabled([mods])
if disabled:
for state in disabled:
log.debug(
'Salt state %s is disabled. To re-enable, run '
'state.enable %s', state, state
)
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return disabled
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is running a specific SLS file (or files), fall back to the
# 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
serial = salt.payload.Serial(__opts__)
cfn = os.path.join(
__opts__['cachedir'],
'{0}.cache.p'.format(kwargs.get('cache_name', 'highstate'))
)
if sync_mods is True:
sync_mods = ['all']
if sync_mods is not None:
sync_mods = salt.utils.args.split_input(sync_mods)
else:
sync_mods = []
if 'all' in sync_mods and sync_mods != ['all']:
# Prevent unnecessary extra syncing
sync_mods = ['all']
for module_type in sync_mods:
try:
__salt__['saltutil.sync_{0}'.format(module_type)](
saltenv=opts['saltenv']
)
except KeyError:
log.warning(
'Invalid custom module type \'%s\', ignoring',
module_type
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
proxy=__proxy__,
context=__context__,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
kwargs.get('__pub_jid'),
pillar_enc=pillar_enc,
mocked=kwargs.get('mock', False),
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
orchestration_jid = kwargs.get('orchestration_jid')
with salt.utils.files.set_umask(0o077):
if kwargs.get('cache'):
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high_ = serial.load(fp_)
return st_.state.call_high(high_, orchestration_jid)
# If the state file is an integer, convert to a string then to unicode
if isinstance(mods, six.integer_types):
mods = salt.utils.stringutils.to_unicode(str(mods)) # future lint: disable=blacklisted-function
mods = salt.utils.args.split_input(mods)
st_.push_active()
try:
high_, errors = st_.render_highstate({opts['saltenv']: mods})
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
if exclude:
exclude = salt.utils.args.split_input(exclude)
if '__exclude__' in high_:
high_['__exclude__'].extend(exclude)
else:
high_['__exclude__'] = exclude
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
ret = st_.state.call_high(high_, orchestration_jid)
finally:
st_.pop_active()
if __salt__['config.option']('state_data', '') == 'terse' or kwargs.get('terse'):
ret = _filter_running(ret)
cache_file = os.path.join(__opts__['cachedir'], 'sls.p')
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
__salt__['cmd.run'](['attrib', '-R', cache_file], python_shell=False)
with salt.utils.files.fopen(cache_file, 'w+b') as fp_:
serial.dump(ret, fp_)
except (IOError, OSError):
log.error(
'Unable to write to SLS cache file %s. Check permission.',
cache_file
)
_set_retcode(ret, high_)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
try:
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
serial.dump(high_, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error(
'Unable to write to highstate cache file %s. Do you have permissions?',
cfn
)
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
return ret | [
"def",
"sls",
"(",
"mods",
",",
"test",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"sync_mods",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"concurrent",
"=",
"kwargs",
".",
"get",
"(",
"'concurrent'",
",",
"Fals... | Execute the states in one or more SLS files
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.sls stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override existing Pillar values set via
``pillar_roots`` or an external Pillar source. Pillar values that
are not included in the kwarg will not be overwritten.
.. versionchanged:: 2016.3.0
GPG-encrypted CLI Pillar data is now supported via the GPG
renderer. See :ref:`here <encrypted-cli-pillar-data>` for details.
pillar_enc
Specify which renderer to use to decrypt encrypted data located within
the ``pillar`` value. Currently, only ``gpg`` is supported.
.. versionadded:: 2016.3.0
exclude
Exclude specific states from execution. Accepts a list of sls names, a
comma-separated string of sls names, or a list of dictionaries
containing ``sls`` or ``id`` keys. Glob-patterns may be used to match
multiple states.
.. code-block:: bash
salt '*' state.sls foo,bar,baz exclude=bar,baz
salt '*' state.sls foo,bar,baz exclude=ba*
salt '*' state.sls foo,bar,baz exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
concurrent : False
Execute state runs concurrently instead of serially
.. warning::
This flag is potentially dangerous. It is designed for use when
multiple state runs can safely be run at the same time. Do *not*
use this flag for performance optimization.
saltenv
Specify a salt fileserver environment to be used when applying states
.. versionchanged:: 0.17.0
Argument name changed from ``env`` to ``saltenv``.
.. versionchanged:: 2014.7.0
If no saltenv is specified, the minion config will be checked for an
``environment`` parameter and if found, it will be used. If none is
found, ``base`` will be used. In prior releases, the minion config
was not checked and ``base`` would always be assumed when the
saltenv was not explicitly set.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
localconfig
Optionally, instead of using the minion config, load minion opts from
the file specified by this argument, and then merge them with the
options from the minion config. This functionality allows for specific
states to be run with their own custom minion configuration, including
different pillars, file_roots, etc.
mock:
The mock option allows for the state run to execute without actually
calling any states. This then returns a mocked return which will show
the requisite ordering as well as fully validate the state run.
.. versionadded:: 2015.8.4
sync_mods
If specified, the desired custom module types will be synced prior to
running the SLS files:
.. code-block:: bash
salt '*' state.sls stuff sync_mods=states,modules
salt '*' state.sls stuff sync_mods=all
.. versionadded:: 2017.7.8,2018.3.3,2019.2.0
CLI Example:
.. code-block:: bash
salt '*' state.sls core,edit.vim dev
salt '*' state.sls core exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
salt '*' state.sls myslsfile pillar="{foo: 'Foo!', bar: 'Bar!'}" | [
"Execute",
"the",
"states",
"in",
"one",
"or",
"more",
"SLS",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1101-L1377 | train |
saltstack/salt | salt/modules/state.py | top | def top(topfn, test=None, queue=False, **kwargs):
'''
Execute a specific top file instead of the default. This is useful to apply
configurations from a different environment (for example, dev or prod), without
modifying the default top file.
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
saltenv
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' state.top reverse_top.sls
salt '*' state.top prod_top.sls exclude=sls_to_exclude
salt '*' state.top dev_top.sls exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
context=__context__,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
context=__context__,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
st_.push_active()
st_.opts['state_top'] = salt.utils.url.create(topfn)
ret = {}
orchestration_jid = kwargs.get('orchestration_jid')
if 'saltenv' in kwargs:
st_.opts['state_top_saltenv'] = kwargs['saltenv']
try:
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
ret = st_.call_highstate(
exclude=kwargs.get('exclude', []),
cache=kwargs.get('cache', None),
cache_name=kwargs.get('cache_name', 'highstate'),
orchestration_jid=orchestration_jid)
finally:
st_.pop_active()
_set_retcode(ret, highstate=st_.building_highstate)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
__opts__['test'] = orig_test
return ret | python | def top(topfn, test=None, queue=False, **kwargs):
'''
Execute a specific top file instead of the default. This is useful to apply
configurations from a different environment (for example, dev or prod), without
modifying the default top file.
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
saltenv
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' state.top reverse_top.sls
salt '*' state.top prod_top.sls exclude=sls_to_exclude
salt '*' state.top dev_top.sls exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]"
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
context=__context__,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
context=__context__,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
st_.push_active()
st_.opts['state_top'] = salt.utils.url.create(topfn)
ret = {}
orchestration_jid = kwargs.get('orchestration_jid')
if 'saltenv' in kwargs:
st_.opts['state_top_saltenv'] = kwargs['saltenv']
try:
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
ret = st_.call_highstate(
exclude=kwargs.get('exclude', []),
cache=kwargs.get('cache', None),
cache_name=kwargs.get('cache_name', 'highstate'),
orchestration_jid=orchestration_jid)
finally:
st_.pop_active()
_set_retcode(ret, highstate=st_.building_highstate)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
__opts__['test'] = orig_test
return ret | [
"def",
"top",
"(",
"topfn",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
... | Execute a specific top file instead of the default. This is useful to apply
configurations from a different environment (for example, dev or prod), without
modifying the default top file.
queue : False
Instead of failing immediately when another state run is in progress,
queue the new state run to begin running once the other has finished.
This option starts a new thread for each queued state run, so use this
option sparingly.
saltenv
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' state.top reverse_top.sls
salt '*' state.top prod_top.sls exclude=sls_to_exclude
salt '*' state.top dev_top.sls exclude="[{'id': 'id_to_exclude'}, {'sls': 'sls_to_exclude'}]" | [
"Execute",
"a",
"specific",
"top",
"file",
"instead",
"of",
"the",
"default",
".",
"This",
"is",
"useful",
"to",
"apply",
"configurations",
"from",
"a",
"different",
"environment",
"(",
"for",
"example",
"dev",
"or",
"prod",
")",
"without",
"modifying",
"the... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1380-L1468 | train |
saltstack/salt | salt/modules/state.py | show_highstate | def show_highstate(queue=False, **kwargs):
'''
Retrieve the highstate data from the salt master and display it
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
st_.push_active()
try:
ret = st_.compile_highstate()
finally:
st_.pop_active()
_set_retcode(ret)
return ret | python | def show_highstate(queue=False, **kwargs):
'''
Retrieve the highstate data from the salt master and display it
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
st_.push_active()
try:
ret = st_.compile_highstate()
finally:
st_.pop_active()
_set_retcode(ret)
return ret | [
"def",
"show_highstate",
"(",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
"pillar_override",
"=",
"kwargs",
... | Retrieve the highstate data from the salt master and display it
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate | [
"Retrieve",
"the",
"highstate",
"data",
"from",
"the",
"salt",
"master",
"and",
"display",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1471-L1520 | train |
saltstack/salt | salt/modules/state.py | show_lowstate | def show_lowstate(queue=False, **kwargs):
'''
List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
assert False
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
st_.push_active()
try:
ret = st_.compile_low_chunks()
finally:
st_.pop_active()
return ret | python | def show_lowstate(queue=False, **kwargs):
'''
List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
assert False
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
st_.push_active()
try:
ret = st_.compile_low_chunks()
finally:
st_.pop_active()
return ret | [
"def",
"show_lowstate",
"(",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"assert",
"False",
"return",
"conflict",
"opts",
"=",
... | List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate | [
"List",
"out",
"the",
"low",
"data",
"that",
"will",
"be",
"applied",
"to",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1523-L1557 | train |
saltstack/salt | salt/modules/state.py | show_state_usage | def show_state_usage(queue=False, **kwargs):
'''
Retrieve the highstate data from the salt master to analyse used and unused states
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_state_usage
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
pillar = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar is not None \
and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
st_ = salt.state.HighState(__opts__, pillar, pillar_enc=pillar_enc)
st_.push_active()
try:
ret = st_.compile_state_usage()
finally:
st_.pop_active()
_set_retcode(ret)
return ret | python | def show_state_usage(queue=False, **kwargs):
'''
Retrieve the highstate data from the salt master to analyse used and unused states
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_state_usage
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
pillar = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar is not None \
and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
st_ = salt.state.HighState(__opts__, pillar, pillar_enc=pillar_enc)
st_.push_active()
try:
ret = st_.compile_state_usage()
finally:
st_.pop_active()
_set_retcode(ret)
return ret | [
"def",
"show_state_usage",
"(",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"return",
"conflict",
"pillar",
"=",
"kwargs",
".",
... | Retrieve the highstate data from the salt master to analyse used and unused states
Custom Pillar data can be passed with the ``pillar`` kwarg.
CLI Example:
.. code-block:: bash
salt '*' state.show_state_usage | [
"Retrieve",
"the",
"highstate",
"data",
"from",
"the",
"salt",
"master",
"to",
"analyse",
"used",
"and",
"unused",
"states"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1560-L1593 | train |
saltstack/salt | salt/modules/state.py | show_states | def show_states(queue=False, **kwargs):
'''
Returns the list of states that will be applied on highstate.
CLI Example:
.. code-block:: bash
salt '*' state.show_states
.. versionadded:: 2019.2.0
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
assert False
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
st_.push_active()
states = OrderedDict()
try:
result = st_.compile_low_chunks()
if not isinstance(result, list):
raise Exception(result)
for s in result:
states[s['__sls__']] = True
finally:
st_.pop_active()
return list(states.keys()) | python | def show_states(queue=False, **kwargs):
'''
Returns the list of states that will be applied on highstate.
CLI Example:
.. code-block:: bash
salt '*' state.show_states
.. versionadded:: 2019.2.0
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
assert False
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
st_.push_active()
states = OrderedDict()
try:
result = st_.compile_low_chunks()
if not isinstance(result, list):
raise Exception(result)
for s in result:
states[s['__sls__']] = True
finally:
st_.pop_active()
return list(states.keys()) | [
"def",
"show_states",
"(",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"assert",
"False",
"return",
"conflict",
"opts",
"=",
"s... | Returns the list of states that will be applied on highstate.
CLI Example:
.. code-block:: bash
salt '*' state.show_states
.. versionadded:: 2019.2.0 | [
"Returns",
"the",
"list",
"of",
"states",
"that",
"will",
"be",
"applied",
"on",
"highstate",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1596-L1641 | train |
saltstack/salt | salt/modules/state.py | sls_id | def sls_id(id_, mods, test=None, queue=False, **kwargs):
'''
Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requisites
.. versionadded:: 2014.7.0
saltenv : base
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.sls_id my_state my_module pillar='{"foo": "bar"}'
.. note::
Values passed this way will override existing Pillar values set via
``pillar_roots`` or an external Pillar source. Pillar values that
are not included in the kwarg will not be overwritten.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' state.sls_id my_state my_module
salt '*' state.sls_id my_state my_module,a_common_module
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is running a specific ID within a specific SLS file, fall back
# to the 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
split_mods = salt.utils.args.split_input(mods)
st_.push_active()
try:
high_, errors = st_.render_highstate({opts['saltenv']: split_mods})
finally:
st_.pop_active()
errors += st_.state.verify_high(high_)
# Apply requisites to high data
high_, req_in_errors = st_.state.requisite_in(high_)
if req_in_errors:
# This if statement should not be necessary if there were no errors,
# but it is required to get the unit tests to pass.
errors.extend(req_in_errors)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
chunks = st_.state.compile_high_data(high_)
ret = {}
for chunk in chunks:
if chunk.get('__id__', '') == id_:
ret.update(st_.state.call_chunk(chunk, {}, chunks))
_set_retcode(ret, highstate=highstate)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
if not ret:
raise SaltInvocationError(
'No matches for ID \'{0}\' found in SLS \'{1}\' within saltenv '
'\'{2}\''.format(id_, mods, opts['saltenv'])
)
return ret | python | def sls_id(id_, mods, test=None, queue=False, **kwargs):
'''
Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requisites
.. versionadded:: 2014.7.0
saltenv : base
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.sls_id my_state my_module pillar='{"foo": "bar"}'
.. note::
Values passed this way will override existing Pillar values set via
``pillar_roots`` or an external Pillar source. Pillar values that
are not included in the kwarg will not be overwritten.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' state.sls_id my_state my_module
salt '*' state.sls_id my_state my_module,a_common_module
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is running a specific ID within a specific SLS file, fall back
# to the 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
return ['Pillar failed to render with the following messages:'] + errors
split_mods = salt.utils.args.split_input(mods)
st_.push_active()
try:
high_, errors = st_.render_highstate({opts['saltenv']: split_mods})
finally:
st_.pop_active()
errors += st_.state.verify_high(high_)
# Apply requisites to high data
high_, req_in_errors = st_.state.requisite_in(high_)
if req_in_errors:
# This if statement should not be necessary if there were no errors,
# but it is required to get the unit tests to pass.
errors.extend(req_in_errors)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
chunks = st_.state.compile_high_data(high_)
ret = {}
for chunk in chunks:
if chunk.get('__id__', '') == id_:
ret.update(st_.state.call_chunk(chunk, {}, chunks))
_set_retcode(ret, highstate=highstate)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
if not ret:
raise SaltInvocationError(
'No matches for ID \'{0}\' found in SLS \'{1}\' within saltenv '
'\'{2}\''.format(id_, mods, opts['saltenv'])
)
return ret | [
"def",
"sls_id",
"(",
"id_",
",",
"mods",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"retur... | Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requisites
.. versionadded:: 2014.7.0
saltenv : base
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.sls_id my_state my_module pillar='{"foo": "bar"}'
.. note::
Values passed this way will override existing Pillar values set via
``pillar_roots`` or an external Pillar source. Pillar values that
are not included in the kwarg will not be overwritten.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' state.sls_id my_state my_module
salt '*' state.sls_id my_state my_module,a_common_module | [
"Call",
"a",
"single",
"ID",
"from",
"the",
"named",
"module",
"(",
"s",
")",
"and",
"handle",
"all",
"requisites"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1644-L1760 | train |
saltstack/salt | salt/modules/state.py | show_low_sls | def show_low_sls(mods, test=None, queue=False, **kwargs):
'''
Display the low data from a specific sls. The default environment is
``base``, use ``saltenv`` to specify a different environment.
saltenv
Specify a salt fileserver environment to be used when applying states
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.show_low_sls stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
CLI Example:
.. code-block:: bash
salt '*' state.show_low_sls foo
salt '*' state.show_low_sls foo saltenv=dev
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is dealing with a specific SLS file (or files), fall back to
# the 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
mods = salt.utils.args.split_input(mods)
st_.push_active()
try:
high_, errors = st_.render_highstate({opts['saltenv']: mods})
finally:
st_.pop_active()
errors += st_.state.verify_high(high_)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
ret = st_.state.compile_high_data(high_)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
return ret | python | def show_low_sls(mods, test=None, queue=False, **kwargs):
'''
Display the low data from a specific sls. The default environment is
``base``, use ``saltenv`` to specify a different environment.
saltenv
Specify a salt fileserver environment to be used when applying states
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.show_low_sls stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
CLI Example:
.. code-block:: bash
salt '*' state.show_low_sls foo
salt '*' state.show_low_sls foo saltenv=dev
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is dealing with a specific SLS file (or files), fall back to
# the 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.HighState(opts,
pillar_override,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts,
pillar_override,
initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
mods = salt.utils.args.split_input(mods)
st_.push_active()
try:
high_, errors = st_.render_highstate({opts['saltenv']: mods})
finally:
st_.pop_active()
errors += st_.state.verify_high(high_)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
ret = st_.state.compile_high_data(high_)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
return ret | [
"def",
"show_low_sls",
"(",
"mods",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'env'",
"in",
"kwargs",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"kwargs",
".",
"pop",
"(",
"'env'",
")",
"confl... | Display the low data from a specific sls. The default environment is
``base``, use ``saltenv`` to specify a different environment.
saltenv
Specify a salt fileserver environment to be used when applying states
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
salt '*' state.show_low_sls stuff pillar='{"foo": "bar"}'
.. note::
Values passed this way will override Pillar values set via
``pillar_roots`` or an external Pillar source.
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
CLI Example:
.. code-block:: bash
salt '*' state.show_low_sls foo
salt '*' state.show_low_sls foo saltenv=dev | [
"Display",
"the",
"low",
"data",
"from",
"a",
"specific",
"sls",
".",
"The",
"default",
"environment",
"is",
"base",
"use",
"saltenv",
"to",
"specify",
"a",
"different",
"environment",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1763-L1851 | train |
saltstack/salt | salt/modules/state.py | sls_exists | def sls_exists(mods, test=None, queue=False, **kwargs):
'''
Tests for the existance the of a specific SLS or list of SLS files on the
master. Similar to :py:func:`state.show_sls <salt.modules.state.show_sls>`,
rather than returning state details, returns True or False. The default
environment is ``base``, use ``saltenv`` to specify a different environment.
.. versionadded:: 2019.2.0
saltenv
Specify a salt fileserver environment from which to look for the SLS files
specified in the ``mods`` argument
CLI Example:
.. code-block:: bash
salt '*' state.sls_exists core,edit.vim saltenv=dev
'''
return isinstance(
show_sls(mods, test=test, queue=queue, **kwargs),
dict
) | python | def sls_exists(mods, test=None, queue=False, **kwargs):
'''
Tests for the existance the of a specific SLS or list of SLS files on the
master. Similar to :py:func:`state.show_sls <salt.modules.state.show_sls>`,
rather than returning state details, returns True or False. The default
environment is ``base``, use ``saltenv`` to specify a different environment.
.. versionadded:: 2019.2.0
saltenv
Specify a salt fileserver environment from which to look for the SLS files
specified in the ``mods`` argument
CLI Example:
.. code-block:: bash
salt '*' state.sls_exists core,edit.vim saltenv=dev
'''
return isinstance(
show_sls(mods, test=test, queue=queue, **kwargs),
dict
) | [
"def",
"sls_exists",
"(",
"mods",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"isinstance",
"(",
"show_sls",
"(",
"mods",
",",
"test",
"=",
"test",
",",
"queue",
"=",
"queue",
",",
"*",
"*",
... | Tests for the existance the of a specific SLS or list of SLS files on the
master. Similar to :py:func:`state.show_sls <salt.modules.state.show_sls>`,
rather than returning state details, returns True or False. The default
environment is ``base``, use ``saltenv`` to specify a different environment.
.. versionadded:: 2019.2.0
saltenv
Specify a salt fileserver environment from which to look for the SLS files
specified in the ``mods`` argument
CLI Example:
.. code-block:: bash
salt '*' state.sls_exists core,edit.vim saltenv=dev | [
"Tests",
"for",
"the",
"existance",
"the",
"of",
"a",
"specific",
"SLS",
"or",
"list",
"of",
"SLS",
"files",
"on",
"the",
"master",
".",
"Similar",
"to",
":",
"py",
":",
"func",
":",
"state",
".",
"show_sls",
"<salt",
".",
"modules",
".",
"state",
".... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1941-L1963 | train |
saltstack/salt | salt/modules/state.py | id_exists | def id_exists(ids, mods, test=None, queue=False, **kwargs):
'''
Tests for the existence of a specific ID or list of IDs within the
specified SLS file(s). Similar to :py:func:`state.sls_exists
<salt.modules.state.sls_exists>`, returns True or False. The default
environment is base``, use ``saltenv`` to specify a different environment.
.. versionadded:: 2019.2.0
saltenv
Specify a salt fileserver environment from which to look for the SLS files
specified in the ``mods`` argument
CLI Example:
.. code-block:: bash
salt '*' state.id_exists create_myfile,update_template filestate saltenv=dev
'''
ids = salt.utils.args.split_input(ids)
ids = set(ids)
sls_ids = set(x['__id__'] for x in show_low_sls(mods, test=test, queue=queue, **kwargs))
return ids.issubset(sls_ids) | python | def id_exists(ids, mods, test=None, queue=False, **kwargs):
'''
Tests for the existence of a specific ID or list of IDs within the
specified SLS file(s). Similar to :py:func:`state.sls_exists
<salt.modules.state.sls_exists>`, returns True or False. The default
environment is base``, use ``saltenv`` to specify a different environment.
.. versionadded:: 2019.2.0
saltenv
Specify a salt fileserver environment from which to look for the SLS files
specified in the ``mods`` argument
CLI Example:
.. code-block:: bash
salt '*' state.id_exists create_myfile,update_template filestate saltenv=dev
'''
ids = salt.utils.args.split_input(ids)
ids = set(ids)
sls_ids = set(x['__id__'] for x in show_low_sls(mods, test=test, queue=queue, **kwargs))
return ids.issubset(sls_ids) | [
"def",
"id_exists",
"(",
"ids",
",",
"mods",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ids",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"split_input",
"(",
"ids",
")",
"ids",
"=",
"set",
"(",
"i... | Tests for the existence of a specific ID or list of IDs within the
specified SLS file(s). Similar to :py:func:`state.sls_exists
<salt.modules.state.sls_exists>`, returns True or False. The default
environment is base``, use ``saltenv`` to specify a different environment.
.. versionadded:: 2019.2.0
saltenv
Specify a salt fileserver environment from which to look for the SLS files
specified in the ``mods`` argument
CLI Example:
.. code-block:: bash
salt '*' state.id_exists create_myfile,update_template filestate saltenv=dev | [
"Tests",
"for",
"the",
"existence",
"of",
"a",
"specific",
"ID",
"or",
"list",
"of",
"IDs",
"within",
"the",
"specified",
"SLS",
"file",
"(",
"s",
")",
".",
"Similar",
"to",
":",
"py",
":",
"func",
":",
"state",
".",
"sls_exists",
"<salt",
".",
"modu... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1966-L1988 | train |
saltstack/salt | salt/modules/state.py | show_top | def show_top(queue=False, **kwargs):
'''
Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts, initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
errors = []
top_ = st_.get_top()
errors += st_.verify_tops(top_)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
matches = st_.top_matches(top_)
return matches | python | def show_top(queue=False, **kwargs):
'''
Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top
'''
if 'env' in kwargs:
# "env" is not supported; Use "saltenv".
kwargs.pop('env')
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
try:
st_ = salt.state.HighState(opts,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.HighState(opts, initial_pillar=_get_initial_pillar(opts))
errors = _get_pillar_errors(kwargs, pillar=st_.opts['pillar'])
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_PILLAR_FAILURE
raise CommandExecutionError('Pillar failed to render', info=errors)
errors = []
top_ = st_.get_top()
errors += st_.verify_tops(top_)
if errors:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return errors
matches = st_.top_matches(top_)
return matches | [
"def",
"show_top",
"(",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'env'",
"in",
"kwargs",
":",
"# \"env\" is not supported; Use \"saltenv\".",
"kwargs",
".",
"pop",
"(",
"'env'",
")",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",... | Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top | [
"Return",
"the",
"top",
"data",
"that",
"the",
"minion",
"will",
"use",
"for",
"a",
"highstate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L1991-L2029 | train |
saltstack/salt | salt/modules/state.py | single | def single(fun, name, test=None, queue=False, **kwargs):
'''
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML salt file. Alternatively, JSON format of keyword values
is also supported.
CLI Example:
.. code-block:: bash
salt '*' state.single pkg.installed name=vim
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
comps = fun.split('.')
if len(comps) < 2:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return 'Invalid function passed'
kwargs.update({'state': comps[0],
'fun': comps[1],
'__id__': name,
'name': name})
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
err = st_.verify_data(kwargs)
if err:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return err
st_._mod_init(kwargs)
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
ret = {'{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(kwargs):
st_.call(kwargs)}
_set_retcode(ret)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
__opts__['test'] = orig_test
return ret | python | def single(fun, name, test=None, queue=False, **kwargs):
'''
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML salt file. Alternatively, JSON format of keyword values
is also supported.
CLI Example:
.. code-block:: bash
salt '*' state.single pkg.installed name=vim
'''
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
comps = fun.split('.')
if len(comps) < 2:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return 'Invalid function passed'
kwargs.update({'state': comps[0],
'fun': comps[1],
'__id__': name,
'name': name})
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
pillar_override = kwargs.get('pillar')
pillar_enc = kwargs.get('pillar_enc')
if pillar_enc is None \
and pillar_override is not None \
and not isinstance(pillar_override, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary, unless pillar_enc '
'is specified.'
)
try:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
proxy=__proxy__,
initial_pillar=_get_initial_pillar(opts))
except NameError:
st_ = salt.state.State(opts,
pillar_override,
pillar_enc=pillar_enc,
initial_pillar=_get_initial_pillar(opts))
err = st_.verify_data(kwargs)
if err:
__context__['retcode'] = salt.defaults.exitcodes.EX_STATE_COMPILER_ERROR
return err
st_._mod_init(kwargs)
snapper_pre = _snapper_pre(opts, kwargs.get('__pub_jid', 'called localy'))
ret = {'{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(kwargs):
st_.call(kwargs)}
_set_retcode(ret)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
_snapper_post(opts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
__opts__['test'] = orig_test
return ret | [
"def",
"single",
"(",
"fun",
",",
"name",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
"conflict",
"is",
"not",
"None",
":",
"retur... | Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML salt file. Alternatively, JSON format of keyword values
is also supported.
CLI Example:
.. code-block:: bash
salt '*' state.single pkg.installed name=vim | [
"Execute",
"a",
"single",
"state",
"function",
"with",
"the",
"named",
"kwargs",
"returns",
"False",
"if",
"insufficient",
"data",
"is",
"sent",
"to",
"the",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2032-L2099 | train |
saltstack/salt | salt/modules/state.py | clear_cache | def clear_cache():
'''
Clear out cached state files, forcing even cache runs to refresh the cache
on the next state execution.
Remember that the state cache is completely disabled by default, this
execution only applies if cache=True is used in states
CLI Example:
.. code-block:: bash
salt '*' state.clear_cache
'''
ret = []
for fn_ in os.listdir(__opts__['cachedir']):
if fn_.endswith('.cache.p'):
path = os.path.join(__opts__['cachedir'], fn_)
if not os.path.isfile(path):
continue
os.remove(path)
ret.append(fn_)
return ret | python | def clear_cache():
'''
Clear out cached state files, forcing even cache runs to refresh the cache
on the next state execution.
Remember that the state cache is completely disabled by default, this
execution only applies if cache=True is used in states
CLI Example:
.. code-block:: bash
salt '*' state.clear_cache
'''
ret = []
for fn_ in os.listdir(__opts__['cachedir']):
if fn_.endswith('.cache.p'):
path = os.path.join(__opts__['cachedir'], fn_)
if not os.path.isfile(path):
continue
os.remove(path)
ret.append(fn_)
return ret | [
"def",
"clear_cache",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"fn_",
"in",
"os",
".",
"listdir",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
")",
":",
"if",
"fn_",
".",
"endswith",
"(",
"'.cache.p'",
")",
":",
"path",
"=",
"os",
".",
"path",
"."... | Clear out cached state files, forcing even cache runs to refresh the cache
on the next state execution.
Remember that the state cache is completely disabled by default, this
execution only applies if cache=True is used in states
CLI Example:
.. code-block:: bash
salt '*' state.clear_cache | [
"Clear",
"out",
"cached",
"state",
"files",
"forcing",
"even",
"cache",
"runs",
"to",
"refresh",
"the",
"cache",
"on",
"the",
"next",
"state",
"execution",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2102-L2124 | train |
saltstack/salt | salt/modules/state.py | pkg | def pkg(pkg_path,
pkg_sum,
hash_type,
test=None,
**kwargs):
'''
Execute a packaged state run, the packaged state run will exist in a
tarball available locally. This packaged state
can be generated using salt-ssh.
CLI Example:
.. code-block:: bash
salt '*' state.pkg /tmp/salt_state.tgz 760a9353810e36f6d81416366fc426dc md5
'''
# TODO - Add ability to download from salt master or other source
popts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
if not os.path.isfile(pkg_path):
return {}
if not salt.utils.hashutils.get_hash(pkg_path, hash_type) == pkg_sum:
return {}
root = tempfile.mkdtemp()
s_pkg = tarfile.open(pkg_path, 'r:gz')
# Verify that the tarball does not extract outside of the intended root
members = s_pkg.getmembers()
for member in members:
if salt.utils.stringutils.to_unicode(member.path).startswith((os.sep, '..{0}'.format(os.sep))):
return {}
elif '..{0}'.format(os.sep) in salt.utils.stringutils.to_unicode(member.path):
return {}
s_pkg.extractall(root)
s_pkg.close()
lowstate_json = os.path.join(root, 'lowstate.json')
with salt.utils.files.fopen(lowstate_json, 'r') as fp_:
lowstate = salt.utils.json.load(fp_)
# Check for errors in the lowstate
for chunk in lowstate:
if not isinstance(chunk, dict):
return lowstate
pillar_json = os.path.join(root, 'pillar.json')
if os.path.isfile(pillar_json):
with salt.utils.files.fopen(pillar_json, 'r') as fp_:
pillar_override = salt.utils.json.load(fp_)
else:
pillar_override = None
roster_grains_json = os.path.join(root, 'roster_grains.json')
if os.path.isfile(roster_grains_json):
with salt.utils.files.fopen(roster_grains_json, 'r') as fp_:
roster_grains = salt.utils.json.load(fp_)
if os.path.isfile(roster_grains_json):
popts['grains'] = roster_grains
popts['fileclient'] = 'local'
popts['file_roots'] = {}
popts['test'] = _get_test_value(test, **kwargs)
envs = os.listdir(root)
for fn_ in envs:
full = os.path.join(root, fn_)
if not os.path.isdir(full):
continue
popts['file_roots'][fn_] = [full]
st_ = salt.state.State(popts, pillar_override=pillar_override)
snapper_pre = _snapper_pre(popts, kwargs.get('__pub_jid', 'called localy'))
ret = st_.call_chunks(lowstate)
ret = st_.call_listen(lowstate, ret)
try:
shutil.rmtree(root)
except (IOError, OSError):
pass
_set_retcode(ret)
_snapper_post(popts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
return ret | python | def pkg(pkg_path,
pkg_sum,
hash_type,
test=None,
**kwargs):
'''
Execute a packaged state run, the packaged state run will exist in a
tarball available locally. This packaged state
can be generated using salt-ssh.
CLI Example:
.. code-block:: bash
salt '*' state.pkg /tmp/salt_state.tgz 760a9353810e36f6d81416366fc426dc md5
'''
# TODO - Add ability to download from salt master or other source
popts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
if not os.path.isfile(pkg_path):
return {}
if not salt.utils.hashutils.get_hash(pkg_path, hash_type) == pkg_sum:
return {}
root = tempfile.mkdtemp()
s_pkg = tarfile.open(pkg_path, 'r:gz')
# Verify that the tarball does not extract outside of the intended root
members = s_pkg.getmembers()
for member in members:
if salt.utils.stringutils.to_unicode(member.path).startswith((os.sep, '..{0}'.format(os.sep))):
return {}
elif '..{0}'.format(os.sep) in salt.utils.stringutils.to_unicode(member.path):
return {}
s_pkg.extractall(root)
s_pkg.close()
lowstate_json = os.path.join(root, 'lowstate.json')
with salt.utils.files.fopen(lowstate_json, 'r') as fp_:
lowstate = salt.utils.json.load(fp_)
# Check for errors in the lowstate
for chunk in lowstate:
if not isinstance(chunk, dict):
return lowstate
pillar_json = os.path.join(root, 'pillar.json')
if os.path.isfile(pillar_json):
with salt.utils.files.fopen(pillar_json, 'r') as fp_:
pillar_override = salt.utils.json.load(fp_)
else:
pillar_override = None
roster_grains_json = os.path.join(root, 'roster_grains.json')
if os.path.isfile(roster_grains_json):
with salt.utils.files.fopen(roster_grains_json, 'r') as fp_:
roster_grains = salt.utils.json.load(fp_)
if os.path.isfile(roster_grains_json):
popts['grains'] = roster_grains
popts['fileclient'] = 'local'
popts['file_roots'] = {}
popts['test'] = _get_test_value(test, **kwargs)
envs = os.listdir(root)
for fn_ in envs:
full = os.path.join(root, fn_)
if not os.path.isdir(full):
continue
popts['file_roots'][fn_] = [full]
st_ = salt.state.State(popts, pillar_override=pillar_override)
snapper_pre = _snapper_pre(popts, kwargs.get('__pub_jid', 'called localy'))
ret = st_.call_chunks(lowstate)
ret = st_.call_listen(lowstate, ret)
try:
shutil.rmtree(root)
except (IOError, OSError):
pass
_set_retcode(ret)
_snapper_post(popts, kwargs.get('__pub_jid', 'called localy'), snapper_pre)
return ret | [
"def",
"pkg",
"(",
"pkg_path",
",",
"pkg_sum",
",",
"hash_type",
",",
"test",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO - Add ability to download from salt master or other source",
"popts",
"=",
"salt",
".",
"utils",
".",
"state",
".",
"get_sls_opt... | Execute a packaged state run, the packaged state run will exist in a
tarball available locally. This packaged state
can be generated using salt-ssh.
CLI Example:
.. code-block:: bash
salt '*' state.pkg /tmp/salt_state.tgz 760a9353810e36f6d81416366fc426dc md5 | [
"Execute",
"a",
"packaged",
"state",
"run",
"the",
"packaged",
"state",
"run",
"will",
"exist",
"in",
"a",
"tarball",
"available",
"locally",
".",
"This",
"packaged",
"state",
"can",
"be",
"generated",
"using",
"salt",
"-",
"ssh",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2127-L2200 | train |
saltstack/salt | salt/modules/state.py | disable | def disable(states):
'''
Disable state runs.
CLI Example:
.. code-block:: bash
salt '*' state.disable highstate
salt '*' state.disable highstate,test.succeed_without_changes
.. note::
To disable a state file from running provide the same name that would
be passed in a state.sls call.
salt '*' state.disable bind.config
'''
ret = {
'res': True,
'msg': ''
}
states = salt.utils.args.split_input(states)
msg = []
_disabled = __salt__['grains.get']('state_runs_disabled')
if not isinstance(_disabled, list):
_disabled = []
_changed = False
for _state in states:
if _state in _disabled:
msg.append('Info: {0} state already disabled.'.format(_state))
else:
msg.append('Info: {0} state disabled.'.format(_state))
_disabled.append(_state)
_changed = True
if _changed:
__salt__['grains.setval']('state_runs_disabled', _disabled)
ret['msg'] = '\n'.join(msg)
# refresh the grains
__salt__['saltutil.refresh_modules']()
return ret | python | def disable(states):
'''
Disable state runs.
CLI Example:
.. code-block:: bash
salt '*' state.disable highstate
salt '*' state.disable highstate,test.succeed_without_changes
.. note::
To disable a state file from running provide the same name that would
be passed in a state.sls call.
salt '*' state.disable bind.config
'''
ret = {
'res': True,
'msg': ''
}
states = salt.utils.args.split_input(states)
msg = []
_disabled = __salt__['grains.get']('state_runs_disabled')
if not isinstance(_disabled, list):
_disabled = []
_changed = False
for _state in states:
if _state in _disabled:
msg.append('Info: {0} state already disabled.'.format(_state))
else:
msg.append('Info: {0} state disabled.'.format(_state))
_disabled.append(_state)
_changed = True
if _changed:
__salt__['grains.setval']('state_runs_disabled', _disabled)
ret['msg'] = '\n'.join(msg)
# refresh the grains
__salt__['saltutil.refresh_modules']()
return ret | [
"def",
"disable",
"(",
"states",
")",
":",
"ret",
"=",
"{",
"'res'",
":",
"True",
",",
"'msg'",
":",
"''",
"}",
"states",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"split_input",
"(",
"states",
")",
"msg",
"=",
"[",
"]",
"_disabled",
"=",
"__s... | Disable state runs.
CLI Example:
.. code-block:: bash
salt '*' state.disable highstate
salt '*' state.disable highstate,test.succeed_without_changes
.. note::
To disable a state file from running provide the same name that would
be passed in a state.sls call.
salt '*' state.disable bind.config | [
"Disable",
"state",
"runs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2203-L2251 | train |
saltstack/salt | salt/modules/state.py | enable | def enable(states):
'''
Enable state function or sls run
CLI Example:
.. code-block:: bash
salt '*' state.enable highstate
salt '*' state.enable test.succeed_without_changes
.. note::
To enable a state file from running provide the same name that would
be passed in a state.sls call.
salt '*' state.disable bind.config
'''
ret = {
'res': True,
'msg': ''
}
states = salt.utils.args.split_input(states)
log.debug('states %s', states)
msg = []
_disabled = __salt__['grains.get']('state_runs_disabled')
if not isinstance(_disabled, list):
_disabled = []
_changed = False
for _state in states:
log.debug('_state %s', _state)
if _state not in _disabled:
msg.append('Info: {0} state already enabled.'.format(_state))
else:
msg.append('Info: {0} state enabled.'.format(_state))
_disabled.remove(_state)
_changed = True
if _changed:
__salt__['grains.setval']('state_runs_disabled', _disabled)
ret['msg'] = '\n'.join(msg)
# refresh the grains
__salt__['saltutil.refresh_modules']()
return ret | python | def enable(states):
'''
Enable state function or sls run
CLI Example:
.. code-block:: bash
salt '*' state.enable highstate
salt '*' state.enable test.succeed_without_changes
.. note::
To enable a state file from running provide the same name that would
be passed in a state.sls call.
salt '*' state.disable bind.config
'''
ret = {
'res': True,
'msg': ''
}
states = salt.utils.args.split_input(states)
log.debug('states %s', states)
msg = []
_disabled = __salt__['grains.get']('state_runs_disabled')
if not isinstance(_disabled, list):
_disabled = []
_changed = False
for _state in states:
log.debug('_state %s', _state)
if _state not in _disabled:
msg.append('Info: {0} state already enabled.'.format(_state))
else:
msg.append('Info: {0} state enabled.'.format(_state))
_disabled.remove(_state)
_changed = True
if _changed:
__salt__['grains.setval']('state_runs_disabled', _disabled)
ret['msg'] = '\n'.join(msg)
# refresh the grains
__salt__['saltutil.refresh_modules']()
return ret | [
"def",
"enable",
"(",
"states",
")",
":",
"ret",
"=",
"{",
"'res'",
":",
"True",
",",
"'msg'",
":",
"''",
"}",
"states",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"split_input",
"(",
"states",
")",
"log",
".",
"debug",
"(",
"'states %s'",
",",
... | Enable state function or sls run
CLI Example:
.. code-block:: bash
salt '*' state.enable highstate
salt '*' state.enable test.succeed_without_changes
.. note::
To enable a state file from running provide the same name that would
be passed in a state.sls call.
salt '*' state.disable bind.config | [
"Enable",
"state",
"function",
"or",
"sls",
"run"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2254-L2304 | train |
saltstack/salt | salt/modules/state.py | _disabled | def _disabled(funs):
'''
Return messages for disabled states
that match state functions in funs.
'''
ret = []
_disabled = __salt__['grains.get']('state_runs_disabled')
for state in funs:
for _state in _disabled:
if '.*' in _state:
target_state = _state.split('.')[0]
target_state = target_state + '.' if not target_state.endswith('.') else target_state
if state.startswith(target_state):
err = (
'The state file "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state,
_state,
)
ret.append(err)
continue
else:
if _state == state:
err = (
'The state file "{0}" is currently disabled, '
'to re-enable, run state.enable {0}.'
).format(
_state,
)
ret.append(err)
continue
return ret | python | def _disabled(funs):
'''
Return messages for disabled states
that match state functions in funs.
'''
ret = []
_disabled = __salt__['grains.get']('state_runs_disabled')
for state in funs:
for _state in _disabled:
if '.*' in _state:
target_state = _state.split('.')[0]
target_state = target_state + '.' if not target_state.endswith('.') else target_state
if state.startswith(target_state):
err = (
'The state file "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state,
_state,
)
ret.append(err)
continue
else:
if _state == state:
err = (
'The state file "{0}" is currently disabled, '
'to re-enable, run state.enable {0}.'
).format(
_state,
)
ret.append(err)
continue
return ret | [
"def",
"_disabled",
"(",
"funs",
")",
":",
"ret",
"=",
"[",
"]",
"_disabled",
"=",
"__salt__",
"[",
"'grains.get'",
"]",
"(",
"'state_runs_disabled'",
")",
"for",
"state",
"in",
"funs",
":",
"for",
"_state",
"in",
"_disabled",
":",
"if",
"'.*'",
"in",
... | Return messages for disabled states
that match state functions in funs. | [
"Return",
"messages",
"for",
"disabled",
"states",
"that",
"match",
"state",
"functions",
"in",
"funs",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2320-L2352 | train |
saltstack/salt | salt/modules/state.py | event | def event(tagmatch='*',
count=-1,
quiet=False,
sock_dir=None,
pretty=False,
node='minion'):
r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly from the CLI.
Enable debug logging to see ignored events.
:param tagmatch: the event is written to stdout for each tag that matches
this glob or regular expression.
:param count: this number is decremented for each event that matches the
``tagmatch`` parameter; pass ``-1`` to listen forever.
:param quiet: do not print to stdout; just block
:param sock_dir: path to the Salt master's event socket file.
:param pretty: Output the JSON all on a single line if ``False`` (useful
for shell tools); pretty-print the JSON output if ``True``.
:param node: Watch the minion-side or master-side event bus.
CLI Example:
.. code-block:: bash
salt-call --local state.event pretty=True
'''
sevent = salt.utils.event.get_event(
node,
sock_dir or __opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
while True:
ret = sevent.get_event(full=True, auto_reconnect=True)
if ret is None:
continue
if salt.utils.stringutils.expr_match(ret['tag'], tagmatch):
if not quiet:
salt.utils.stringutils.print_cli(
str('{0}\t{1}').format( # future lint: blacklisted-function
salt.utils.stringutils.to_str(ret['tag']),
salt.utils.json.dumps(
ret['data'],
sort_keys=pretty,
indent=None if not pretty else 4)
)
)
sys.stdout.flush()
if count > 0:
count -= 1
log.debug('Remaining event matches: %s', count)
if count == 0:
break
else:
log.debug('Skipping event tag: %s', ret['tag'])
continue | python | def event(tagmatch='*',
count=-1,
quiet=False,
sock_dir=None,
pretty=False,
node='minion'):
r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly from the CLI.
Enable debug logging to see ignored events.
:param tagmatch: the event is written to stdout for each tag that matches
this glob or regular expression.
:param count: this number is decremented for each event that matches the
``tagmatch`` parameter; pass ``-1`` to listen forever.
:param quiet: do not print to stdout; just block
:param sock_dir: path to the Salt master's event socket file.
:param pretty: Output the JSON all on a single line if ``False`` (useful
for shell tools); pretty-print the JSON output if ``True``.
:param node: Watch the minion-side or master-side event bus.
CLI Example:
.. code-block:: bash
salt-call --local state.event pretty=True
'''
sevent = salt.utils.event.get_event(
node,
sock_dir or __opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=True)
while True:
ret = sevent.get_event(full=True, auto_reconnect=True)
if ret is None:
continue
if salt.utils.stringutils.expr_match(ret['tag'], tagmatch):
if not quiet:
salt.utils.stringutils.print_cli(
str('{0}\t{1}').format( # future lint: blacklisted-function
salt.utils.stringutils.to_str(ret['tag']),
salt.utils.json.dumps(
ret['data'],
sort_keys=pretty,
indent=None if not pretty else 4)
)
)
sys.stdout.flush()
if count > 0:
count -= 1
log.debug('Remaining event matches: %s', count)
if count == 0:
break
else:
log.debug('Skipping event tag: %s', ret['tag'])
continue | [
"def",
"event",
"(",
"tagmatch",
"=",
"'*'",
",",
"count",
"=",
"-",
"1",
",",
"quiet",
"=",
"False",
",",
"sock_dir",
"=",
"None",
",",
"pretty",
"=",
"False",
",",
"node",
"=",
"'minion'",
")",
":",
"sevent",
"=",
"salt",
".",
"utils",
".",
"ev... | r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly from the CLI.
Enable debug logging to see ignored events.
:param tagmatch: the event is written to stdout for each tag that matches
this glob or regular expression.
:param count: this number is decremented for each event that matches the
``tagmatch`` parameter; pass ``-1`` to listen forever.
:param quiet: do not print to stdout; just block
:param sock_dir: path to the Salt master's event socket file.
:param pretty: Output the JSON all on a single line if ``False`` (useful
for shell tools); pretty-print the JSON output if ``True``.
:param node: Watch the minion-side or master-side event bus.
CLI Example:
.. code-block:: bash
salt-call --local state.event pretty=True | [
"r",
"Watch",
"Salt",
"s",
"event",
"bus",
"and",
"block",
"until",
"the",
"given",
"tag",
"is",
"matched"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L2355-L2422 | train |
saltstack/salt | salt/states/grains.py | exists | def exists(name, delimiter=DEFAULT_TARGET_DELIM):
'''
Ensure that a grain is set
name
The grain name
delimiter
A delimiter different from the default can be provided.
Check whether a grain exists. Does not attempt to check or set the value.
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Grain exists'}
_non_existent = object()
existing = __salt__['grains.get'](name, _non_existent)
if existing is _non_existent:
ret['result'] = False
ret['comment'] = 'Grain does not exist'
return ret | python | def exists(name, delimiter=DEFAULT_TARGET_DELIM):
'''
Ensure that a grain is set
name
The grain name
delimiter
A delimiter different from the default can be provided.
Check whether a grain exists. Does not attempt to check or set the value.
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Grain exists'}
_non_existent = object()
existing = __salt__['grains.get'](name, _non_existent)
if existing is _non_existent:
ret['result'] = False
ret['comment'] = 'Grain does not exist'
return ret | [
"def",
"exists",
"(",
"name",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"delimiter",
",",
"DEFAULT_TARGET_DELIM",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"... | Ensure that a grain is set
name
The grain name
delimiter
A delimiter different from the default can be provided.
Check whether a grain exists. Does not attempt to check or set the value. | [
"Ensure",
"that",
"a",
"grain",
"is",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grains.py#L23-L45 | train |
saltstack/salt | salt/states/grains.py | present | def present(name, value, delimiter=DEFAULT_TARGET_DELIM, force=False):
'''
Ensure that a grain is set
.. versionchanged:: v2015.8.2
name
The grain name
value
The value to set on the grain
force
If force is True, the existing grain will be overwritten
regardless of its existing or provided value type. Defaults to False
.. versionadded:: v2015.8.2
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
It is now capable to set a grain to a complex value (ie. lists and dicts)
and supports nested grains as well.
If the grain does not yet exist, a new grain is set to the given value. For
a nested grain, the necessary keys are created if they don't exist. If
a given key is an existing value, it will be converted, but an existing value
different from the given key will fail the state.
If the grain with the given name exists, its value is updated to the new
value unless its existing or provided value is complex (list or dict). Use
`force: True` to overwrite.
.. code-block:: yaml
cheese:
grains.present:
- value: edam
nested_grain_with_complex_value:
grains.present:
- name: icinga:Apache SSL
- value:
- command: check_https
- params: -H localhost -p 443 -S
with,a,custom,delimiter:
grains.present:
- value: yay
- delimiter: ','
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
_non_existent = object()
existing = __salt__['grains.get'](name, _non_existent)
if existing == value:
ret['comment'] = 'Grain is already set'
return ret
if __opts__['test']:
ret['result'] = None
if existing is _non_existent:
ret['comment'] = 'Grain {0} is set to be added'.format(name)
ret['changes'] = {'new': name}
else:
ret['comment'] = 'Grain {0} is set to be changed'.format(name)
ret['changes'] = {'changed': {name: value}}
return ret
ret = __salt__['grains.set'](name, value, force=force)
if ret['result'] is True and ret['changes'] != {}:
ret['comment'] = 'Set grain {0} to {1}'.format(name, value)
ret['name'] = name
return ret | python | def present(name, value, delimiter=DEFAULT_TARGET_DELIM, force=False):
'''
Ensure that a grain is set
.. versionchanged:: v2015.8.2
name
The grain name
value
The value to set on the grain
force
If force is True, the existing grain will be overwritten
regardless of its existing or provided value type. Defaults to False
.. versionadded:: v2015.8.2
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
It is now capable to set a grain to a complex value (ie. lists and dicts)
and supports nested grains as well.
If the grain does not yet exist, a new grain is set to the given value. For
a nested grain, the necessary keys are created if they don't exist. If
a given key is an existing value, it will be converted, but an existing value
different from the given key will fail the state.
If the grain with the given name exists, its value is updated to the new
value unless its existing or provided value is complex (list or dict). Use
`force: True` to overwrite.
.. code-block:: yaml
cheese:
grains.present:
- value: edam
nested_grain_with_complex_value:
grains.present:
- name: icinga:Apache SSL
- value:
- command: check_https
- params: -H localhost -p 443 -S
with,a,custom,delimiter:
grains.present:
- value: yay
- delimiter: ','
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
_non_existent = object()
existing = __salt__['grains.get'](name, _non_existent)
if existing == value:
ret['comment'] = 'Grain is already set'
return ret
if __opts__['test']:
ret['result'] = None
if existing is _non_existent:
ret['comment'] = 'Grain {0} is set to be added'.format(name)
ret['changes'] = {'new': name}
else:
ret['comment'] = 'Grain {0} is set to be changed'.format(name)
ret['changes'] = {'changed': {name: value}}
return ret
ret = __salt__['grains.set'](name, value, force=force)
if ret['result'] is True and ret['changes'] != {}:
ret['comment'] = 'Set grain {0} to {1}'.format(name, value)
ret['name'] = name
return ret | [
"def",
"present",
"(",
"name",
",",
"value",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
",",
"force",
"=",
"False",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"delimiter",
",",
"DEFAULT_TARGET_DELIM",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
... | Ensure that a grain is set
.. versionchanged:: v2015.8.2
name
The grain name
value
The value to set on the grain
force
If force is True, the existing grain will be overwritten
regardless of its existing or provided value type. Defaults to False
.. versionadded:: v2015.8.2
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
It is now capable to set a grain to a complex value (ie. lists and dicts)
and supports nested grains as well.
If the grain does not yet exist, a new grain is set to the given value. For
a nested grain, the necessary keys are created if they don't exist. If
a given key is an existing value, it will be converted, but an existing value
different from the given key will fail the state.
If the grain with the given name exists, its value is updated to the new
value unless its existing or provided value is complex (list or dict). Use
`force: True` to overwrite.
.. code-block:: yaml
cheese:
grains.present:
- value: edam
nested_grain_with_complex_value:
grains.present:
- name: icinga:Apache SSL
- value:
- command: check_https
- params: -H localhost -p 443 -S
with,a,custom,delimiter:
grains.present:
- value: yay
- delimiter: ',' | [
"Ensure",
"that",
"a",
"grain",
"is",
"set"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grains.py#L48-L124 | train |
saltstack/salt | salt/states/grains.py | list_present | def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2014.1.0
Ensure the value is present in the list-type grain. Note: If the grain that is
provided in ``name`` is not present on the system, this new grain will be created
with the corresponding provided value.
name
The grain name.
value
The value is present in the list type grain.
delimiter
A delimiter different from the default ``:`` can be provided.
.. versionadded:: v2015.8.2
The grain should be `list type <http://docs.python.org/2/tutorial/datastructures.html#data-structures>`_
.. code-block:: yaml
roles:
grains.list_present:
- value: web
For multiple grains, the syntax looks like:
.. code-block:: yaml
roles:
grains.list_present:
- value:
- web
- dev
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grain = __salt__['grains.get'](name)
if grain:
# check whether grain is a list
if not isinstance(grain, list):
ret['result'] = False
ret['comment'] = 'Grain {0} is not a valid list'.format(name)
return ret
if isinstance(value, list):
if set(value).issubset(set(__salt__['grains.get'](name))):
ret['comment'] = 'Value {1} is already in grain {0}'.format(name, value)
return ret
elif name in __context__.get('pending_grains', {}):
# elements common to both
intersection = set(value).intersection(__context__.get('pending_grains', {})[name])
if intersection:
value = list(set(value).difference(__context__['pending_grains'][name]))
ret['comment'] = 'Removed value {0} from update due to context found in "{1}".\n'.format(value, name)
if 'pending_grains' not in __context__:
__context__['pending_grains'] = {}
if name not in __context__['pending_grains']:
__context__['pending_grains'][name] = set()
__context__['pending_grains'][name].update(value)
else:
if value in grain:
ret['comment'] = 'Value {1} is already in grain {0}'.format(name, value)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value {1} is set to be appended to grain {0}'.format(name, value)
ret['changes'] = {'new': grain}
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Grain {0} is set to be added'.format(name)
ret['changes'] = {'new': grain}
return ret
new_grains = __salt__['grains.append'](name, value)
if isinstance(value, list):
if not set(value).issubset(set(__salt__['grains.get'](name))):
ret['result'] = False
ret['comment'] = 'Failed append value {1} to grain {0}'.format(name, value)
return ret
else:
if value not in __salt__['grains.get'](name, delimiter=DEFAULT_TARGET_DELIM):
ret['result'] = False
ret['comment'] = 'Failed append value {1} to grain {0}'.format(name, value)
return ret
ret['comment'] = 'Append value {1} to grain {0}'.format(name, value)
ret['changes'] = {'new': new_grains}
return ret | python | def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2014.1.0
Ensure the value is present in the list-type grain. Note: If the grain that is
provided in ``name`` is not present on the system, this new grain will be created
with the corresponding provided value.
name
The grain name.
value
The value is present in the list type grain.
delimiter
A delimiter different from the default ``:`` can be provided.
.. versionadded:: v2015.8.2
The grain should be `list type <http://docs.python.org/2/tutorial/datastructures.html#data-structures>`_
.. code-block:: yaml
roles:
grains.list_present:
- value: web
For multiple grains, the syntax looks like:
.. code-block:: yaml
roles:
grains.list_present:
- value:
- web
- dev
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grain = __salt__['grains.get'](name)
if grain:
# check whether grain is a list
if not isinstance(grain, list):
ret['result'] = False
ret['comment'] = 'Grain {0} is not a valid list'.format(name)
return ret
if isinstance(value, list):
if set(value).issubset(set(__salt__['grains.get'](name))):
ret['comment'] = 'Value {1} is already in grain {0}'.format(name, value)
return ret
elif name in __context__.get('pending_grains', {}):
# elements common to both
intersection = set(value).intersection(__context__.get('pending_grains', {})[name])
if intersection:
value = list(set(value).difference(__context__['pending_grains'][name]))
ret['comment'] = 'Removed value {0} from update due to context found in "{1}".\n'.format(value, name)
if 'pending_grains' not in __context__:
__context__['pending_grains'] = {}
if name not in __context__['pending_grains']:
__context__['pending_grains'][name] = set()
__context__['pending_grains'][name].update(value)
else:
if value in grain:
ret['comment'] = 'Value {1} is already in grain {0}'.format(name, value)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value {1} is set to be appended to grain {0}'.format(name, value)
ret['changes'] = {'new': grain}
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Grain {0} is set to be added'.format(name)
ret['changes'] = {'new': grain}
return ret
new_grains = __salt__['grains.append'](name, value)
if isinstance(value, list):
if not set(value).issubset(set(__salt__['grains.get'](name))):
ret['result'] = False
ret['comment'] = 'Failed append value {1} to grain {0}'.format(name, value)
return ret
else:
if value not in __salt__['grains.get'](name, delimiter=DEFAULT_TARGET_DELIM):
ret['result'] = False
ret['comment'] = 'Failed append value {1} to grain {0}'.format(name, value)
return ret
ret['comment'] = 'Append value {1} to grain {0}'.format(name, value)
ret['changes'] = {'new': new_grains}
return ret | [
"def",
"list_present",
"(",
"name",
",",
"value",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"delimiter",
",",
"DEFAULT_TARGET_DELIM",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'chan... | .. versionadded:: 2014.1.0
Ensure the value is present in the list-type grain. Note: If the grain that is
provided in ``name`` is not present on the system, this new grain will be created
with the corresponding provided value.
name
The grain name.
value
The value is present in the list type grain.
delimiter
A delimiter different from the default ``:`` can be provided.
.. versionadded:: v2015.8.2
The grain should be `list type <http://docs.python.org/2/tutorial/datastructures.html#data-structures>`_
.. code-block:: yaml
roles:
grains.list_present:
- value: web
For multiple grains, the syntax looks like:
.. code-block:: yaml
roles:
grains.list_present:
- value:
- web
- dev | [
"..",
"versionadded",
"::",
"2014",
".",
"1",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grains.py#L127-L219 | train |
saltstack/salt | salt/states/grains.py | list_absent | def list_absent(name, value, delimiter=DEFAULT_TARGET_DELIM):
'''
Delete a value from a grain formed as a list.
.. versionadded:: 2014.1.0
name
The grain name.
value
The value to delete from the grain list.
delimiter
A delimiter different from the default ``:`` can be provided.
.. versionadded:: v2015.8.2
The grain should be `list type <http://docs.python.org/2/tutorial/datastructures.html#data-structures>`_
.. code-block:: yaml
roles:
grains.list_absent:
- value: db
For multiple grains, the syntax looks like:
.. code-block:: yaml
roles:
grains.list_absent:
- value:
- web
- dev
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
comments = []
grain = __salt__['grains.get'](name, None)
if grain:
if isinstance(grain, list):
if not isinstance(value, list):
value = [value]
for val in value:
if val not in grain:
comments.append('Value {1} is absent from '
'grain {0}'.format(name, val))
elif __opts__['test']:
ret['result'] = None
comments.append('Value {1} in grain {0} is set '
'to be deleted'.format(name, val))
if 'deleted' not in ret['changes'].keys():
ret['changes'] = {'deleted': []}
ret['changes']['deleted'].append(val)
elif val in grain:
__salt__['grains.remove'](name, val)
comments.append('Value {1} was deleted from '
'grain {0}'.format(name, val))
if 'deleted' not in ret['changes'].keys():
ret['changes'] = {'deleted': []}
ret['changes']['deleted'].append(val)
ret['comment'] = '\n'.join(comments)
return ret
else:
ret['result'] = False
ret['comment'] = 'Grain {0} is not a valid list'\
.format(name)
else:
ret['comment'] = 'Grain {0} does not exist'.format(name)
return ret | python | def list_absent(name, value, delimiter=DEFAULT_TARGET_DELIM):
'''
Delete a value from a grain formed as a list.
.. versionadded:: 2014.1.0
name
The grain name.
value
The value to delete from the grain list.
delimiter
A delimiter different from the default ``:`` can be provided.
.. versionadded:: v2015.8.2
The grain should be `list type <http://docs.python.org/2/tutorial/datastructures.html#data-structures>`_
.. code-block:: yaml
roles:
grains.list_absent:
- value: db
For multiple grains, the syntax looks like:
.. code-block:: yaml
roles:
grains.list_absent:
- value:
- web
- dev
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
comments = []
grain = __salt__['grains.get'](name, None)
if grain:
if isinstance(grain, list):
if not isinstance(value, list):
value = [value]
for val in value:
if val not in grain:
comments.append('Value {1} is absent from '
'grain {0}'.format(name, val))
elif __opts__['test']:
ret['result'] = None
comments.append('Value {1} in grain {0} is set '
'to be deleted'.format(name, val))
if 'deleted' not in ret['changes'].keys():
ret['changes'] = {'deleted': []}
ret['changes']['deleted'].append(val)
elif val in grain:
__salt__['grains.remove'](name, val)
comments.append('Value {1} was deleted from '
'grain {0}'.format(name, val))
if 'deleted' not in ret['changes'].keys():
ret['changes'] = {'deleted': []}
ret['changes']['deleted'].append(val)
ret['comment'] = '\n'.join(comments)
return ret
else:
ret['result'] = False
ret['comment'] = 'Grain {0} is not a valid list'\
.format(name)
else:
ret['comment'] = 'Grain {0} does not exist'.format(name)
return ret | [
"def",
"list_absent",
"(",
"name",
",",
"value",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"delimiter",
",",
"DEFAULT_TARGET_DELIM",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'chang... | Delete a value from a grain formed as a list.
.. versionadded:: 2014.1.0
name
The grain name.
value
The value to delete from the grain list.
delimiter
A delimiter different from the default ``:`` can be provided.
.. versionadded:: v2015.8.2
The grain should be `list type <http://docs.python.org/2/tutorial/datastructures.html#data-structures>`_
.. code-block:: yaml
roles:
grains.list_absent:
- value: db
For multiple grains, the syntax looks like:
.. code-block:: yaml
roles:
grains.list_absent:
- value:
- web
- dev | [
"Delete",
"a",
"value",
"from",
"a",
"grain",
"formed",
"as",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grains.py#L222-L295 | train |
saltstack/salt | salt/states/grains.py | absent | def absent(name,
destructive=False,
delimiter=DEFAULT_TARGET_DELIM,
force=False):
'''
.. versionadded:: 2014.7.0
Delete a grain from the grains config file
name
The grain name
destructive
If destructive is True, delete the entire grain. If
destructive is False, set the grain's value to None. Defaults to False.
force
If force is True, the existing grain will be overwritten
regardless of its existing or provided value type. Defaults to False
.. versionadded:: v2015.8.2
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
.. versionchanged:: v2015.8.2
This state now support nested grains and complex values. It is also more
conservative: if a grain has a value that is a list or a dict, it will
not be removed unless the `force` parameter is True.
.. code-block:: yaml
grain_name:
grains.absent
'''
_non_existent = object()
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grain = __salt__['grains.get'](name, _non_existent)
if grain is None:
if __opts__['test']:
ret['result'] = None
if destructive is True:
ret['comment'] = 'Grain {0} is set to be deleted'.format(name)
ret['changes'] = {'deleted': name}
return ret
ret = __salt__['grains.set'](name,
None,
destructive=destructive,
force=force)
if ret['result']:
if destructive is True:
ret['comment'] = 'Grain {0} was deleted'.format(name)
ret['changes'] = {'deleted': name}
ret['name'] = name
elif grain is not _non_existent:
if __opts__['test']:
ret['result'] = None
if destructive is True:
ret['comment'] = 'Grain {0} is set to be deleted'.format(name)
ret['changes'] = {'deleted': name}
else:
ret['comment'] = 'Value for grain {0} is set to be ' \
'deleted (None)'.format(name)
ret['changes'] = {'grain': name, 'value': None}
return ret
ret = __salt__['grains.set'](name,
None,
destructive=destructive,
force=force)
if ret['result']:
if destructive is True:
ret['comment'] = 'Grain {0} was deleted'.format(name)
ret['changes'] = {'deleted': name}
else:
ret['comment'] = 'Value for grain {0} was set to None'.format(name)
ret['changes'] = {'grain': name, 'value': None}
ret['name'] = name
else:
ret['comment'] = 'Grain {0} does not exist'.format(name)
return ret | python | def absent(name,
destructive=False,
delimiter=DEFAULT_TARGET_DELIM,
force=False):
'''
.. versionadded:: 2014.7.0
Delete a grain from the grains config file
name
The grain name
destructive
If destructive is True, delete the entire grain. If
destructive is False, set the grain's value to None. Defaults to False.
force
If force is True, the existing grain will be overwritten
regardless of its existing or provided value type. Defaults to False
.. versionadded:: v2015.8.2
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
.. versionchanged:: v2015.8.2
This state now support nested grains and complex values. It is also more
conservative: if a grain has a value that is a list or a dict, it will
not be removed unless the `force` parameter is True.
.. code-block:: yaml
grain_name:
grains.absent
'''
_non_existent = object()
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grain = __salt__['grains.get'](name, _non_existent)
if grain is None:
if __opts__['test']:
ret['result'] = None
if destructive is True:
ret['comment'] = 'Grain {0} is set to be deleted'.format(name)
ret['changes'] = {'deleted': name}
return ret
ret = __salt__['grains.set'](name,
None,
destructive=destructive,
force=force)
if ret['result']:
if destructive is True:
ret['comment'] = 'Grain {0} was deleted'.format(name)
ret['changes'] = {'deleted': name}
ret['name'] = name
elif grain is not _non_existent:
if __opts__['test']:
ret['result'] = None
if destructive is True:
ret['comment'] = 'Grain {0} is set to be deleted'.format(name)
ret['changes'] = {'deleted': name}
else:
ret['comment'] = 'Value for grain {0} is set to be ' \
'deleted (None)'.format(name)
ret['changes'] = {'grain': name, 'value': None}
return ret
ret = __salt__['grains.set'](name,
None,
destructive=destructive,
force=force)
if ret['result']:
if destructive is True:
ret['comment'] = 'Grain {0} was deleted'.format(name)
ret['changes'] = {'deleted': name}
else:
ret['comment'] = 'Value for grain {0} was set to None'.format(name)
ret['changes'] = {'grain': name, 'value': None}
ret['name'] = name
else:
ret['comment'] = 'Grain {0} does not exist'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"destructive",
"=",
"False",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
",",
"force",
"=",
"False",
")",
":",
"_non_existent",
"=",
"object",
"(",
")",
"name",
"=",
"re",
".",
"sub",
"(",
"delimiter",
",",
"DEFAULT_... | .. versionadded:: 2014.7.0
Delete a grain from the grains config file
name
The grain name
destructive
If destructive is True, delete the entire grain. If
destructive is False, set the grain's value to None. Defaults to False.
force
If force is True, the existing grain will be overwritten
regardless of its existing or provided value type. Defaults to False
.. versionadded:: v2015.8.2
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
.. versionchanged:: v2015.8.2
This state now support nested grains and complex values. It is also more
conservative: if a grain has a value that is a list or a dict, it will
not be removed unless the `force` parameter is True.
.. code-block:: yaml
grain_name:
grains.absent | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grains.py#L298-L386 | train |
saltstack/salt | salt/states/grains.py | append | def append(name, value, convert=False,
delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2014.7.0
Append a value to a list in the grains config file. The grain that is being
appended to (name) must exist before the new value can be added.
name
The grain name
value
The value to append
convert
If convert is True, convert non-list contents into a list.
If convert is False and the grain contains non-list contents, an error
is given. Defaults to False.
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
.. code-block:: yaml
grain_name:
grains.append:
- value: to_be_appended
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grain = __salt__['grains.get'](name, None)
# Check if bool(grain) is False or if the grain is specified in the minions
# grains. Grains can be set to a None value by omitting a value in the
# definition.
if grain or name in __grains__:
if isinstance(grain, list):
if value in grain:
ret['comment'] = 'Value {1} is already in the list ' \
'for grain {0}'.format(name, value)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value {1} in grain {0} is set to ' \
'be added'.format(name, value)
ret['changes'] = {'added': value}
return ret
__salt__['grains.append'](name, value)
ret['comment'] = 'Value {1} was added to grain {0}'.format(name, value)
ret['changes'] = {'added': value}
else:
if convert is True:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Grain {0} is set to be converted ' \
'to list and value {1} will be ' \
'added'.format(name, value)
ret['changes'] = {'added': value}
return ret
grain = [] if grain is None else [grain]
grain.append(value)
__salt__['grains.setval'](name, grain)
ret['comment'] = 'Value {1} was added to grain {0}'.format(name, value)
ret['changes'] = {'added': value}
else:
ret['result'] = False
ret['comment'] = 'Grain {0} is not a valid list'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Grain {0} does not exist'.format(name)
return ret | python | def append(name, value, convert=False,
delimiter=DEFAULT_TARGET_DELIM):
'''
.. versionadded:: 2014.7.0
Append a value to a list in the grains config file. The grain that is being
appended to (name) must exist before the new value can be added.
name
The grain name
value
The value to append
convert
If convert is True, convert non-list contents into a list.
If convert is False and the grain contains non-list contents, an error
is given. Defaults to False.
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
.. code-block:: yaml
grain_name:
grains.append:
- value: to_be_appended
'''
name = re.sub(delimiter, DEFAULT_TARGET_DELIM, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
grain = __salt__['grains.get'](name, None)
# Check if bool(grain) is False or if the grain is specified in the minions
# grains. Grains can be set to a None value by omitting a value in the
# definition.
if grain or name in __grains__:
if isinstance(grain, list):
if value in grain:
ret['comment'] = 'Value {1} is already in the list ' \
'for grain {0}'.format(name, value)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Value {1} in grain {0} is set to ' \
'be added'.format(name, value)
ret['changes'] = {'added': value}
return ret
__salt__['grains.append'](name, value)
ret['comment'] = 'Value {1} was added to grain {0}'.format(name, value)
ret['changes'] = {'added': value}
else:
if convert is True:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Grain {0} is set to be converted ' \
'to list and value {1} will be ' \
'added'.format(name, value)
ret['changes'] = {'added': value}
return ret
grain = [] if grain is None else [grain]
grain.append(value)
__salt__['grains.setval'](name, grain)
ret['comment'] = 'Value {1} was added to grain {0}'.format(name, value)
ret['changes'] = {'added': value}
else:
ret['result'] = False
ret['comment'] = 'Grain {0} is not a valid list'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Grain {0} does not exist'.format(name)
return ret | [
"def",
"append",
"(",
"name",
",",
"value",
",",
"convert",
"=",
"False",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"name",
"=",
"re",
".",
"sub",
"(",
"delimiter",
",",
"DEFAULT_TARGET_DELIM",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
... | .. versionadded:: 2014.7.0
Append a value to a list in the grains config file. The grain that is being
appended to (name) must exist before the new value can be added.
name
The grain name
value
The value to append
convert
If convert is True, convert non-list contents into a list.
If convert is False and the grain contains non-list contents, an error
is given. Defaults to False.
delimiter
A delimiter different from the default can be provided.
.. versionadded:: v2015.8.2
.. code-block:: yaml
grain_name:
grains.append:
- value: to_be_appended | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/grains.py#L389-L464 | train |
saltstack/salt | salt/modules/chocolatey.py | _clear_context | def _clear_context(context):
'''
Clear variables stored in __context__. Run this function when a new version
of chocolatey is installed.
'''
for var in (x for x in __context__ if x.startswith('chocolatey.')):
context.pop(var) | python | def _clear_context(context):
'''
Clear variables stored in __context__. Run this function when a new version
of chocolatey is installed.
'''
for var in (x for x in __context__ if x.startswith('chocolatey.')):
context.pop(var) | [
"def",
"_clear_context",
"(",
"context",
")",
":",
"for",
"var",
"in",
"(",
"x",
"for",
"x",
"in",
"__context__",
"if",
"x",
".",
"startswith",
"(",
"'chocolatey.'",
")",
")",
":",
"context",
".",
"pop",
"(",
"var",
")"
] | Clear variables stored in __context__. Run this function when a new version
of chocolatey is installed. | [
"Clear",
"variables",
"stored",
"in",
"__context__",
".",
"Run",
"this",
"function",
"when",
"a",
"new",
"version",
"of",
"chocolatey",
"is",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L51-L57 | train |
saltstack/salt | salt/modules/chocolatey.py | _yes | def _yes(context):
'''
Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list
'''
if 'chocolatey._yes' in __context__:
return context['chocolatey._yes']
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.9'):
answer = ['--yes']
else:
answer = []
context['chocolatey._yes'] = answer
return answer | python | def _yes(context):
'''
Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list
'''
if 'chocolatey._yes' in __context__:
return context['chocolatey._yes']
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.9'):
answer = ['--yes']
else:
answer = []
context['chocolatey._yes'] = answer
return answer | [
"def",
"_yes",
"(",
"context",
")",
":",
"if",
"'chocolatey._yes'",
"in",
"__context__",
":",
"return",
"context",
"[",
"'chocolatey._yes'",
"]",
"if",
"_LooseVersion",
"(",
"chocolatey_version",
"(",
")",
")",
">=",
"_LooseVersion",
"(",
"'0.9.9'",
")",
":",
... | Returns ['--yes'] if on v0.9.9.0 or later, otherwise returns an empty list | [
"Returns",
"[",
"--",
"yes",
"]",
"if",
"on",
"v0",
".",
"9",
".",
"9",
".",
"0",
"or",
"later",
"otherwise",
"returns",
"an",
"empty",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L60-L71 | train |
saltstack/salt | salt/modules/chocolatey.py | _no_progress | def _no_progress(context):
'''
Returns ['--no-progress'] if on v0.10.4 or later, otherwise returns an
empty list
'''
if 'chocolatey._no_progress' in __context__:
return context['chocolatey._no_progress']
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.10.4'):
answer = ['--no-progress']
else:
log.warning('--no-progress unsupported in choco < 0.10.4')
answer = []
context['chocolatey._no_progress'] = answer
return answer | python | def _no_progress(context):
'''
Returns ['--no-progress'] if on v0.10.4 or later, otherwise returns an
empty list
'''
if 'chocolatey._no_progress' in __context__:
return context['chocolatey._no_progress']
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.10.4'):
answer = ['--no-progress']
else:
log.warning('--no-progress unsupported in choco < 0.10.4')
answer = []
context['chocolatey._no_progress'] = answer
return answer | [
"def",
"_no_progress",
"(",
"context",
")",
":",
"if",
"'chocolatey._no_progress'",
"in",
"__context__",
":",
"return",
"context",
"[",
"'chocolatey._no_progress'",
"]",
"if",
"_LooseVersion",
"(",
"chocolatey_version",
"(",
")",
")",
">=",
"_LooseVersion",
"(",
"... | Returns ['--no-progress'] if on v0.10.4 or later, otherwise returns an
empty list | [
"Returns",
"[",
"--",
"no",
"-",
"progress",
"]",
"if",
"on",
"v0",
".",
"10",
".",
"4",
"or",
"later",
"otherwise",
"returns",
"an",
"empty",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L74-L87 | train |
saltstack/salt | salt/modules/chocolatey.py | _find_chocolatey | def _find_chocolatey(context, salt):
'''
Returns the full path to chocolatey.bat on the host.
'''
if 'chocolatey._path' in context:
return context['chocolatey._path']
choc_defaults = ['C:\\Chocolatey\\bin\\chocolatey.bat',
'C:\\ProgramData\\Chocolatey\\bin\\chocolatey.exe', ]
choc_path = salt['cmd.which']('chocolatey.exe')
if not choc_path:
for choc_dir in choc_defaults:
if salt['cmd.has_exec'](choc_dir):
choc_path = choc_dir
if not choc_path:
err = ('Chocolatey not installed. Use chocolatey.bootstrap to '
'install the Chocolatey package manager.')
raise CommandExecutionError(err)
context['chocolatey._path'] = choc_path
return choc_path | python | def _find_chocolatey(context, salt):
'''
Returns the full path to chocolatey.bat on the host.
'''
if 'chocolatey._path' in context:
return context['chocolatey._path']
choc_defaults = ['C:\\Chocolatey\\bin\\chocolatey.bat',
'C:\\ProgramData\\Chocolatey\\bin\\chocolatey.exe', ]
choc_path = salt['cmd.which']('chocolatey.exe')
if not choc_path:
for choc_dir in choc_defaults:
if salt['cmd.has_exec'](choc_dir):
choc_path = choc_dir
if not choc_path:
err = ('Chocolatey not installed. Use chocolatey.bootstrap to '
'install the Chocolatey package manager.')
raise CommandExecutionError(err)
context['chocolatey._path'] = choc_path
return choc_path | [
"def",
"_find_chocolatey",
"(",
"context",
",",
"salt",
")",
":",
"if",
"'chocolatey._path'",
"in",
"context",
":",
"return",
"context",
"[",
"'chocolatey._path'",
"]",
"choc_defaults",
"=",
"[",
"'C:\\\\Chocolatey\\\\bin\\\\chocolatey.bat'",
",",
"'C:\\\\ProgramData\\\... | Returns the full path to chocolatey.bat on the host. | [
"Returns",
"the",
"full",
"path",
"to",
"chocolatey",
".",
"bat",
"on",
"the",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L90-L109 | train |
saltstack/salt | salt/modules/chocolatey.py | chocolatey_version | def chocolatey_version():
'''
Returns the version of Chocolatey installed on the minion.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.chocolatey_version
'''
if 'chocolatey._version' in __context__:
return __context__['chocolatey._version']
cmd = [_find_chocolatey(__context__, __salt__)]
cmd.append('-v')
out = __salt__['cmd.run'](cmd, python_shell=False)
__context__['chocolatey._version'] = out
return __context__['chocolatey._version'] | python | def chocolatey_version():
'''
Returns the version of Chocolatey installed on the minion.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.chocolatey_version
'''
if 'chocolatey._version' in __context__:
return __context__['chocolatey._version']
cmd = [_find_chocolatey(__context__, __salt__)]
cmd.append('-v')
out = __salt__['cmd.run'](cmd, python_shell=False)
__context__['chocolatey._version'] = out
return __context__['chocolatey._version'] | [
"def",
"chocolatey_version",
"(",
")",
":",
"if",
"'chocolatey._version'",
"in",
"__context__",
":",
"return",
"__context__",
"[",
"'chocolatey._version'",
"]",
"cmd",
"=",
"[",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"]",
"cmd",
".",
"appe... | Returns the version of Chocolatey installed on the minion.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.chocolatey_version | [
"Returns",
"the",
"version",
"of",
"Chocolatey",
"installed",
"on",
"the",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L112-L130 | train |
saltstack/salt | salt/modules/chocolatey.py | bootstrap | def bootstrap(force=False):
'''
Download and install the latest version of the Chocolatey package manager
via the official bootstrap.
Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending
on the host's version of Windows, chocolatey.bootstrap will attempt to
ensure these prerequisites are met by downloading and executing the
appropriate installers from Microsoft.
Note that if PowerShell is installed, you may have to restart the host
machine for Chocolatey to work.
force
Run the bootstrap process even if Chocolatey is found in the path.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.bootstrap
salt '*' chocolatey.bootstrap force=True
'''
# Check if Chocolatey is already present in the path
try:
choc_path = _find_chocolatey(__context__, __salt__)
except CommandExecutionError:
choc_path = None
if choc_path and not force:
return 'Chocolatey found at {0}'.format(choc_path)
# The following lookup tables are required to determine the correct
# download required to install PowerShell. That's right, there's more
# than one! You're welcome.
ps_downloads = {
('Vista', 'x86'): 'http://download.microsoft.com/download/A/7/5/A75BC017-63CE-47D6-8FA4-AFB5C21BAC54/Windows6.0-KB968930-x86.msu',
('Vista', 'AMD64'): 'http://download.microsoft.com/download/3/C/8/3C8CF51E-1D9D-4DAA-AAEA-5C48D1CD055C/Windows6.0-KB968930-x64.msu',
('2008Server', 'x86'): 'http://download.microsoft.com/download/F/9/E/F9EF6ACB-2BA8-4845-9C10-85FC4A69B207/Windows6.0-KB968930-x86.msu',
('2008Server', 'AMD64'): 'http://download.microsoft.com/download/2/8/6/28686477-3242-4E96-9009-30B16BED89AF/Windows6.0-KB968930-x64.msu'
}
# It took until .NET v4.0 for Microsoft got the hang of making installers,
# this should work under any version of Windows
net4_url = 'http://download.microsoft.com/download/1/B/E/1BE39E79-7E39-46A3-96FF-047F95396215/dotNetFx40_Full_setup.exe'
temp_dir = tempfile.gettempdir()
# Check if PowerShell is installed. This should be the case for every
# Windows release following Server 2008.
ps_path = 'C:\\Windows\\SYSTEM32\\WindowsPowerShell\\v1.0\\powershell.exe'
if not __salt__['cmd.has_exec'](ps_path):
if (__grains__['osrelease'], __grains__['cpuarch']) in ps_downloads:
# Install the appropriate release of PowerShell v2.0
url = ps_downloads[(__grains__['osrelease'], __grains__['cpuarch'])]
dest = os.path.join(temp_dir, 'powershell.exe')
__salt__['cp.get_url'](url, dest)
cmd = [dest, '/quiet', '/norestart']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
err = ('Installing Windows PowerShell failed. Please run the '
'installer GUI on the host to get a more specific '
'reason.')
raise CommandExecutionError(err)
else:
err = 'Windows PowerShell not found'
raise CommandNotFoundError(err)
# Run the .NET Framework 4 web installer
dest = os.path.join(temp_dir, 'dotnet4.exe')
__salt__['cp.get_url'](net4_url, dest)
cmd = [dest, '/q', '/norestart']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
err = ('Installing .NET v4.0 failed. Please run the installer GUI on '
'the host to get a more specific reason.')
raise CommandExecutionError(err)
# Run the Chocolatey bootstrap.
cmd = (
'{0} -NoProfile -ExecutionPolicy unrestricted '
'-Command "iex ((new-object net.webclient).'
'DownloadString(\'https://chocolatey.org/install.ps1\'))" '
'&& SET PATH=%PATH%;%systemdrive%\\chocolatey\\bin'
.format(ps_path)
)
result = __salt__['cmd.run_all'](cmd, python_shell=True)
if result['retcode'] != 0:
raise CommandExecutionError(
'Bootstrapping Chocolatey failed: {0}'.format(result['stderr'])
)
return result['stdout'] | python | def bootstrap(force=False):
'''
Download and install the latest version of the Chocolatey package manager
via the official bootstrap.
Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending
on the host's version of Windows, chocolatey.bootstrap will attempt to
ensure these prerequisites are met by downloading and executing the
appropriate installers from Microsoft.
Note that if PowerShell is installed, you may have to restart the host
machine for Chocolatey to work.
force
Run the bootstrap process even if Chocolatey is found in the path.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.bootstrap
salt '*' chocolatey.bootstrap force=True
'''
# Check if Chocolatey is already present in the path
try:
choc_path = _find_chocolatey(__context__, __salt__)
except CommandExecutionError:
choc_path = None
if choc_path and not force:
return 'Chocolatey found at {0}'.format(choc_path)
# The following lookup tables are required to determine the correct
# download required to install PowerShell. That's right, there's more
# than one! You're welcome.
ps_downloads = {
('Vista', 'x86'): 'http://download.microsoft.com/download/A/7/5/A75BC017-63CE-47D6-8FA4-AFB5C21BAC54/Windows6.0-KB968930-x86.msu',
('Vista', 'AMD64'): 'http://download.microsoft.com/download/3/C/8/3C8CF51E-1D9D-4DAA-AAEA-5C48D1CD055C/Windows6.0-KB968930-x64.msu',
('2008Server', 'x86'): 'http://download.microsoft.com/download/F/9/E/F9EF6ACB-2BA8-4845-9C10-85FC4A69B207/Windows6.0-KB968930-x86.msu',
('2008Server', 'AMD64'): 'http://download.microsoft.com/download/2/8/6/28686477-3242-4E96-9009-30B16BED89AF/Windows6.0-KB968930-x64.msu'
}
# It took until .NET v4.0 for Microsoft got the hang of making installers,
# this should work under any version of Windows
net4_url = 'http://download.microsoft.com/download/1/B/E/1BE39E79-7E39-46A3-96FF-047F95396215/dotNetFx40_Full_setup.exe'
temp_dir = tempfile.gettempdir()
# Check if PowerShell is installed. This should be the case for every
# Windows release following Server 2008.
ps_path = 'C:\\Windows\\SYSTEM32\\WindowsPowerShell\\v1.0\\powershell.exe'
if not __salt__['cmd.has_exec'](ps_path):
if (__grains__['osrelease'], __grains__['cpuarch']) in ps_downloads:
# Install the appropriate release of PowerShell v2.0
url = ps_downloads[(__grains__['osrelease'], __grains__['cpuarch'])]
dest = os.path.join(temp_dir, 'powershell.exe')
__salt__['cp.get_url'](url, dest)
cmd = [dest, '/quiet', '/norestart']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
err = ('Installing Windows PowerShell failed. Please run the '
'installer GUI on the host to get a more specific '
'reason.')
raise CommandExecutionError(err)
else:
err = 'Windows PowerShell not found'
raise CommandNotFoundError(err)
# Run the .NET Framework 4 web installer
dest = os.path.join(temp_dir, 'dotnet4.exe')
__salt__['cp.get_url'](net4_url, dest)
cmd = [dest, '/q', '/norestart']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
err = ('Installing .NET v4.0 failed. Please run the installer GUI on '
'the host to get a more specific reason.')
raise CommandExecutionError(err)
# Run the Chocolatey bootstrap.
cmd = (
'{0} -NoProfile -ExecutionPolicy unrestricted '
'-Command "iex ((new-object net.webclient).'
'DownloadString(\'https://chocolatey.org/install.ps1\'))" '
'&& SET PATH=%PATH%;%systemdrive%\\chocolatey\\bin'
.format(ps_path)
)
result = __salt__['cmd.run_all'](cmd, python_shell=True)
if result['retcode'] != 0:
raise CommandExecutionError(
'Bootstrapping Chocolatey failed: {0}'.format(result['stderr'])
)
return result['stdout'] | [
"def",
"bootstrap",
"(",
"force",
"=",
"False",
")",
":",
"# Check if Chocolatey is already present in the path",
"try",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"except",
"CommandExecutionError",
":",
"choc_path",
"=",
"Non... | Download and install the latest version of the Chocolatey package manager
via the official bootstrap.
Chocolatey requires Windows PowerShell and the .NET v4.0 runtime. Depending
on the host's version of Windows, chocolatey.bootstrap will attempt to
ensure these prerequisites are met by downloading and executing the
appropriate installers from Microsoft.
Note that if PowerShell is installed, you may have to restart the host
machine for Chocolatey to work.
force
Run the bootstrap process even if Chocolatey is found in the path.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.bootstrap
salt '*' chocolatey.bootstrap force=True | [
"Download",
"and",
"install",
"the",
"latest",
"version",
"of",
"the",
"Chocolatey",
"package",
"manager",
"via",
"the",
"official",
"bootstrap",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L133-L226 | train |
saltstack/salt | salt/modules/chocolatey.py | list_ | def list_(narrow=None,
all_versions=False,
pre_versions=False,
source=None,
local_only=False,
exact=False):
'''
Instructs Chocolatey to pull a vague package list from the repository.
Args:
narrow (str):
Term used to narrow down results. Searches against
name/description/tag. Default is None.
all_versions (bool):
Display all available package versions in results. Default is False.
pre_versions (bool):
Display pre-release packages in results. Default is False.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed if
None is passed. Default is None.
local_only (bool):
Display packages only installed locally. Default is False.
exact (bool):
Display only packages that match ``narrow`` exactly. Default is
False.
.. versionadded:: 2017.7.0
Returns:
dict: A dictionary of results.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.list <narrow>
salt '*' chocolatey.list <narrow> all_versions=True
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'list']
if narrow:
cmd.append(narrow)
if salt.utils.data.is_true(all_versions):
cmd.append('--allversions')
if salt.utils.data.is_true(pre_versions):
cmd.append('--prerelease')
if source:
cmd.extend(['--source', source])
if local_only:
cmd.append('--local-only')
if exact:
cmd.append('--exact')
# This is needed to parse the output correctly
cmd.append('--limit-output')
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
ret = {}
pkg_re = re.compile(r'(\S+)\|(\S+)')
for line in result['stdout'].split('\n'):
if line.startswith("No packages"):
return ret
for name, ver in pkg_re.findall(line):
if 'chocolatey' in name:
continue
if name not in ret:
ret[name] = []
ret[name].append(ver)
return ret | python | def list_(narrow=None,
all_versions=False,
pre_versions=False,
source=None,
local_only=False,
exact=False):
'''
Instructs Chocolatey to pull a vague package list from the repository.
Args:
narrow (str):
Term used to narrow down results. Searches against
name/description/tag. Default is None.
all_versions (bool):
Display all available package versions in results. Default is False.
pre_versions (bool):
Display pre-release packages in results. Default is False.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed if
None is passed. Default is None.
local_only (bool):
Display packages only installed locally. Default is False.
exact (bool):
Display only packages that match ``narrow`` exactly. Default is
False.
.. versionadded:: 2017.7.0
Returns:
dict: A dictionary of results.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.list <narrow>
salt '*' chocolatey.list <narrow> all_versions=True
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'list']
if narrow:
cmd.append(narrow)
if salt.utils.data.is_true(all_versions):
cmd.append('--allversions')
if salt.utils.data.is_true(pre_versions):
cmd.append('--prerelease')
if source:
cmd.extend(['--source', source])
if local_only:
cmd.append('--local-only')
if exact:
cmd.append('--exact')
# This is needed to parse the output correctly
cmd.append('--limit-output')
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
ret = {}
pkg_re = re.compile(r'(\S+)\|(\S+)')
for line in result['stdout'].split('\n'):
if line.startswith("No packages"):
return ret
for name, ver in pkg_re.findall(line):
if 'chocolatey' in name:
continue
if name not in ret:
ret[name] = []
ret[name].append(ver)
return ret | [
"def",
"list_",
"(",
"narrow",
"=",
"None",
",",
"all_versions",
"=",
"False",
",",
"pre_versions",
"=",
"False",
",",
"source",
"=",
"None",
",",
"local_only",
"=",
"False",
",",
"exact",
"=",
"False",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"("... | Instructs Chocolatey to pull a vague package list from the repository.
Args:
narrow (str):
Term used to narrow down results. Searches against
name/description/tag. Default is None.
all_versions (bool):
Display all available package versions in results. Default is False.
pre_versions (bool):
Display pre-release packages in results. Default is False.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed if
None is passed. Default is None.
local_only (bool):
Display packages only installed locally. Default is False.
exact (bool):
Display only packages that match ``narrow`` exactly. Default is
False.
.. versionadded:: 2017.7.0
Returns:
dict: A dictionary of results.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.list <narrow>
salt '*' chocolatey.list <narrow> all_versions=True | [
"Instructs",
"Chocolatey",
"to",
"pull",
"a",
"vague",
"package",
"list",
"from",
"the",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L229-L311 | train |
saltstack/salt | salt/modules/chocolatey.py | list_windowsfeatures | def list_windowsfeatures():
'''
Instructs Chocolatey to pull a full package list from the Windows Features
list, via the Deployment Image Servicing and Management tool.
Returns:
str: List of Windows Features
CLI Example:
.. code-block:: bash
salt '*' chocolatey.list_windowsfeatures
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'list', '--source', 'windowsfeatures']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def list_windowsfeatures():
'''
Instructs Chocolatey to pull a full package list from the Windows Features
list, via the Deployment Image Servicing and Management tool.
Returns:
str: List of Windows Features
CLI Example:
.. code-block:: bash
salt '*' chocolatey.list_windowsfeatures
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'list', '--source', 'windowsfeatures']
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"list_windowsfeatures",
"(",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"cmd",
"=",
"[",
"choc_path",
",",
"'list'",
",",
"'--source'",
",",
"'windowsfeatures'",
"]",
"result",
"=",
"__salt__",
"[",
"'cmd.r... | Instructs Chocolatey to pull a full package list from the Windows Features
list, via the Deployment Image Servicing and Management tool.
Returns:
str: List of Windows Features
CLI Example:
.. code-block:: bash
salt '*' chocolatey.list_windowsfeatures | [
"Instructs",
"Chocolatey",
"to",
"pull",
"a",
"full",
"package",
"list",
"from",
"the",
"Windows",
"Features",
"list",
"via",
"the",
"Deployment",
"Image",
"Servicing",
"and",
"Management",
"tool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L340-L363 | train |
saltstack/salt | salt/modules/chocolatey.py | install_cygwin | def install_cygwin(name, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Cygwin.
name
The name of the package to be installed. Only accepts a single argument.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_cygwin <package name>
salt '*' chocolatey.install_cygwin <package name> install_args=<args> override_args=True
'''
return install(name,
source='cygwin',
install_args=install_args,
override_args=override_args) | python | def install_cygwin(name, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Cygwin.
name
The name of the package to be installed. Only accepts a single argument.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_cygwin <package name>
salt '*' chocolatey.install_cygwin <package name> install_args=<args> override_args=True
'''
return install(name,
source='cygwin',
install_args=install_args,
override_args=override_args) | [
"def",
"install_cygwin",
"(",
"name",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"source",
"=",
"'cygwin'",
",",
"install_args",
"=",
"install_args",
",",
"override_args",
"=",
"over... | Instructs Chocolatey to install a package via Cygwin.
name
The name of the package to be installed. Only accepts a single argument.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_cygwin <package name>
salt '*' chocolatey.install_cygwin <package name> install_args=<args> override_args=True | [
"Instructs",
"Chocolatey",
"to",
"install",
"a",
"package",
"via",
"Cygwin",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L496-L523 | train |
saltstack/salt | salt/modules/chocolatey.py | install_gem | def install_gem(name, version=None, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Ruby's Gems.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_gem <package name>
salt '*' chocolatey.install_gem <package name> version=<package version>
salt '*' chocolatey.install_gem <package name> install_args=<args> override_args=True
'''
return install(name,
version=version,
source='ruby',
install_args=install_args,
override_args=override_args) | python | def install_gem(name, version=None, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Ruby's Gems.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_gem <package name>
salt '*' chocolatey.install_gem <package name> version=<package version>
salt '*' chocolatey.install_gem <package name> install_args=<args> override_args=True
'''
return install(name,
version=version,
source='ruby',
install_args=install_args,
override_args=override_args) | [
"def",
"install_gem",
"(",
"name",
",",
"version",
"=",
"None",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"version",
"=",
"version",
",",
"source",
"=",
"'ruby'",
",",
"install_... | Instructs Chocolatey to install a package via Ruby's Gems.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_gem <package name>
salt '*' chocolatey.install_gem <package name> version=<package version>
salt '*' chocolatey.install_gem <package name> install_args=<args> override_args=True | [
"Instructs",
"Chocolatey",
"to",
"install",
"a",
"package",
"via",
"Ruby",
"s",
"Gems",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L526-L560 | train |
saltstack/salt | salt/modules/chocolatey.py | install_missing | def install_missing(name, version=None, source=None):
'''
Instructs Chocolatey to install a package if it doesn't already exist.
.. versionchanged:: 2014.7.0
If the minion has Chocolatey >= 0.9.8.24 installed, this function calls
:mod:`chocolatey.install <salt.modules.chocolatey.install>` instead, as
``installmissing`` is deprecated as of that version and will be removed
in Chocolatey 1.0.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
source
Chocolatey repository (directory, share or remote URL feed) the package
comes from. Defaults to the official Chocolatey feed.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_missing <package name>
salt '*' chocolatey.install_missing <package name> version=<package version>
'''
choc_path = _find_chocolatey(__context__, __salt__)
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.8.24'):
log.warning('installmissing is deprecated, using install')
return install(name, version=version)
# chocolatey helpfully only supports a single package argument
cmd = [choc_path, 'installmissing', name]
if version:
cmd.extend(['--version', version])
if source:
cmd.extend(['--source', source])
# Shouldn't need this as this code should never run on v0.9.9 and newer
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def install_missing(name, version=None, source=None):
'''
Instructs Chocolatey to install a package if it doesn't already exist.
.. versionchanged:: 2014.7.0
If the minion has Chocolatey >= 0.9.8.24 installed, this function calls
:mod:`chocolatey.install <salt.modules.chocolatey.install>` instead, as
``installmissing`` is deprecated as of that version and will be removed
in Chocolatey 1.0.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
source
Chocolatey repository (directory, share or remote URL feed) the package
comes from. Defaults to the official Chocolatey feed.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_missing <package name>
salt '*' chocolatey.install_missing <package name> version=<package version>
'''
choc_path = _find_chocolatey(__context__, __salt__)
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.8.24'):
log.warning('installmissing is deprecated, using install')
return install(name, version=version)
# chocolatey helpfully only supports a single package argument
cmd = [choc_path, 'installmissing', name]
if version:
cmd.extend(['--version', version])
if source:
cmd.extend(['--source', source])
# Shouldn't need this as this code should never run on v0.9.9 and newer
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"install_missing",
"(",
"name",
",",
"version",
"=",
"None",
",",
"source",
"=",
"None",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"if",
"_LooseVersion",
"(",
"chocolatey_version",
"(",
")",
")",
">=",
... | Instructs Chocolatey to install a package if it doesn't already exist.
.. versionchanged:: 2014.7.0
If the minion has Chocolatey >= 0.9.8.24 installed, this function calls
:mod:`chocolatey.install <salt.modules.chocolatey.install>` instead, as
``installmissing`` is deprecated as of that version and will be removed
in Chocolatey 1.0.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
source
Chocolatey repository (directory, share or remote URL feed) the package
comes from. Defaults to the official Chocolatey feed.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_missing <package name>
salt '*' chocolatey.install_missing <package name> version=<package version> | [
"Instructs",
"Chocolatey",
"to",
"install",
"a",
"package",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L563-L611 | train |
saltstack/salt | salt/modules/chocolatey.py | install_python | def install_python(name, version=None, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_python <package name>
salt '*' chocolatey.install_python <package name> version=<package version>
salt '*' chocolatey.install_python <package name> install_args=<args> override_args=True
'''
return install(name,
version=version,
source='python',
install_args=install_args,
override_args=override_args) | python | def install_python(name, version=None, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_python <package name>
salt '*' chocolatey.install_python <package name> version=<package version>
salt '*' chocolatey.install_python <package name> install_args=<args> override_args=True
'''
return install(name,
version=version,
source='python',
install_args=install_args,
override_args=override_args) | [
"def",
"install_python",
"(",
"name",
",",
"version",
"=",
"None",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"version",
"=",
"version",
",",
"source",
"=",
"'python'",
",",
"ins... | Instructs Chocolatey to install a package via Python's easy_install.
name
The name of the package to be installed. Only accepts a single argument.
version
Install a specific version of the package. Defaults to latest version
available.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_python <package name>
salt '*' chocolatey.install_python <package name> version=<package version>
salt '*' chocolatey.install_python <package name> install_args=<args> override_args=True | [
"Instructs",
"Chocolatey",
"to",
"install",
"a",
"package",
"via",
"Python",
"s",
"easy_install",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L614-L647 | train |
saltstack/salt | salt/modules/chocolatey.py | install_webpi | def install_webpi(name, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via the Microsoft Web PI service.
name
The name of the package to be installed. Only accepts a single argument.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_webpi <package name>
salt '*' chocolatey.install_webpi <package name> install_args=<args> override_args=True
'''
return install(name,
source='webpi',
install_args=install_args,
override_args=override_args) | python | def install_webpi(name, install_args=None, override_args=False):
'''
Instructs Chocolatey to install a package via the Microsoft Web PI service.
name
The name of the package to be installed. Only accepts a single argument.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_webpi <package name>
salt '*' chocolatey.install_webpi <package name> install_args=<args> override_args=True
'''
return install(name,
source='webpi',
install_args=install_args,
override_args=override_args) | [
"def",
"install_webpi",
"(",
"name",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"return",
"install",
"(",
"name",
",",
"source",
"=",
"'webpi'",
",",
"install_args",
"=",
"install_args",
",",
"override_args",
"=",
"overri... | Instructs Chocolatey to install a package via the Microsoft Web PI service.
name
The name of the package to be installed. Only accepts a single argument.
install_args
A list of install arguments you want to pass to the installation process
i.e product key or feature list
override_args
Set to true if you want to override the original install arguments (for
the native installer) in the package and use your own. When this is set
to False install_args will be appended to the end of the default
arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.install_webpi <package name>
salt '*' chocolatey.install_webpi <package name> install_args=<args> override_args=True | [
"Instructs",
"Chocolatey",
"to",
"install",
"a",
"package",
"via",
"the",
"Microsoft",
"Web",
"PI",
"service",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L667-L694 | train |
saltstack/salt | salt/modules/chocolatey.py | uninstall | def uninstall(name, version=None, uninstall_args=None, override_args=False):
'''
Instructs Chocolatey to uninstall a package.
name
The name of the package to be uninstalled. Only accepts a single
argument.
version
Uninstalls a specific version of the package. Defaults to latest version
installed.
uninstall_args
A list of uninstall arguments you want to pass to the uninstallation
process i.e product key or feature list
override_args
Set to true if you want to override the original uninstall arguments
(for the native uninstaller) in the package and use your own. When this
is set to False uninstall_args will be appended to the end of the
default arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.uninstall <package name>
salt '*' chocolatey.uninstall <package name> version=<package version>
salt '*' chocolatey.uninstall <package name> version=<package version> uninstall_args=<args> override_args=True
'''
choc_path = _find_chocolatey(__context__, __salt__)
# chocolatey helpfully only supports a single package argument
cmd = [choc_path, 'uninstall', name]
if version:
cmd.extend(['--version', version])
if uninstall_args:
cmd.extend(['--uninstallarguments', uninstall_args])
if override_args:
cmd.extend(['--overridearguments'])
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] not in [0, 1605, 1614, 1641]:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def uninstall(name, version=None, uninstall_args=None, override_args=False):
'''
Instructs Chocolatey to uninstall a package.
name
The name of the package to be uninstalled. Only accepts a single
argument.
version
Uninstalls a specific version of the package. Defaults to latest version
installed.
uninstall_args
A list of uninstall arguments you want to pass to the uninstallation
process i.e product key or feature list
override_args
Set to true if you want to override the original uninstall arguments
(for the native uninstaller) in the package and use your own. When this
is set to False uninstall_args will be appended to the end of the
default arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.uninstall <package name>
salt '*' chocolatey.uninstall <package name> version=<package version>
salt '*' chocolatey.uninstall <package name> version=<package version> uninstall_args=<args> override_args=True
'''
choc_path = _find_chocolatey(__context__, __salt__)
# chocolatey helpfully only supports a single package argument
cmd = [choc_path, 'uninstall', name]
if version:
cmd.extend(['--version', version])
if uninstall_args:
cmd.extend(['--uninstallarguments', uninstall_args])
if override_args:
cmd.extend(['--overridearguments'])
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] not in [0, 1605, 1614, 1641]:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"uninstall",
"(",
"name",
",",
"version",
"=",
"None",
",",
"uninstall_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"# chocolatey helpfully only supports a ... | Instructs Chocolatey to uninstall a package.
name
The name of the package to be uninstalled. Only accepts a single
argument.
version
Uninstalls a specific version of the package. Defaults to latest version
installed.
uninstall_args
A list of uninstall arguments you want to pass to the uninstallation
process i.e product key or feature list
override_args
Set to true if you want to override the original uninstall arguments
(for the native uninstaller) in the package and use your own. When this
is set to False uninstall_args will be appended to the end of the
default arguments
CLI Example:
.. code-block:: bash
salt '*' chocolatey.uninstall <package name>
salt '*' chocolatey.uninstall <package name> version=<package version>
salt '*' chocolatey.uninstall <package name> version=<package version> uninstall_args=<args> override_args=True | [
"Instructs",
"Chocolatey",
"to",
"uninstall",
"a",
"package",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L697-L744 | train |
saltstack/salt | salt/modules/chocolatey.py | upgrade | def upgrade(name,
version=None,
source=None,
force=False,
pre_versions=False,
install_args=None,
override_args=False,
force_x86=False,
package_args=None):
'''
.. versionadded:: 2016.3.4
Instructs Chocolatey to upgrade packages on the system. (update is being
deprecated). This command will install the package if not installed.
Args:
name (str):
The name of the package to update, or "all" to update everything
installed on the system.
version (str):
Install a specific version of the package. Defaults to latest
version.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed.
force (bool):
Reinstall the **same** version already installed
pre_versions (bool):
Include pre-release packages in comparison. Defaults to False.
install_args (str):
A list of install arguments you want to pass to the installation
process i.e product key or feature list
override_args (str):
Set to true if you want to override the original install arguments
(for the native installer) in the package and use your own. When
this is set to False install_args will be appended to the end of the
default arguments
force_x86
Force x86 (32bit) installation on 64 bit systems. Defaults to false.
package_args
A list of arguments you want to pass to the package
Returns:
str: Results of the ``chocolatey`` command
CLI Example:
.. code-block:: bash
salt "*" chocolatey.upgrade all
salt "*" chocolatey.upgrade <package name> pre_versions=True
'''
# chocolatey helpfully only supports a single package argument
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'upgrade', name]
if version:
cmd.extend(['--version', version])
if source:
cmd.extend(['--source', source])
if salt.utils.data.is_true(force):
cmd.append('--force')
if salt.utils.data.is_true(pre_versions):
cmd.append('--prerelease')
if install_args:
cmd.extend(['--installarguments', install_args])
if override_args:
cmd.append('--overridearguments')
if force_x86:
cmd.append('--forcex86')
if package_args:
cmd.extend(['--packageparameters', package_args])
# Salt doesn't need to see the progress
cmd.extend(_no_progress(__context__))
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] not in [0, 1641, 3010]:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def upgrade(name,
version=None,
source=None,
force=False,
pre_versions=False,
install_args=None,
override_args=False,
force_x86=False,
package_args=None):
'''
.. versionadded:: 2016.3.4
Instructs Chocolatey to upgrade packages on the system. (update is being
deprecated). This command will install the package if not installed.
Args:
name (str):
The name of the package to update, or "all" to update everything
installed on the system.
version (str):
Install a specific version of the package. Defaults to latest
version.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed.
force (bool):
Reinstall the **same** version already installed
pre_versions (bool):
Include pre-release packages in comparison. Defaults to False.
install_args (str):
A list of install arguments you want to pass to the installation
process i.e product key or feature list
override_args (str):
Set to true if you want to override the original install arguments
(for the native installer) in the package and use your own. When
this is set to False install_args will be appended to the end of the
default arguments
force_x86
Force x86 (32bit) installation on 64 bit systems. Defaults to false.
package_args
A list of arguments you want to pass to the package
Returns:
str: Results of the ``chocolatey`` command
CLI Example:
.. code-block:: bash
salt "*" chocolatey.upgrade all
salt "*" chocolatey.upgrade <package name> pre_versions=True
'''
# chocolatey helpfully only supports a single package argument
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'upgrade', name]
if version:
cmd.extend(['--version', version])
if source:
cmd.extend(['--source', source])
if salt.utils.data.is_true(force):
cmd.append('--force')
if salt.utils.data.is_true(pre_versions):
cmd.append('--prerelease')
if install_args:
cmd.extend(['--installarguments', install_args])
if override_args:
cmd.append('--overridearguments')
if force_x86:
cmd.append('--forcex86')
if package_args:
cmd.extend(['--packageparameters', package_args])
# Salt doesn't need to see the progress
cmd.extend(_no_progress(__context__))
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] not in [0, 1641, 3010]:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"upgrade",
"(",
"name",
",",
"version",
"=",
"None",
",",
"source",
"=",
"None",
",",
"force",
"=",
"False",
",",
"pre_versions",
"=",
"False",
",",
"install_args",
"=",
"None",
",",
"override_args",
"=",
"False",
",",
"force_x86",
"=",
"False",
... | .. versionadded:: 2016.3.4
Instructs Chocolatey to upgrade packages on the system. (update is being
deprecated). This command will install the package if not installed.
Args:
name (str):
The name of the package to update, or "all" to update everything
installed on the system.
version (str):
Install a specific version of the package. Defaults to latest
version.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed.
force (bool):
Reinstall the **same** version already installed
pre_versions (bool):
Include pre-release packages in comparison. Defaults to False.
install_args (str):
A list of install arguments you want to pass to the installation
process i.e product key or feature list
override_args (str):
Set to true if you want to override the original install arguments
(for the native installer) in the package and use your own. When
this is set to False install_args will be appended to the end of the
default arguments
force_x86
Force x86 (32bit) installation on 64 bit systems. Defaults to false.
package_args
A list of arguments you want to pass to the package
Returns:
str: Results of the ``chocolatey`` command
CLI Example:
.. code-block:: bash
salt "*" chocolatey.upgrade all
salt "*" chocolatey.upgrade <package name> pre_versions=True | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"4"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L747-L839 | train |
saltstack/salt | salt/modules/chocolatey.py | update | def update(name, source=None, pre_versions=False):
'''
Instructs Chocolatey to update packages on the system.
name
The name of the package to update, or "all" to update everything
installed on the system.
source
Chocolatey repository (directory, share or remote URL feed) the package
comes from. Defaults to the official Chocolatey feed.
pre_versions
Include pre-release packages in comparison. Defaults to False.
CLI Example:
.. code-block:: bash
salt "*" chocolatey.update all
salt "*" chocolatey.update <package name> pre_versions=True
'''
# chocolatey helpfully only supports a single package argument
choc_path = _find_chocolatey(__context__, __salt__)
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.8.24'):
log.warning('update is deprecated, using upgrade')
return upgrade(name, source=source, pre_versions=pre_versions)
cmd = [choc_path, 'update', name]
if source:
cmd.extend(['--source', source])
if salt.utils.data.is_true(pre_versions):
cmd.append('--prerelease')
# Salt doesn't need to see the progress
cmd.extend(_no_progress(__context__))
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] not in [0, 1641, 3010]:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def update(name, source=None, pre_versions=False):
'''
Instructs Chocolatey to update packages on the system.
name
The name of the package to update, or "all" to update everything
installed on the system.
source
Chocolatey repository (directory, share or remote URL feed) the package
comes from. Defaults to the official Chocolatey feed.
pre_versions
Include pre-release packages in comparison. Defaults to False.
CLI Example:
.. code-block:: bash
salt "*" chocolatey.update all
salt "*" chocolatey.update <package name> pre_versions=True
'''
# chocolatey helpfully only supports a single package argument
choc_path = _find_chocolatey(__context__, __salt__)
if _LooseVersion(chocolatey_version()) >= _LooseVersion('0.9.8.24'):
log.warning('update is deprecated, using upgrade')
return upgrade(name, source=source, pre_versions=pre_versions)
cmd = [choc_path, 'update', name]
if source:
cmd.extend(['--source', source])
if salt.utils.data.is_true(pre_versions):
cmd.append('--prerelease')
# Salt doesn't need to see the progress
cmd.extend(_no_progress(__context__))
cmd.extend(_yes(__context__))
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] not in [0, 1641, 3010]:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"update",
"(",
"name",
",",
"source",
"=",
"None",
",",
"pre_versions",
"=",
"False",
")",
":",
"# chocolatey helpfully only supports a single package argument",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"if",
"_LooseVersio... | Instructs Chocolatey to update packages on the system.
name
The name of the package to update, or "all" to update everything
installed on the system.
source
Chocolatey repository (directory, share or remote URL feed) the package
comes from. Defaults to the official Chocolatey feed.
pre_versions
Include pre-release packages in comparison. Defaults to False.
CLI Example:
.. code-block:: bash
salt "*" chocolatey.update all
salt "*" chocolatey.update <package name> pre_versions=True | [
"Instructs",
"Chocolatey",
"to",
"update",
"packages",
"on",
"the",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L842-L887 | train |
saltstack/salt | salt/modules/chocolatey.py | version | def version(name, check_remote=False, source=None, pre_versions=False):
'''
Instructs Chocolatey to check an installed package version, and optionally
compare it to one available from a remote feed.
Args:
name (str):
The name of the package to check. Required.
check_remote (bool):
Get the version number of the latest package from the remote feed.
Default is False.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed.
Default is None.
pre_versions (bool):
Include pre-release packages in comparison. Default is False.
Returns:
dict: A dictionary of currently installed software and versions
CLI Example:
.. code-block:: bash
salt "*" chocolatey.version <package name>
salt "*" chocolatey.version <package name> check_remote=True
'''
installed = list_(narrow=name, local_only=True)
installed = {k.lower(): v for k, v in installed.items()}
packages = {}
lower_name = name.lower()
for pkg in installed:
if lower_name in pkg.lower():
packages[pkg] = installed[pkg]
if check_remote:
available = list_(narrow=name, pre_versions=pre_versions, source=source)
available = {k.lower(): v for k, v in available.items()}
for pkg in packages:
# Grab the current version from the package that was installed
packages[pkg] = {'installed': installed[pkg]}
# If there's a remote package available, then also include that
# in the dictionary that we return.
if pkg in available:
packages[pkg]['available'] = available[pkg]
continue
return packages | python | def version(name, check_remote=False, source=None, pre_versions=False):
'''
Instructs Chocolatey to check an installed package version, and optionally
compare it to one available from a remote feed.
Args:
name (str):
The name of the package to check. Required.
check_remote (bool):
Get the version number of the latest package from the remote feed.
Default is False.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed.
Default is None.
pre_versions (bool):
Include pre-release packages in comparison. Default is False.
Returns:
dict: A dictionary of currently installed software and versions
CLI Example:
.. code-block:: bash
salt "*" chocolatey.version <package name>
salt "*" chocolatey.version <package name> check_remote=True
'''
installed = list_(narrow=name, local_only=True)
installed = {k.lower(): v for k, v in installed.items()}
packages = {}
lower_name = name.lower()
for pkg in installed:
if lower_name in pkg.lower():
packages[pkg] = installed[pkg]
if check_remote:
available = list_(narrow=name, pre_versions=pre_versions, source=source)
available = {k.lower(): v for k, v in available.items()}
for pkg in packages:
# Grab the current version from the package that was installed
packages[pkg] = {'installed': installed[pkg]}
# If there's a remote package available, then also include that
# in the dictionary that we return.
if pkg in available:
packages[pkg]['available'] = available[pkg]
continue
return packages | [
"def",
"version",
"(",
"name",
",",
"check_remote",
"=",
"False",
",",
"source",
"=",
"None",
",",
"pre_versions",
"=",
"False",
")",
":",
"installed",
"=",
"list_",
"(",
"narrow",
"=",
"name",
",",
"local_only",
"=",
"True",
")",
"installed",
"=",
"{"... | Instructs Chocolatey to check an installed package version, and optionally
compare it to one available from a remote feed.
Args:
name (str):
The name of the package to check. Required.
check_remote (bool):
Get the version number of the latest package from the remote feed.
Default is False.
source (str):
Chocolatey repository (directory, share or remote URL feed) the
package comes from. Defaults to the official Chocolatey feed.
Default is None.
pre_versions (bool):
Include pre-release packages in comparison. Default is False.
Returns:
dict: A dictionary of currently installed software and versions
CLI Example:
.. code-block:: bash
salt "*" chocolatey.version <package name>
salt "*" chocolatey.version <package name> check_remote=True | [
"Instructs",
"Chocolatey",
"to",
"check",
"an",
"installed",
"package",
"version",
"and",
"optionally",
"compare",
"it",
"to",
"one",
"available",
"from",
"a",
"remote",
"feed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L890-L945 | train |
saltstack/salt | salt/modules/chocolatey.py | add_source | def add_source(name, source_location, username=None, password=None):
'''
Instructs Chocolatey to add a source.
name
The name of the source to be added as a chocolatey repository.
source
Location of the source you want to work with.
username
Provide username for chocolatey sources that need authentication
credentials.
password
Provide password for chocolatey sources that need authentication
credentials.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.add_source <source name> <source_location>
salt '*' chocolatey.add_source <source name> <source_location> user=<user> password=<password>
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'sources', 'add', '--name', name, '--source', source_location]
if username:
cmd.extend(['--user', username])
if password:
cmd.extend(['--password', password])
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def add_source(name, source_location, username=None, password=None):
'''
Instructs Chocolatey to add a source.
name
The name of the source to be added as a chocolatey repository.
source
Location of the source you want to work with.
username
Provide username for chocolatey sources that need authentication
credentials.
password
Provide password for chocolatey sources that need authentication
credentials.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.add_source <source name> <source_location>
salt '*' chocolatey.add_source <source name> <source_location> user=<user> password=<password>
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'sources', 'add', '--name', name, '--source', source_location]
if username:
cmd.extend(['--user', username])
if password:
cmd.extend(['--password', password])
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"add_source",
"(",
"name",
",",
"source_location",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"cmd",
"=",
"[",
"choc_path",
",",
"'sources'",
... | Instructs Chocolatey to add a source.
name
The name of the source to be added as a chocolatey repository.
source
Location of the source you want to work with.
username
Provide username for chocolatey sources that need authentication
credentials.
password
Provide password for chocolatey sources that need authentication
credentials.
CLI Example:
.. code-block:: bash
salt '*' chocolatey.add_source <source name> <source_location>
salt '*' chocolatey.add_source <source name> <source_location> user=<user> password=<password> | [
"Instructs",
"Chocolatey",
"to",
"add",
"a",
"source",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L948-L987 | train |
saltstack/salt | salt/modules/chocolatey.py | _change_source_state | def _change_source_state(name, state):
'''
Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository.
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'source', state, '--name', name]
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | python | def _change_source_state(name, state):
'''
Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository.
'''
choc_path = _find_chocolatey(__context__, __salt__)
cmd = [choc_path, 'source', state, '--name', name]
result = __salt__['cmd.run_all'](cmd, python_shell=False)
if result['retcode'] != 0:
raise CommandExecutionError(
'Running chocolatey failed: {0}'.format(result['stdout'])
)
return result['stdout'] | [
"def",
"_change_source_state",
"(",
"name",
",",
"state",
")",
":",
"choc_path",
"=",
"_find_chocolatey",
"(",
"__context__",
",",
"__salt__",
")",
"cmd",
"=",
"[",
"choc_path",
",",
"'source'",
",",
"state",
",",
"'--name'",
",",
"name",
"]",
"result",
"=... | Instructs Chocolatey to change the state of a source.
name
Name of the repository to affect.
state
State in which you want the chocolatey repository. | [
"Instructs",
"Chocolatey",
"to",
"change",
"the",
"state",
"of",
"a",
"source",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/chocolatey.py#L990-L1010 | train |
saltstack/salt | salt/modules/layman.py | add | def add(overlay):
'''
Add the given overlay from the cached remote list to your locally
installed overlays. Specify 'ALL' to add all overlays from the
remote list.
Return a list of the new overlay(s) added:
CLI Example:
.. code-block:: bash
salt '*' layman.add <overlay name>
'''
ret = list()
old_overlays = list_local()
cmd = 'layman --quietness=0 --add {0}'.format(overlay)
add_attempt = __salt__['cmd.run_all'](cmd, python_shell=False, stdin='y')
if add_attempt['retcode'] != 0:
raise salt.exceptions.CommandExecutionError(add_attempt['stdout'])
new_overlays = list_local()
# If we did not have any overlays before and we successfully added
# a new one. We need to ensure the make.conf is sourcing layman's
# make.conf so emerge can see the overlays
if not old_overlays and new_overlays:
srcline = 'source /var/lib/layman/make.conf'
makeconf = _get_makeconf()
if not __salt__['file.contains'](makeconf, 'layman'):
__salt__['file.append'](makeconf, srcline)
ret = [overlay for overlay in new_overlays if overlay not in old_overlays]
return ret | python | def add(overlay):
'''
Add the given overlay from the cached remote list to your locally
installed overlays. Specify 'ALL' to add all overlays from the
remote list.
Return a list of the new overlay(s) added:
CLI Example:
.. code-block:: bash
salt '*' layman.add <overlay name>
'''
ret = list()
old_overlays = list_local()
cmd = 'layman --quietness=0 --add {0}'.format(overlay)
add_attempt = __salt__['cmd.run_all'](cmd, python_shell=False, stdin='y')
if add_attempt['retcode'] != 0:
raise salt.exceptions.CommandExecutionError(add_attempt['stdout'])
new_overlays = list_local()
# If we did not have any overlays before and we successfully added
# a new one. We need to ensure the make.conf is sourcing layman's
# make.conf so emerge can see the overlays
if not old_overlays and new_overlays:
srcline = 'source /var/lib/layman/make.conf'
makeconf = _get_makeconf()
if not __salt__['file.contains'](makeconf, 'layman'):
__salt__['file.append'](makeconf, srcline)
ret = [overlay for overlay in new_overlays if overlay not in old_overlays]
return ret | [
"def",
"add",
"(",
"overlay",
")",
":",
"ret",
"=",
"list",
"(",
")",
"old_overlays",
"=",
"list_local",
"(",
")",
"cmd",
"=",
"'layman --quietness=0 --add {0}'",
".",
"format",
"(",
"overlay",
")",
"add_attempt",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
... | Add the given overlay from the cached remote list to your locally
installed overlays. Specify 'ALL' to add all overlays from the
remote list.
Return a list of the new overlay(s) added:
CLI Example:
.. code-block:: bash
salt '*' layman.add <overlay name> | [
"Add",
"the",
"given",
"overlay",
"from",
"the",
"cached",
"remote",
"list",
"to",
"your",
"locally",
"installed",
"overlays",
".",
"Specify",
"ALL",
"to",
"add",
"all",
"overlays",
"from",
"the",
"remote",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/layman.py#L33-L65 | train |
saltstack/salt | salt/modules/layman.py | delete | def delete(overlay):
'''
Remove the given overlay from the your locally installed overlays.
Specify 'ALL' to remove all overlays.
Return a list of the overlays(s) that were removed:
CLI Example:
.. code-block:: bash
salt '*' layman.delete <overlay name>
'''
ret = list()
old_overlays = list_local()
cmd = 'layman --quietness=0 --delete {0}'.format(overlay)
delete_attempt = __salt__['cmd.run_all'](cmd, python_shell=False)
if delete_attempt['retcode'] != 0:
raise salt.exceptions.CommandExecutionError(delete_attempt['stdout'])
new_overlays = list_local()
# If we now have no overlays added, We need to ensure that the make.conf
# does not source layman's make.conf, as it will break emerge
if not new_overlays:
srcline = 'source /var/lib/layman/make.conf'
makeconf = _get_makeconf()
if __salt__['file.contains'](makeconf, 'layman'):
__salt__['file.sed'](makeconf, srcline, '')
ret = [overlay for overlay in old_overlays if overlay not in new_overlays]
return ret | python | def delete(overlay):
'''
Remove the given overlay from the your locally installed overlays.
Specify 'ALL' to remove all overlays.
Return a list of the overlays(s) that were removed:
CLI Example:
.. code-block:: bash
salt '*' layman.delete <overlay name>
'''
ret = list()
old_overlays = list_local()
cmd = 'layman --quietness=0 --delete {0}'.format(overlay)
delete_attempt = __salt__['cmd.run_all'](cmd, python_shell=False)
if delete_attempt['retcode'] != 0:
raise salt.exceptions.CommandExecutionError(delete_attempt['stdout'])
new_overlays = list_local()
# If we now have no overlays added, We need to ensure that the make.conf
# does not source layman's make.conf, as it will break emerge
if not new_overlays:
srcline = 'source /var/lib/layman/make.conf'
makeconf = _get_makeconf()
if __salt__['file.contains'](makeconf, 'layman'):
__salt__['file.sed'](makeconf, srcline, '')
ret = [overlay for overlay in old_overlays if overlay not in new_overlays]
return ret | [
"def",
"delete",
"(",
"overlay",
")",
":",
"ret",
"=",
"list",
"(",
")",
"old_overlays",
"=",
"list_local",
"(",
")",
"cmd",
"=",
"'layman --quietness=0 --delete {0}'",
".",
"format",
"(",
"overlay",
")",
"delete_attempt",
"=",
"__salt__",
"[",
"'cmd.run_all'"... | Remove the given overlay from the your locally installed overlays.
Specify 'ALL' to remove all overlays.
Return a list of the overlays(s) that were removed:
CLI Example:
.. code-block:: bash
salt '*' layman.delete <overlay name> | [
"Remove",
"the",
"given",
"overlay",
"from",
"the",
"your",
"locally",
"installed",
"overlays",
".",
"Specify",
"ALL",
"to",
"remove",
"all",
"overlays",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/layman.py#L68-L98 | train |
saltstack/salt | salt/modules/layman.py | list_local | def list_local():
'''
List the locally installed overlays.
Return a list of installed overlays:
CLI Example:
.. code-block:: bash
salt '*' layman.list_local
'''
cmd = 'layman --quietness=1 --list-local --nocolor'
out = __salt__['cmd.run'](cmd, python_shell=False).split('\n')
ret = [line.split()[1] for line in out if len(line.split()) > 2]
return ret | python | def list_local():
'''
List the locally installed overlays.
Return a list of installed overlays:
CLI Example:
.. code-block:: bash
salt '*' layman.list_local
'''
cmd = 'layman --quietness=1 --list-local --nocolor'
out = __salt__['cmd.run'](cmd, python_shell=False).split('\n')
ret = [line.split()[1] for line in out if len(line.split()) > 2]
return ret | [
"def",
"list_local",
"(",
")",
":",
"cmd",
"=",
"'layman --quietness=1 --list-local --nocolor'",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
".",
"split",
"(",
"'\\n'",
")",
"ret",
"=",
"[",
"line",
".... | List the locally installed overlays.
Return a list of installed overlays:
CLI Example:
.. code-block:: bash
salt '*' layman.list_local | [
"List",
"the",
"locally",
"installed",
"overlays",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/layman.py#L119-L134 | train |
saltstack/salt | salt/auth/django.py | __django_auth_setup | def __django_auth_setup():
'''
Prepare the connection to the Django authentication framework
'''
if django.VERSION >= (1, 7):
django.setup()
global DJANGO_AUTH_CLASS
if DJANGO_AUTH_CLASS is not None:
return
# Versions 1.7 and later of Django don't pull models until
# they are needed. When using framework facilities outside the
# web application container we need to run django.setup() to
# get the model definitions cached.
if '^model' in __opts__['external_auth']['django']:
django_model_fullname = __opts__['external_auth']['django']['^model']
django_model_name = django_model_fullname.split('.')[-1]
django_module_name = '.'.join(django_model_fullname.split('.')[0:-1])
django_auth_module = __import__(django_module_name, globals(), locals(), 'SaltExternalAuthModel')
DJANGO_AUTH_CLASS_str = 'django_auth_module.{0}'.format(django_model_name)
DJANGO_AUTH_CLASS = eval(DJANGO_AUTH_CLASS_str) | python | def __django_auth_setup():
'''
Prepare the connection to the Django authentication framework
'''
if django.VERSION >= (1, 7):
django.setup()
global DJANGO_AUTH_CLASS
if DJANGO_AUTH_CLASS is not None:
return
# Versions 1.7 and later of Django don't pull models until
# they are needed. When using framework facilities outside the
# web application container we need to run django.setup() to
# get the model definitions cached.
if '^model' in __opts__['external_auth']['django']:
django_model_fullname = __opts__['external_auth']['django']['^model']
django_model_name = django_model_fullname.split('.')[-1]
django_module_name = '.'.join(django_model_fullname.split('.')[0:-1])
django_auth_module = __import__(django_module_name, globals(), locals(), 'SaltExternalAuthModel')
DJANGO_AUTH_CLASS_str = 'django_auth_module.{0}'.format(django_model_name)
DJANGO_AUTH_CLASS = eval(DJANGO_AUTH_CLASS_str) | [
"def",
"__django_auth_setup",
"(",
")",
":",
"if",
"django",
".",
"VERSION",
">=",
"(",
"1",
",",
"7",
")",
":",
"django",
".",
"setup",
"(",
")",
"global",
"DJANGO_AUTH_CLASS",
"if",
"DJANGO_AUTH_CLASS",
"is",
"not",
"None",
":",
"return",
"# Versions 1.7... | Prepare the connection to the Django authentication framework | [
"Prepare",
"the",
"connection",
"to",
"the",
"Django",
"authentication",
"framework"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/django.py#L93-L116 | train |
saltstack/salt | salt/auth/django.py | auth | def auth(username, password):
'''
Simple Django auth
'''
django_auth_path = __opts__['django_auth_path']
if django_auth_path not in sys.path:
sys.path.append(django_auth_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', __opts__['django_auth_settings'])
__django_auth_setup()
if not is_connection_usable():
connection.close()
import django.contrib.auth # pylint: disable=import-error,3rd-party-module-not-gated
user = django.contrib.auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
log.debug('Django authentication successful')
return True
else:
log.debug('Django authentication: the password is valid but the account is disabled.')
else:
log.debug('Django authentication failed.')
return False | python | def auth(username, password):
'''
Simple Django auth
'''
django_auth_path = __opts__['django_auth_path']
if django_auth_path not in sys.path:
sys.path.append(django_auth_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', __opts__['django_auth_settings'])
__django_auth_setup()
if not is_connection_usable():
connection.close()
import django.contrib.auth # pylint: disable=import-error,3rd-party-module-not-gated
user = django.contrib.auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
log.debug('Django authentication successful')
return True
else:
log.debug('Django authentication: the password is valid but the account is disabled.')
else:
log.debug('Django authentication failed.')
return False | [
"def",
"auth",
"(",
"username",
",",
"password",
")",
":",
"django_auth_path",
"=",
"__opts__",
"[",
"'django_auth_path'",
"]",
"if",
"django_auth_path",
"not",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"append",
"(",
"django_auth_path",
")",
... | Simple Django auth | [
"Simple",
"Django",
"auth"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/django.py#L119-L144 | train |
saltstack/salt | salt/matchers/confirm_top.py | confirm_top | def confirm_top(match, data, nodegroups=None):
'''
Takes the data passed to a top file environment and determines if the
data matches this minion
'''
matcher = 'compound'
if not data:
log.error('Received bad data when setting the match from the top '
'file')
return False
for item in data:
if isinstance(item, dict):
if 'match' in item:
matcher = item['match']
matchers = salt.loader.matchers(__opts__)
funcname = matcher + '_match.match'
if matcher == 'nodegroup':
return matchers[funcname](match, nodegroups)
else:
m = matchers[funcname]
return m(match) | python | def confirm_top(match, data, nodegroups=None):
'''
Takes the data passed to a top file environment and determines if the
data matches this minion
'''
matcher = 'compound'
if not data:
log.error('Received bad data when setting the match from the top '
'file')
return False
for item in data:
if isinstance(item, dict):
if 'match' in item:
matcher = item['match']
matchers = salt.loader.matchers(__opts__)
funcname = matcher + '_match.match'
if matcher == 'nodegroup':
return matchers[funcname](match, nodegroups)
else:
m = matchers[funcname]
return m(match) | [
"def",
"confirm_top",
"(",
"match",
",",
"data",
",",
"nodegroups",
"=",
"None",
")",
":",
"matcher",
"=",
"'compound'",
"if",
"not",
"data",
":",
"log",
".",
"error",
"(",
"'Received bad data when setting the match from the top '",
"'file'",
")",
"return",
"Fal... | Takes the data passed to a top file environment and determines if the
data matches this minion | [
"Takes",
"the",
"data",
"passed",
"to",
"a",
"top",
"file",
"environment",
"and",
"determines",
"if",
"the",
"data",
"matches",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/confirm_top.py#L15-L36 | train |
saltstack/salt | salt/modules/win_servermanager.py | list_installed | def list_installed():
'''
List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
Returns:
dict: A dictionary of installed features
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed
'''
cmd = 'Get-WindowsFeature ' \
'-ErrorAction SilentlyContinue ' \
'-WarningAction SilentlyContinue ' \
'| Select DisplayName,Name,Installed'
features = _pshell_json(cmd)
ret = {}
for entry in features:
if entry['Installed']:
ret[entry['Name']] = entry['DisplayName']
return ret | python | def list_installed():
'''
List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
Returns:
dict: A dictionary of installed features
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed
'''
cmd = 'Get-WindowsFeature ' \
'-ErrorAction SilentlyContinue ' \
'-WarningAction SilentlyContinue ' \
'| Select DisplayName,Name,Installed'
features = _pshell_json(cmd)
ret = {}
for entry in features:
if entry['Installed']:
ret[entry['Name']] = entry['DisplayName']
return ret | [
"def",
"list_installed",
"(",
")",
":",
"cmd",
"=",
"'Get-WindowsFeature '",
"'-ErrorAction SilentlyContinue '",
"'-WarningAction SilentlyContinue '",
"'| Select DisplayName,Name,Installed'",
"features",
"=",
"_pshell_json",
"(",
"cmd",
")",
"ret",
"=",
"{",
"}",
"for",
"... | List installed features. Supported on Windows Server 2008 and Windows 8 and
newer.
Returns:
dict: A dictionary of installed features
CLI Example:
.. code-block:: bash
salt '*' win_servermanager.list_installed | [
"List",
"installed",
"features",
".",
"Supported",
"on",
"Windows",
"Server",
"2008",
"and",
"Windows",
"8",
"and",
"newer",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_servermanager.py#L108-L133 | train |
saltstack/salt | salt/modules/win_servermanager.py | install | def install(feature, recurse=False, restart=False, source=None, exclude=None):
r'''
Install a feature
.. note::
Some features require reboot after un/installation, if so until the
server is restarted other features can not be installed!
.. note::
Some features take a long time to complete un/installation, set -t with
a long timeout
Args:
feature (str, list):
The name of the feature(s) to install. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be installed.
recurse (Options[bool]):
Install all sub-features. Default is False
restart (Optional[bool]):
Restarts the computer when installation is complete, if required by
the role/feature installed. Will also trigger a reboot if an item
in ``exclude`` requires a reboot to be properly removed. Default is
False
source (Optional[str]):
Path to the source files if missing from the target system. None
means that the system will use windows update services to find the
required files. Default is None
exclude (Optional[str]):
The name of the feature to exclude when installing the named
feature. This can be a single feature, a string of features in a
comma-delimited list (no spaces), or a list of features.
.. warning::
As there is no exclude option for the ``Add-WindowsFeature``
or ``Install-WindowsFeature`` PowerShell commands the features
named in ``exclude`` will be installed with other sub-features
and will then be removed. **If the feature named in ``exclude``
is not a sub-feature of one of the installed items it will still
be removed.**
Returns:
dict: A dictionary containing the results of the install
CLI Example:
.. code-block:: bash
# Install the Telnet Client passing a single string
salt '*' win_servermanager.install Telnet-Client
# Install the TFTP Client and the SNMP Service passing a comma-delimited
# string. Install all sub-features
salt '*' win_servermanager.install TFTP-Client,SNMP-Service recurse=True
# Install the TFTP Client from d:\side-by-side
salt '*' win_servermanager.install TFTP-Client source=d:\\side-by-side
# Install the XPS Viewer, SNMP Service, and Remote Access passing a
# list. Install all sub-features, but exclude the Web Server
salt '*' win_servermanager.install "['XPS-Viewer', 'SNMP-Service', 'RemoteAccess']" True recurse=True exclude="Web-Server"
'''
# If it is a list of features, make it a comma delimited string
if isinstance(feature, list):
feature = ','.join(feature)
# Use Install-WindowsFeature on Windows 2012 (osversion 6.2) and later
# minions. Default to Add-WindowsFeature for earlier releases of Windows.
# The newer command makes management tools optional so add them for parity
# with old behavior.
command = 'Add-WindowsFeature'
management_tools = ''
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.2') >= 0:
command = 'Install-WindowsFeature'
management_tools = '-IncludeManagementTools'
cmd = '{0} -Name {1} {2} {3} {4} ' \
'-WarningAction SilentlyContinue'\
.format(command, _cmd_quote(feature), management_tools,
'-IncludeAllSubFeature' if recurse else '',
'' if source is None else '-Source {0}'.format(source))
out = _pshell_json(cmd)
# Uninstall items in the exclude list
# The Install-WindowsFeature command doesn't have the concept of an exclude
# list. So you install first, then remove
if exclude is not None:
removed = remove(exclude)
# Results are stored in a list of dictionaries in `FeatureResult`
if out['FeatureResult']:
ret = {'ExitCode': out['ExitCode'],
'RestartNeeded': False,
'Restarted': False,
'Features': {},
'Success': out['Success']}
# FeatureResult is a list of dicts, so each item is a dict
for item in out['FeatureResult']:
ret['Features'][item['Name']] = {
'DisplayName': item['DisplayName'],
'Message': item['Message'],
'RestartNeeded': item['RestartNeeded'],
'SkipReason': item['SkipReason'],
'Success': item['Success']
}
if item['RestartNeeded']:
ret['RestartNeeded'] = True
# Only items that installed are in the list of dictionaries
# Add 'Already installed' for features that aren't in the list of dicts
for item in feature.split(','):
if item not in ret['Features']:
ret['Features'][item] = {'Message': 'Already installed'}
# Some items in the exclude list were removed after installation
# Show what was done, update the dict
if exclude is not None:
# Features is a dict, so it only iterates over the keys
for item in removed['Features']:
if item in ret['Features']:
ret['Features'][item] = {
'Message': 'Removed after installation (exclude)',
'DisplayName': removed['Features'][item]['DisplayName'],
'RestartNeeded': removed['Features'][item]['RestartNeeded'],
'SkipReason': removed['Features'][item]['SkipReason'],
'Success': removed['Features'][item]['Success']
}
# Exclude items might need a restart
if removed['Features'][item]['RestartNeeded']:
ret['RestartNeeded'] = True
# Restart here if needed
if restart:
if ret['RestartNeeded']:
if __salt__['system.restart'](in_seconds=True):
ret['Restarted'] = True
return ret
else:
# If we get here then all features were already installed
ret = {'ExitCode': out['ExitCode'],
'Features': {},
'RestartNeeded': False,
'Restarted': False,
'Success': out['Success']}
for item in feature.split(','):
ret['Features'][item] = {'Message': 'Already installed'}
return ret | python | def install(feature, recurse=False, restart=False, source=None, exclude=None):
r'''
Install a feature
.. note::
Some features require reboot after un/installation, if so until the
server is restarted other features can not be installed!
.. note::
Some features take a long time to complete un/installation, set -t with
a long timeout
Args:
feature (str, list):
The name of the feature(s) to install. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be installed.
recurse (Options[bool]):
Install all sub-features. Default is False
restart (Optional[bool]):
Restarts the computer when installation is complete, if required by
the role/feature installed. Will also trigger a reboot if an item
in ``exclude`` requires a reboot to be properly removed. Default is
False
source (Optional[str]):
Path to the source files if missing from the target system. None
means that the system will use windows update services to find the
required files. Default is None
exclude (Optional[str]):
The name of the feature to exclude when installing the named
feature. This can be a single feature, a string of features in a
comma-delimited list (no spaces), or a list of features.
.. warning::
As there is no exclude option for the ``Add-WindowsFeature``
or ``Install-WindowsFeature`` PowerShell commands the features
named in ``exclude`` will be installed with other sub-features
and will then be removed. **If the feature named in ``exclude``
is not a sub-feature of one of the installed items it will still
be removed.**
Returns:
dict: A dictionary containing the results of the install
CLI Example:
.. code-block:: bash
# Install the Telnet Client passing a single string
salt '*' win_servermanager.install Telnet-Client
# Install the TFTP Client and the SNMP Service passing a comma-delimited
# string. Install all sub-features
salt '*' win_servermanager.install TFTP-Client,SNMP-Service recurse=True
# Install the TFTP Client from d:\side-by-side
salt '*' win_servermanager.install TFTP-Client source=d:\\side-by-side
# Install the XPS Viewer, SNMP Service, and Remote Access passing a
# list. Install all sub-features, but exclude the Web Server
salt '*' win_servermanager.install "['XPS-Viewer', 'SNMP-Service', 'RemoteAccess']" True recurse=True exclude="Web-Server"
'''
# If it is a list of features, make it a comma delimited string
if isinstance(feature, list):
feature = ','.join(feature)
# Use Install-WindowsFeature on Windows 2012 (osversion 6.2) and later
# minions. Default to Add-WindowsFeature for earlier releases of Windows.
# The newer command makes management tools optional so add them for parity
# with old behavior.
command = 'Add-WindowsFeature'
management_tools = ''
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.2') >= 0:
command = 'Install-WindowsFeature'
management_tools = '-IncludeManagementTools'
cmd = '{0} -Name {1} {2} {3} {4} ' \
'-WarningAction SilentlyContinue'\
.format(command, _cmd_quote(feature), management_tools,
'-IncludeAllSubFeature' if recurse else '',
'' if source is None else '-Source {0}'.format(source))
out = _pshell_json(cmd)
# Uninstall items in the exclude list
# The Install-WindowsFeature command doesn't have the concept of an exclude
# list. So you install first, then remove
if exclude is not None:
removed = remove(exclude)
# Results are stored in a list of dictionaries in `FeatureResult`
if out['FeatureResult']:
ret = {'ExitCode': out['ExitCode'],
'RestartNeeded': False,
'Restarted': False,
'Features': {},
'Success': out['Success']}
# FeatureResult is a list of dicts, so each item is a dict
for item in out['FeatureResult']:
ret['Features'][item['Name']] = {
'DisplayName': item['DisplayName'],
'Message': item['Message'],
'RestartNeeded': item['RestartNeeded'],
'SkipReason': item['SkipReason'],
'Success': item['Success']
}
if item['RestartNeeded']:
ret['RestartNeeded'] = True
# Only items that installed are in the list of dictionaries
# Add 'Already installed' for features that aren't in the list of dicts
for item in feature.split(','):
if item not in ret['Features']:
ret['Features'][item] = {'Message': 'Already installed'}
# Some items in the exclude list were removed after installation
# Show what was done, update the dict
if exclude is not None:
# Features is a dict, so it only iterates over the keys
for item in removed['Features']:
if item in ret['Features']:
ret['Features'][item] = {
'Message': 'Removed after installation (exclude)',
'DisplayName': removed['Features'][item]['DisplayName'],
'RestartNeeded': removed['Features'][item]['RestartNeeded'],
'SkipReason': removed['Features'][item]['SkipReason'],
'Success': removed['Features'][item]['Success']
}
# Exclude items might need a restart
if removed['Features'][item]['RestartNeeded']:
ret['RestartNeeded'] = True
# Restart here if needed
if restart:
if ret['RestartNeeded']:
if __salt__['system.restart'](in_seconds=True):
ret['Restarted'] = True
return ret
else:
# If we get here then all features were already installed
ret = {'ExitCode': out['ExitCode'],
'Features': {},
'RestartNeeded': False,
'Restarted': False,
'Success': out['Success']}
for item in feature.split(','):
ret['Features'][item] = {'Message': 'Already installed'}
return ret | [
"def",
"install",
"(",
"feature",
",",
"recurse",
"=",
"False",
",",
"restart",
"=",
"False",
",",
"source",
"=",
"None",
",",
"exclude",
"=",
"None",
")",
":",
"# If it is a list of features, make it a comma delimited string",
"if",
"isinstance",
"(",
"feature",
... | r'''
Install a feature
.. note::
Some features require reboot after un/installation, if so until the
server is restarted other features can not be installed!
.. note::
Some features take a long time to complete un/installation, set -t with
a long timeout
Args:
feature (str, list):
The name of the feature(s) to install. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be installed.
recurse (Options[bool]):
Install all sub-features. Default is False
restart (Optional[bool]):
Restarts the computer when installation is complete, if required by
the role/feature installed. Will also trigger a reboot if an item
in ``exclude`` requires a reboot to be properly removed. Default is
False
source (Optional[str]):
Path to the source files if missing from the target system. None
means that the system will use windows update services to find the
required files. Default is None
exclude (Optional[str]):
The name of the feature to exclude when installing the named
feature. This can be a single feature, a string of features in a
comma-delimited list (no spaces), or a list of features.
.. warning::
As there is no exclude option for the ``Add-WindowsFeature``
or ``Install-WindowsFeature`` PowerShell commands the features
named in ``exclude`` will be installed with other sub-features
and will then be removed. **If the feature named in ``exclude``
is not a sub-feature of one of the installed items it will still
be removed.**
Returns:
dict: A dictionary containing the results of the install
CLI Example:
.. code-block:: bash
# Install the Telnet Client passing a single string
salt '*' win_servermanager.install Telnet-Client
# Install the TFTP Client and the SNMP Service passing a comma-delimited
# string. Install all sub-features
salt '*' win_servermanager.install TFTP-Client,SNMP-Service recurse=True
# Install the TFTP Client from d:\side-by-side
salt '*' win_servermanager.install TFTP-Client source=d:\\side-by-side
# Install the XPS Viewer, SNMP Service, and Remote Access passing a
# list. Install all sub-features, but exclude the Web Server
salt '*' win_servermanager.install "['XPS-Viewer', 'SNMP-Service', 'RemoteAccess']" True recurse=True exclude="Web-Server" | [
"r",
"Install",
"a",
"feature"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_servermanager.py#L136-L298 | train |
saltstack/salt | salt/modules/win_servermanager.py | remove | def remove(feature, remove_payload=False, restart=False):
r'''
Remove an installed feature
.. note::
Some features require a reboot after installation/uninstallation. If
one of these features are modified, then other features cannot be
installed until the server is restarted. Additionally, some features
take a while to complete installation/uninstallation, so it is a good
idea to use the ``-t`` option to set a longer timeout.
Args:
feature (str, list):
The name of the feature(s) to remove. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be removed.
remove_payload (Optional[bool]):
True will cause the feature to be removed from the side-by-side
store (``%SystemDrive%:\Windows\WinSxS``). Default is False
restart (Optional[bool]):
Restarts the computer when uninstall is complete, if required by the
role/feature removed. Default is False
Returns:
dict: A dictionary containing the results of the uninstall
CLI Example:
.. code-block:: bash
salt -t 600 '*' win_servermanager.remove Telnet-Client
'''
# If it is a list of features, make it a comma delimited string
if isinstance(feature, list):
feature = ','.join(feature)
# Use Uninstall-WindowsFeature on Windows 2012 (osversion 6.2) and later
# minions. Default to Remove-WindowsFeature for earlier releases of Windows.
# The newer command makes management tools optional so add them for parity
# with old behavior.
command = 'Remove-WindowsFeature'
management_tools = ''
_remove_payload = ''
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.2') >= 0:
command = 'Uninstall-WindowsFeature'
management_tools = '-IncludeManagementTools'
# Only available with the `Uninstall-WindowsFeature` command
if remove_payload:
_remove_payload = '-Remove'
cmd = '{0} -Name {1} {2} {3} {4} ' \
'-WarningAction SilentlyContinue'\
.format(command, _cmd_quote(feature), management_tools,
_remove_payload,
'-Restart' if restart else '')
try:
out = _pshell_json(cmd)
except CommandExecutionError as exc:
if 'ArgumentNotValid' in exc.message:
raise CommandExecutionError('Invalid Feature Name', info=exc.info)
raise
# Results are stored in a list of dictionaries in `FeatureResult`
if out['FeatureResult']:
ret = {'ExitCode': out['ExitCode'],
'RestartNeeded': False,
'Restarted': False,
'Features': {},
'Success': out['Success']}
for item in out['FeatureResult']:
ret['Features'][item['Name']] = {
'DisplayName': item['DisplayName'],
'Message': item['Message'],
'RestartNeeded': item['RestartNeeded'],
'SkipReason': item['SkipReason'],
'Success': item['Success']
}
# Only items that installed are in the list of dictionaries
# Add 'Not installed' for features that aren't in the list of dicts
for item in feature.split(','):
if item not in ret['Features']:
ret['Features'][item] = {'Message': 'Not installed'}
return ret
else:
# If we get here then none of the features were installed
ret = {'ExitCode': out['ExitCode'],
'Features': {},
'RestartNeeded': False,
'Restarted': False,
'Success': out['Success']}
for item in feature.split(','):
ret['Features'][item] = {'Message': 'Not installed'}
return ret | python | def remove(feature, remove_payload=False, restart=False):
r'''
Remove an installed feature
.. note::
Some features require a reboot after installation/uninstallation. If
one of these features are modified, then other features cannot be
installed until the server is restarted. Additionally, some features
take a while to complete installation/uninstallation, so it is a good
idea to use the ``-t`` option to set a longer timeout.
Args:
feature (str, list):
The name of the feature(s) to remove. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be removed.
remove_payload (Optional[bool]):
True will cause the feature to be removed from the side-by-side
store (``%SystemDrive%:\Windows\WinSxS``). Default is False
restart (Optional[bool]):
Restarts the computer when uninstall is complete, if required by the
role/feature removed. Default is False
Returns:
dict: A dictionary containing the results of the uninstall
CLI Example:
.. code-block:: bash
salt -t 600 '*' win_servermanager.remove Telnet-Client
'''
# If it is a list of features, make it a comma delimited string
if isinstance(feature, list):
feature = ','.join(feature)
# Use Uninstall-WindowsFeature on Windows 2012 (osversion 6.2) and later
# minions. Default to Remove-WindowsFeature for earlier releases of Windows.
# The newer command makes management tools optional so add them for parity
# with old behavior.
command = 'Remove-WindowsFeature'
management_tools = ''
_remove_payload = ''
if salt.utils.versions.version_cmp(__grains__['osversion'], '6.2') >= 0:
command = 'Uninstall-WindowsFeature'
management_tools = '-IncludeManagementTools'
# Only available with the `Uninstall-WindowsFeature` command
if remove_payload:
_remove_payload = '-Remove'
cmd = '{0} -Name {1} {2} {3} {4} ' \
'-WarningAction SilentlyContinue'\
.format(command, _cmd_quote(feature), management_tools,
_remove_payload,
'-Restart' if restart else '')
try:
out = _pshell_json(cmd)
except CommandExecutionError as exc:
if 'ArgumentNotValid' in exc.message:
raise CommandExecutionError('Invalid Feature Name', info=exc.info)
raise
# Results are stored in a list of dictionaries in `FeatureResult`
if out['FeatureResult']:
ret = {'ExitCode': out['ExitCode'],
'RestartNeeded': False,
'Restarted': False,
'Features': {},
'Success': out['Success']}
for item in out['FeatureResult']:
ret['Features'][item['Name']] = {
'DisplayName': item['DisplayName'],
'Message': item['Message'],
'RestartNeeded': item['RestartNeeded'],
'SkipReason': item['SkipReason'],
'Success': item['Success']
}
# Only items that installed are in the list of dictionaries
# Add 'Not installed' for features that aren't in the list of dicts
for item in feature.split(','):
if item not in ret['Features']:
ret['Features'][item] = {'Message': 'Not installed'}
return ret
else:
# If we get here then none of the features were installed
ret = {'ExitCode': out['ExitCode'],
'Features': {},
'RestartNeeded': False,
'Restarted': False,
'Success': out['Success']}
for item in feature.split(','):
ret['Features'][item] = {'Message': 'Not installed'}
return ret | [
"def",
"remove",
"(",
"feature",
",",
"remove_payload",
"=",
"False",
",",
"restart",
"=",
"False",
")",
":",
"# If it is a list of features, make it a comma delimited string",
"if",
"isinstance",
"(",
"feature",
",",
"list",
")",
":",
"feature",
"=",
"','",
".",
... | r'''
Remove an installed feature
.. note::
Some features require a reboot after installation/uninstallation. If
one of these features are modified, then other features cannot be
installed until the server is restarted. Additionally, some features
take a while to complete installation/uninstallation, so it is a good
idea to use the ``-t`` option to set a longer timeout.
Args:
feature (str, list):
The name of the feature(s) to remove. This can be a single feature,
a string of features in a comma delimited list (no spaces), or a
list of features.
.. versionadded:: 2018.3.0
Added the ability to pass a list of features to be removed.
remove_payload (Optional[bool]):
True will cause the feature to be removed from the side-by-side
store (``%SystemDrive%:\Windows\WinSxS``). Default is False
restart (Optional[bool]):
Restarts the computer when uninstall is complete, if required by the
role/feature removed. Default is False
Returns:
dict: A dictionary containing the results of the uninstall
CLI Example:
.. code-block:: bash
salt -t 600 '*' win_servermanager.remove Telnet-Client | [
"r",
"Remove",
"an",
"installed",
"feature"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_servermanager.py#L301-L407 | train |
saltstack/salt | salt/modules/iwtools.py | scan | def scan(iface, style=None):
'''
List networks on a wireless interface
CLI Examples:
salt minion iwtools.scan wlp3s0
salt minion iwtools.scan wlp3s0 list
'''
if not _valid_iface(iface):
raise SaltInvocationError(
'The interface specified is not valid'
)
out = __salt__['cmd.run']('iwlist {0} scan'.format(iface))
if 'Network is down' in out:
__salt__['cmd.run']('ip link set {0} up'.format(iface))
out = __salt__['cmd.run']('iwlist {0} scan'.format(iface))
ret = {}
tmp = {}
for line in out.splitlines():
if not line.strip():
continue
if 'Scan completed' in line:
continue
if line.strip().startswith('Cell'):
comps = line.split(' - ')
line = comps[1]
if tmp:
ret[tmp['Address']] = tmp
tmp = {}
comps = line.split(':')
if comps[0].strip() == 'Address':
# " is a valid character in SSIDs, but iwlist likes to wrap SSIDs in them
comps[1] = comps[1].lstrip('"').rstrip('"')
if comps[0].strip() == 'IE':
if 'IE' not in tmp:
tmp['IE'] = []
tmp['IE'].append(':'.join(comps[1:]).strip())
else:
tmp[comps[0].strip()] = ':'.join(comps[1:]).strip()
ret[tmp['Address']] = tmp
if style == 'list':
return ret.keys()
return ret | python | def scan(iface, style=None):
'''
List networks on a wireless interface
CLI Examples:
salt minion iwtools.scan wlp3s0
salt minion iwtools.scan wlp3s0 list
'''
if not _valid_iface(iface):
raise SaltInvocationError(
'The interface specified is not valid'
)
out = __salt__['cmd.run']('iwlist {0} scan'.format(iface))
if 'Network is down' in out:
__salt__['cmd.run']('ip link set {0} up'.format(iface))
out = __salt__['cmd.run']('iwlist {0} scan'.format(iface))
ret = {}
tmp = {}
for line in out.splitlines():
if not line.strip():
continue
if 'Scan completed' in line:
continue
if line.strip().startswith('Cell'):
comps = line.split(' - ')
line = comps[1]
if tmp:
ret[tmp['Address']] = tmp
tmp = {}
comps = line.split(':')
if comps[0].strip() == 'Address':
# " is a valid character in SSIDs, but iwlist likes to wrap SSIDs in them
comps[1] = comps[1].lstrip('"').rstrip('"')
if comps[0].strip() == 'IE':
if 'IE' not in tmp:
tmp['IE'] = []
tmp['IE'].append(':'.join(comps[1:]).strip())
else:
tmp[comps[0].strip()] = ':'.join(comps[1:]).strip()
ret[tmp['Address']] = tmp
if style == 'list':
return ret.keys()
return ret | [
"def",
"scan",
"(",
"iface",
",",
"style",
"=",
"None",
")",
":",
"if",
"not",
"_valid_iface",
"(",
"iface",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'The interface specified is not valid'",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'i... | List networks on a wireless interface
CLI Examples:
salt minion iwtools.scan wlp3s0
salt minion iwtools.scan wlp3s0 list | [
"List",
"networks",
"on",
"a",
"wireless",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iwtools.py#L28-L75 | train |
saltstack/salt | salt/modules/iwtools.py | set_mode | def set_mode(iface, mode):
'''
List networks on a wireless interface
CLI Example:
salt minion iwtools.set_mode wlp3s0 Managed
'''
if not _valid_iface(iface):
raise SaltInvocationError(
'The interface specified is not valid'
)
valid_modes = ('Managed', 'Ad-Hoc', 'Master', 'Repeater', 'Secondary', 'Monitor', 'Auto')
if mode not in valid_modes:
raise SaltInvocationError(
'One of the following modes must be specified: {0}'.format(', '.join(valid_modes))
)
__salt__['ip.down'](iface)
out = __salt__['cmd.run']('iwconfig {0} mode {1}'.format(iface, mode))
__salt__['ip.up'](iface)
return mode | python | def set_mode(iface, mode):
'''
List networks on a wireless interface
CLI Example:
salt minion iwtools.set_mode wlp3s0 Managed
'''
if not _valid_iface(iface):
raise SaltInvocationError(
'The interface specified is not valid'
)
valid_modes = ('Managed', 'Ad-Hoc', 'Master', 'Repeater', 'Secondary', 'Monitor', 'Auto')
if mode not in valid_modes:
raise SaltInvocationError(
'One of the following modes must be specified: {0}'.format(', '.join(valid_modes))
)
__salt__['ip.down'](iface)
out = __salt__['cmd.run']('iwconfig {0} mode {1}'.format(iface, mode))
__salt__['ip.up'](iface)
return mode | [
"def",
"set_mode",
"(",
"iface",
",",
"mode",
")",
":",
"if",
"not",
"_valid_iface",
"(",
"iface",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'The interface specified is not valid'",
")",
"valid_modes",
"=",
"(",
"'Managed'",
",",
"'Ad-Hoc'",
",",
"'Master'... | List networks on a wireless interface
CLI Example:
salt minion iwtools.set_mode wlp3s0 Managed | [
"List",
"networks",
"on",
"a",
"wireless",
"interface"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iwtools.py#L78-L100 | train |
saltstack/salt | salt/modules/iwtools.py | list_interfaces | def list_interfaces(style=None):
'''
List all of the wireless interfaces
CLI Example:
salt minion iwtools.list_interfaces
'''
ret = {}
tmp = None
iface = None
out = __salt__['cmd.run']('iwconfig')
for line in out.splitlines():
if not line:
continue
if 'no wireless extensions' in line:
continue
comps = line.strip().split(' ')
if not line.startswith(' '):
if tmp is not None:
ret[iface] = tmp.copy()
iface = comps.pop(0)
tmp = {'extra': []}
for item in comps:
if ':' in item:
parts = item.split(':')
key = parts[0].strip()
value = parts[1].strip()
if key == 'ESSID':
value = value.lstrip('"').rstrip('"')
tmp[key] = value
elif '=' in item:
parts = item.split('=')
tmp[parts[0].strip()] = parts[1].strip()
else:
tmp['extra'].append(item)
ret[iface] = tmp.copy()
if style == 'list':
return ret.keys()
return ret | python | def list_interfaces(style=None):
'''
List all of the wireless interfaces
CLI Example:
salt minion iwtools.list_interfaces
'''
ret = {}
tmp = None
iface = None
out = __salt__['cmd.run']('iwconfig')
for line in out.splitlines():
if not line:
continue
if 'no wireless extensions' in line:
continue
comps = line.strip().split(' ')
if not line.startswith(' '):
if tmp is not None:
ret[iface] = tmp.copy()
iface = comps.pop(0)
tmp = {'extra': []}
for item in comps:
if ':' in item:
parts = item.split(':')
key = parts[0].strip()
value = parts[1].strip()
if key == 'ESSID':
value = value.lstrip('"').rstrip('"')
tmp[key] = value
elif '=' in item:
parts = item.split('=')
tmp[parts[0].strip()] = parts[1].strip()
else:
tmp['extra'].append(item)
ret[iface] = tmp.copy()
if style == 'list':
return ret.keys()
return ret | [
"def",
"list_interfaces",
"(",
"style",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"tmp",
"=",
"None",
"iface",
"=",
"None",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'iwconfig'",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
... | List all of the wireless interfaces
CLI Example:
salt minion iwtools.list_interfaces | [
"List",
"all",
"of",
"the",
"wireless",
"interfaces"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/iwtools.py#L113-L155 | train |
saltstack/salt | salt/beacons/smartos_vmadm.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
vcfg_ret = True
vcfg_msg = 'Valid beacon configuration'
if not isinstance(config, list):
vcfg_ret = False
vcfg_msg = 'Configuration for vmadm beacon must be a list!'
return vcfg_ret, vcfg_msg | python | def validate(config):
'''
Validate the beacon configuration
'''
vcfg_ret = True
vcfg_msg = 'Valid beacon configuration'
if not isinstance(config, list):
vcfg_ret = False
vcfg_msg = 'Configuration for vmadm beacon must be a list!'
return vcfg_ret, vcfg_msg | [
"def",
"validate",
"(",
"config",
")",
":",
"vcfg_ret",
"=",
"True",
"vcfg_msg",
"=",
"'Valid beacon configuration'",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"vcfg_ret",
"=",
"False",
"vcfg_msg",
"=",
"'Configuration for vmadm beacon must ... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/smartos_vmadm.py#L55-L66 | train |
saltstack/salt | salt/beacons/smartos_vmadm.py | beacon | def beacon(config):
'''
Poll vmadm for changes
'''
ret = []
# NOTE: lookup current images
current_vms = __salt__['vmadm.list'](
keyed=True,
order='uuid,state,alias,hostname,dns_domain',
)
# NOTE: apply configuration
if VMADM_STATE['first_run']:
log.info('Applying configuration for vmadm beacon')
_config = {}
list(map(_config.update, config))
if 'startup_create_event' not in _config or not _config['startup_create_event']:
VMADM_STATE['vms'] = current_vms
# NOTE: create events
for uuid in current_vms:
event = {}
if uuid not in VMADM_STATE['vms']:
event['tag'] = "created/{}".format(uuid)
for label in current_vms[uuid]:
if label == 'state':
continue
event[label] = current_vms[uuid][label]
if event:
ret.append(event)
# NOTE: deleted events
for uuid in VMADM_STATE['vms']:
event = {}
if uuid not in current_vms:
event['tag'] = "deleted/{}".format(uuid)
for label in VMADM_STATE['vms'][uuid]:
if label == 'state':
continue
event[label] = VMADM_STATE['vms'][uuid][label]
if event:
ret.append(event)
# NOTE: state change events
for uuid in current_vms:
event = {}
if VMADM_STATE['first_run'] or \
uuid not in VMADM_STATE['vms'] or \
current_vms[uuid].get('state', 'unknown') != VMADM_STATE['vms'][uuid].get('state', 'unknown'):
event['tag'] = "{}/{}".format(current_vms[uuid].get('state', 'unknown'), uuid)
for label in current_vms[uuid]:
if label == 'state':
continue
event[label] = current_vms[uuid][label]
if event:
ret.append(event)
# NOTE: update stored state
VMADM_STATE['vms'] = current_vms
# NOTE: disable first_run
if VMADM_STATE['first_run']:
VMADM_STATE['first_run'] = False
return ret | python | def beacon(config):
'''
Poll vmadm for changes
'''
ret = []
# NOTE: lookup current images
current_vms = __salt__['vmadm.list'](
keyed=True,
order='uuid,state,alias,hostname,dns_domain',
)
# NOTE: apply configuration
if VMADM_STATE['first_run']:
log.info('Applying configuration for vmadm beacon')
_config = {}
list(map(_config.update, config))
if 'startup_create_event' not in _config or not _config['startup_create_event']:
VMADM_STATE['vms'] = current_vms
# NOTE: create events
for uuid in current_vms:
event = {}
if uuid not in VMADM_STATE['vms']:
event['tag'] = "created/{}".format(uuid)
for label in current_vms[uuid]:
if label == 'state':
continue
event[label] = current_vms[uuid][label]
if event:
ret.append(event)
# NOTE: deleted events
for uuid in VMADM_STATE['vms']:
event = {}
if uuid not in current_vms:
event['tag'] = "deleted/{}".format(uuid)
for label in VMADM_STATE['vms'][uuid]:
if label == 'state':
continue
event[label] = VMADM_STATE['vms'][uuid][label]
if event:
ret.append(event)
# NOTE: state change events
for uuid in current_vms:
event = {}
if VMADM_STATE['first_run'] or \
uuid not in VMADM_STATE['vms'] or \
current_vms[uuid].get('state', 'unknown') != VMADM_STATE['vms'][uuid].get('state', 'unknown'):
event['tag'] = "{}/{}".format(current_vms[uuid].get('state', 'unknown'), uuid)
for label in current_vms[uuid]:
if label == 'state':
continue
event[label] = current_vms[uuid][label]
if event:
ret.append(event)
# NOTE: update stored state
VMADM_STATE['vms'] = current_vms
# NOTE: disable first_run
if VMADM_STATE['first_run']:
VMADM_STATE['first_run'] = False
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"# NOTE: lookup current images",
"current_vms",
"=",
"__salt__",
"[",
"'vmadm.list'",
"]",
"(",
"keyed",
"=",
"True",
",",
"order",
"=",
"'uuid,state,alias,hostname,dns_domain'",
",",
")",
"# NOTE: ... | Poll vmadm for changes | [
"Poll",
"vmadm",
"for",
"changes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/smartos_vmadm.py#L69-L139 | train |
saltstack/salt | salt/modules/mssql.py | tsql_query | def tsql_query(query, **kwargs):
'''
Run a SQL query and return query result as list of tuples, or a list of dictionaries if as_dict was passed, or an empty list if no data is available.
CLI Example:
.. code-block:: bash
salt minion mssql.tsql_query 'SELECT @@version as version' as_dict=True
'''
try:
cur = _get_connection(**kwargs).cursor()
cur.execute(query)
# Making sure the result is JSON serializable
return loads(_MssqlEncoder().encode({'resultset': cur.fetchall()}))['resultset']
except Exception as err:
# Trying to look like the output of cur.fetchall()
return (('Could not run the query', ), (six.text_type(err), )) | python | def tsql_query(query, **kwargs):
'''
Run a SQL query and return query result as list of tuples, or a list of dictionaries if as_dict was passed, or an empty list if no data is available.
CLI Example:
.. code-block:: bash
salt minion mssql.tsql_query 'SELECT @@version as version' as_dict=True
'''
try:
cur = _get_connection(**kwargs).cursor()
cur.execute(query)
# Making sure the result is JSON serializable
return loads(_MssqlEncoder().encode({'resultset': cur.fetchall()}))['resultset']
except Exception as err:
# Trying to look like the output of cur.fetchall()
return (('Could not run the query', ), (six.text_type(err), )) | [
"def",
"tsql_query",
"(",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"cur",
"=",
"_get_connection",
"(",
"*",
"*",
"kwargs",
")",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"query",
")",
"# Making sure the result is JSON serializable... | Run a SQL query and return query result as list of tuples, or a list of dictionaries if as_dict was passed, or an empty list if no data is available.
CLI Example:
.. code-block:: bash
salt minion mssql.tsql_query 'SELECT @@version as version' as_dict=True | [
"Run",
"a",
"SQL",
"query",
"and",
"return",
"query",
"result",
"as",
"list",
"of",
"tuples",
"or",
"a",
"list",
"of",
"dictionaries",
"if",
"as_dict",
"was",
"passed",
"or",
"an",
"empty",
"list",
"if",
"no",
"data",
"is",
"available",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L74-L91 | train |
saltstack/salt | salt/modules/mssql.py | db_create | def db_create(database, containment='NONE', new_database_options=None, **kwargs):
'''
Creates a new database.
Does not update options of existing databases.
new_database_options can only be a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.db_create DB_NAME
'''
if containment not in ['NONE', 'PARTIAL']:
return 'CONTAINMENT can be one of NONE and PARTIAL'
sql = "CREATE DATABASE [{0}] CONTAINMENT = {1} ".format(database, containment)
if new_database_options:
sql += ' WITH ' + ', '.join(new_database_options)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
except Exception as e:
return 'Could not create the login: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | python | def db_create(database, containment='NONE', new_database_options=None, **kwargs):
'''
Creates a new database.
Does not update options of existing databases.
new_database_options can only be a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.db_create DB_NAME
'''
if containment not in ['NONE', 'PARTIAL']:
return 'CONTAINMENT can be one of NONE and PARTIAL'
sql = "CREATE DATABASE [{0}] CONTAINMENT = {1} ".format(database, containment)
if new_database_options:
sql += ' WITH ' + ', '.join(new_database_options)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
except Exception as e:
return 'Could not create the login: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | [
"def",
"db_create",
"(",
"database",
",",
"containment",
"=",
"'NONE'",
",",
"new_database_options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"containment",
"not",
"in",
"[",
"'NONE'",
",",
"'PARTIAL'",
"]",
":",
"return",
"'CONTAINMENT can be o... | Creates a new database.
Does not update options of existing databases.
new_database_options can only be a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.db_create DB_NAME | [
"Creates",
"a",
"new",
"database",
".",
"Does",
"not",
"update",
"options",
"of",
"existing",
"databases",
".",
"new_database_options",
"can",
"only",
"be",
"a",
"list",
"of",
"strings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L134-L164 | train |
saltstack/salt | salt/modules/mssql.py | db_remove | def db_remove(database_name, **kwargs):
'''
Drops a specific database from the MS SQL server.
It will not drop any of 'master', 'model', 'msdb' or 'tempdb'.
CLI Example:
.. code-block:: bash
salt minion mssql.db_remove database_name='DBNAME'
'''
try:
if db_exists(database_name, **kwargs) and database_name not in ['master', 'model', 'msdb', 'tempdb']:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute('ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE'.format(database_name))
cur.execute('DROP DATABASE {0}'.format(database_name))
conn.autocommit(False)
conn.close()
return True
else:
return False
except Exception as e:
return 'Could not find the database: {0}'.format(e) | python | def db_remove(database_name, **kwargs):
'''
Drops a specific database from the MS SQL server.
It will not drop any of 'master', 'model', 'msdb' or 'tempdb'.
CLI Example:
.. code-block:: bash
salt minion mssql.db_remove database_name='DBNAME'
'''
try:
if db_exists(database_name, **kwargs) and database_name not in ['master', 'model', 'msdb', 'tempdb']:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute('ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE'.format(database_name))
cur.execute('DROP DATABASE {0}'.format(database_name))
conn.autocommit(False)
conn.close()
return True
else:
return False
except Exception as e:
return 'Could not find the database: {0}'.format(e) | [
"def",
"db_remove",
"(",
"database_name",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"db_exists",
"(",
"database_name",
",",
"*",
"*",
"kwargs",
")",
"and",
"database_name",
"not",
"in",
"[",
"'master'",
",",
"'model'",
",",
"'msdb'",
",",
"'... | Drops a specific database from the MS SQL server.
It will not drop any of 'master', 'model', 'msdb' or 'tempdb'.
CLI Example:
.. code-block:: bash
salt minion mssql.db_remove database_name='DBNAME' | [
"Drops",
"a",
"specific",
"database",
"from",
"the",
"MS",
"SQL",
"server",
".",
"It",
"will",
"not",
"drop",
"any",
"of",
"master",
"model",
"msdb",
"or",
"tempdb",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L167-L191 | train |
saltstack/salt | salt/modules/mssql.py | role_exists | def role_exists(role, **kwargs):
'''
Checks if a role exists.
CLI Example:
.. code-block:: bash
salt minion mssql.role_exists db_owner
'''
# We should get one, and only one row
return len(tsql_query(query='sp_helprole "{0}"'.format(role), as_dict=True, **kwargs)) == 1 | python | def role_exists(role, **kwargs):
'''
Checks if a role exists.
CLI Example:
.. code-block:: bash
salt minion mssql.role_exists db_owner
'''
# We should get one, and only one row
return len(tsql_query(query='sp_helprole "{0}"'.format(role), as_dict=True, **kwargs)) == 1 | [
"def",
"role_exists",
"(",
"role",
",",
"*",
"*",
"kwargs",
")",
":",
"# We should get one, and only one row",
"return",
"len",
"(",
"tsql_query",
"(",
"query",
"=",
"'sp_helprole \"{0}\"'",
".",
"format",
"(",
"role",
")",
",",
"as_dict",
"=",
"True",
",",
... | Checks if a role exists.
CLI Example:
.. code-block:: bash
salt minion mssql.role_exists db_owner | [
"Checks",
"if",
"a",
"role",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L208-L220 | train |
saltstack/salt | salt/modules/mssql.py | role_create | def role_create(role, owner=None, grants=None, **kwargs):
'''
Creates a new database role.
If no owner is specified, the role will be owned by the user that
executes CREATE ROLE, which is the user argument or mssql.user option.
grants is list of strings.
CLI Example:
.. code-block:: bash
salt minion mssql.role_create role=product01 owner=sysdba grants='["SELECT", "INSERT", "UPDATE", "DELETE", "EXECUTE"]'
'''
if not grants:
grants = []
sql = 'CREATE ROLE {0}'.format(role)
if owner:
sql += ' AUTHORIZATION {0}'.format(owner)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
for grant in grants:
conn.cursor().execute('GRANT {0} TO [{1}]'.format(grant, role))
except Exception as e:
return 'Could not create the role: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | python | def role_create(role, owner=None, grants=None, **kwargs):
'''
Creates a new database role.
If no owner is specified, the role will be owned by the user that
executes CREATE ROLE, which is the user argument or mssql.user option.
grants is list of strings.
CLI Example:
.. code-block:: bash
salt minion mssql.role_create role=product01 owner=sysdba grants='["SELECT", "INSERT", "UPDATE", "DELETE", "EXECUTE"]'
'''
if not grants:
grants = []
sql = 'CREATE ROLE {0}'.format(role)
if owner:
sql += ' AUTHORIZATION {0}'.format(owner)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
for grant in grants:
conn.cursor().execute('GRANT {0} TO [{1}]'.format(grant, role))
except Exception as e:
return 'Could not create the role: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | [
"def",
"role_create",
"(",
"role",
",",
"owner",
"=",
"None",
",",
"grants",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"grants",
":",
"grants",
"=",
"[",
"]",
"sql",
"=",
"'CREATE ROLE {0}'",
".",
"format",
"(",
"role",
")",
"if"... | Creates a new database role.
If no owner is specified, the role will be owned by the user that
executes CREATE ROLE, which is the user argument or mssql.user option.
grants is list of strings.
CLI Example:
.. code-block:: bash
salt minion mssql.role_create role=product01 owner=sysdba grants='["SELECT", "INSERT", "UPDATE", "DELETE", "EXECUTE"]' | [
"Creates",
"a",
"new",
"database",
"role",
".",
"If",
"no",
"owner",
"is",
"specified",
"the",
"role",
"will",
"be",
"owned",
"by",
"the",
"user",
"that",
"executes",
"CREATE",
"ROLE",
"which",
"is",
"the",
"user",
"argument",
"or",
"mssql",
".",
"user",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L223-L257 | train |
saltstack/salt | salt/modules/mssql.py | role_remove | def role_remove(role, **kwargs):
'''
Remove a database role.
CLI Example:
.. code-block:: bash
salt minion mssql.role_create role=test_role01
'''
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute('DROP ROLE {0}'.format(role))
conn.autocommit(True)
conn.close()
return True
except Exception as e:
return 'Could not create the role: {0}'.format(e) | python | def role_remove(role, **kwargs):
'''
Remove a database role.
CLI Example:
.. code-block:: bash
salt minion mssql.role_create role=test_role01
'''
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute('DROP ROLE {0}'.format(role))
conn.autocommit(True)
conn.close()
return True
except Exception as e:
return 'Could not create the role: {0}'.format(e) | [
"def",
"role_remove",
"(",
"role",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"_get_connection",
"(",
"*",
"*",
"kwargs",
")",
"conn",
".",
"autocommit",
"(",
"True",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
... | Remove a database role.
CLI Example:
.. code-block:: bash
salt minion mssql.role_create role=test_role01 | [
"Remove",
"a",
"database",
"role",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L260-L279 | train |
saltstack/salt | salt/modules/mssql.py | login_exists | def login_exists(login, domain='', **kwargs):
'''
Find if a login exists in the MS SQL server.
domain, if provided, will be prepended to login
CLI Example:
.. code-block:: bash
salt minion mssql.login_exists 'LOGIN'
'''
if domain:
login = '{0}\\{1}'.format(domain, login)
try:
# We should get one, and only one row
return len(tsql_query(query="SELECT name FROM sys.syslogins WHERE name='{0}'".format(login), **kwargs)) == 1
except Exception as e:
return 'Could not find the login: {0}'.format(e) | python | def login_exists(login, domain='', **kwargs):
'''
Find if a login exists in the MS SQL server.
domain, if provided, will be prepended to login
CLI Example:
.. code-block:: bash
salt minion mssql.login_exists 'LOGIN'
'''
if domain:
login = '{0}\\{1}'.format(domain, login)
try:
# We should get one, and only one row
return len(tsql_query(query="SELECT name FROM sys.syslogins WHERE name='{0}'".format(login), **kwargs)) == 1
except Exception as e:
return 'Could not find the login: {0}'.format(e) | [
"def",
"login_exists",
"(",
"login",
",",
"domain",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"domain",
":",
"login",
"=",
"'{0}\\\\{1}'",
".",
"format",
"(",
"domain",
",",
"login",
")",
"try",
":",
"# We should get one, and only one row",
"retu... | Find if a login exists in the MS SQL server.
domain, if provided, will be prepended to login
CLI Example:
.. code-block:: bash
salt minion mssql.login_exists 'LOGIN' | [
"Find",
"if",
"a",
"login",
"exists",
"in",
"the",
"MS",
"SQL",
"server",
".",
"domain",
"if",
"provided",
"will",
"be",
"prepended",
"to",
"login"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L282-L300 | train |
saltstack/salt | salt/modules/mssql.py | login_create | def login_create(login, new_login_password=None, new_login_domain='', new_login_roles=None, new_login_options=None, **kwargs):
'''
Creates a new login. Does not update password of existing logins. For
Windows authentication, provide ``new_login_domain``. For SQL Server
authentication, prvide ``new_login_password``. Since hashed passwords are
*varbinary* values, if the ``new_login_password`` is 'int / long', it will
be considered to be HASHED.
new_login_roles
a list of SERVER roles
new_login_options
a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.login_create LOGIN_NAME database=DBNAME [new_login_password=PASSWORD]
'''
# One and only one of password and domain should be specifies
if bool(new_login_password) == bool(new_login_domain):
return False
if login_exists(login, new_login_domain, **kwargs):
return False
if new_login_domain:
login = '{0}\\{1}'.format(new_login_domain, login)
if not new_login_roles:
new_login_roles = []
if not new_login_options:
new_login_options = []
sql = "CREATE LOGIN [{0}] ".format(login)
if new_login_domain:
sql += " FROM WINDOWS "
elif isinstance(new_login_password, six.integer_types):
new_login_options.insert(0, "PASSWORD=0x{0:x} HASHED".format(new_login_password))
else: # Plain test password
new_login_options.insert(0, "PASSWORD=N'{0}'".format(new_login_password))
if new_login_options:
sql += ' WITH ' + ', '.join(new_login_options)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
for role in new_login_roles:
conn.cursor().execute('ALTER SERVER ROLE [{0}] ADD MEMBER [{1}]'.format(role, login))
except Exception as e:
return 'Could not create the login: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | python | def login_create(login, new_login_password=None, new_login_domain='', new_login_roles=None, new_login_options=None, **kwargs):
'''
Creates a new login. Does not update password of existing logins. For
Windows authentication, provide ``new_login_domain``. For SQL Server
authentication, prvide ``new_login_password``. Since hashed passwords are
*varbinary* values, if the ``new_login_password`` is 'int / long', it will
be considered to be HASHED.
new_login_roles
a list of SERVER roles
new_login_options
a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.login_create LOGIN_NAME database=DBNAME [new_login_password=PASSWORD]
'''
# One and only one of password and domain should be specifies
if bool(new_login_password) == bool(new_login_domain):
return False
if login_exists(login, new_login_domain, **kwargs):
return False
if new_login_domain:
login = '{0}\\{1}'.format(new_login_domain, login)
if not new_login_roles:
new_login_roles = []
if not new_login_options:
new_login_options = []
sql = "CREATE LOGIN [{0}] ".format(login)
if new_login_domain:
sql += " FROM WINDOWS "
elif isinstance(new_login_password, six.integer_types):
new_login_options.insert(0, "PASSWORD=0x{0:x} HASHED".format(new_login_password))
else: # Plain test password
new_login_options.insert(0, "PASSWORD=N'{0}'".format(new_login_password))
if new_login_options:
sql += ' WITH ' + ', '.join(new_login_options)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
for role in new_login_roles:
conn.cursor().execute('ALTER SERVER ROLE [{0}] ADD MEMBER [{1}]'.format(role, login))
except Exception as e:
return 'Could not create the login: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | [
"def",
"login_create",
"(",
"login",
",",
"new_login_password",
"=",
"None",
",",
"new_login_domain",
"=",
"''",
",",
"new_login_roles",
"=",
"None",
",",
"new_login_options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# One and only one of password and doma... | Creates a new login. Does not update password of existing logins. For
Windows authentication, provide ``new_login_domain``. For SQL Server
authentication, prvide ``new_login_password``. Since hashed passwords are
*varbinary* values, if the ``new_login_password`` is 'int / long', it will
be considered to be HASHED.
new_login_roles
a list of SERVER roles
new_login_options
a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.login_create LOGIN_NAME database=DBNAME [new_login_password=PASSWORD] | [
"Creates",
"a",
"new",
"login",
".",
"Does",
"not",
"update",
"password",
"of",
"existing",
"logins",
".",
"For",
"Windows",
"authentication",
"provide",
"new_login_domain",
".",
"For",
"SQL",
"Server",
"authentication",
"prvide",
"new_login_password",
".",
"Since... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L303-L359 | train |
saltstack/salt | salt/modules/mssql.py | login_remove | def login_remove(login, **kwargs):
'''
Removes an login.
CLI Example:
.. code-block:: bash
salt minion mssql.login_remove LOGINNAME
'''
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute("DROP LOGIN [{0}]".format(login))
conn.autocommit(False)
conn.close()
return True
except Exception as e:
return 'Could not remove the login: {0}'.format(e) | python | def login_remove(login, **kwargs):
'''
Removes an login.
CLI Example:
.. code-block:: bash
salt minion mssql.login_remove LOGINNAME
'''
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute("DROP LOGIN [{0}]".format(login))
conn.autocommit(False)
conn.close()
return True
except Exception as e:
return 'Could not remove the login: {0}'.format(e) | [
"def",
"login_remove",
"(",
"login",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"_get_connection",
"(",
"*",
"*",
"kwargs",
")",
"conn",
".",
"autocommit",
"(",
"True",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"cur",
".",
... | Removes an login.
CLI Example:
.. code-block:: bash
salt minion mssql.login_remove LOGINNAME | [
"Removes",
"an",
"login",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L362-L381 | train |
saltstack/salt | salt/modules/mssql.py | user_exists | def user_exists(username, domain='', database=None, **kwargs):
'''
Find if an user exists in a specific database on the MS SQL server.
domain, if provided, will be prepended to username
CLI Example:
.. code-block:: bash
salt minion mssql.user_exists 'USERNAME' [database='DBNAME']
'''
if domain:
username = '{0}\\{1}'.format(domain, username)
if database:
kwargs['database'] = database
# We should get one, and only one row
return len(tsql_query(query="SELECT name FROM sysusers WHERE name='{0}'".format(username), **kwargs)) == 1 | python | def user_exists(username, domain='', database=None, **kwargs):
'''
Find if an user exists in a specific database on the MS SQL server.
domain, if provided, will be prepended to username
CLI Example:
.. code-block:: bash
salt minion mssql.user_exists 'USERNAME' [database='DBNAME']
'''
if domain:
username = '{0}\\{1}'.format(domain, username)
if database:
kwargs['database'] = database
# We should get one, and only one row
return len(tsql_query(query="SELECT name FROM sysusers WHERE name='{0}'".format(username), **kwargs)) == 1 | [
"def",
"user_exists",
"(",
"username",
",",
"domain",
"=",
"''",
",",
"database",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"domain",
":",
"username",
"=",
"'{0}\\\\{1}'",
".",
"format",
"(",
"domain",
",",
"username",
")",
"if",
"database"... | Find if an user exists in a specific database on the MS SQL server.
domain, if provided, will be prepended to username
CLI Example:
.. code-block:: bash
salt minion mssql.user_exists 'USERNAME' [database='DBNAME'] | [
"Find",
"if",
"an",
"user",
"exists",
"in",
"a",
"specific",
"database",
"on",
"the",
"MS",
"SQL",
"server",
".",
"domain",
"if",
"provided",
"will",
"be",
"prepended",
"to",
"username"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L384-L400 | train |
saltstack/salt | salt/modules/mssql.py | user_create | def user_create(username, login=None, domain='', database=None, roles=None, options=None, **kwargs):
'''
Creates a new user. If login is not specified, the user will be created
without a login. domain, if provided, will be prepended to username.
options can only be a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.user_create USERNAME database=DBNAME
'''
if domain and not login:
return 'domain cannot be set without login'
if user_exists(username, domain, **kwargs):
return 'User {0} already exists'.format(username)
if domain:
username = '{0}\\{1}'.format(domain, username)
login = '{0}\\{1}'.format(domain, login) if login else login
if database:
kwargs['database'] = database
if not roles:
roles = []
if not options:
options = []
sql = "CREATE USER [{0}] ".format(username)
if login:
# If the login does not exist, user creation will throw
# if not login_exists(name, **kwargs):
# return False
sql += " FOR LOGIN [{0}]".format(login)
else: # Plain test password
sql += " WITHOUT LOGIN"
if options:
sql += ' WITH ' + ', '.join(options)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
for role in roles:
conn.cursor().execute('ALTER ROLE [{0}] ADD MEMBER [{1}]'.format(role, username))
except Exception as e:
return 'Could not create the user: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | python | def user_create(username, login=None, domain='', database=None, roles=None, options=None, **kwargs):
'''
Creates a new user. If login is not specified, the user will be created
without a login. domain, if provided, will be prepended to username.
options can only be a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.user_create USERNAME database=DBNAME
'''
if domain and not login:
return 'domain cannot be set without login'
if user_exists(username, domain, **kwargs):
return 'User {0} already exists'.format(username)
if domain:
username = '{0}\\{1}'.format(domain, username)
login = '{0}\\{1}'.format(domain, login) if login else login
if database:
kwargs['database'] = database
if not roles:
roles = []
if not options:
options = []
sql = "CREATE USER [{0}] ".format(username)
if login:
# If the login does not exist, user creation will throw
# if not login_exists(name, **kwargs):
# return False
sql += " FOR LOGIN [{0}]".format(login)
else: # Plain test password
sql += " WITHOUT LOGIN"
if options:
sql += ' WITH ' + ', '.join(options)
conn = None
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
# cur = conn.cursor()
# cur.execute(sql)
conn.cursor().execute(sql)
for role in roles:
conn.cursor().execute('ALTER ROLE [{0}] ADD MEMBER [{1}]'.format(role, username))
except Exception as e:
return 'Could not create the user: {0}'.format(e)
finally:
if conn:
conn.autocommit(False)
conn.close()
return True | [
"def",
"user_create",
"(",
"username",
",",
"login",
"=",
"None",
",",
"domain",
"=",
"''",
",",
"database",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"options",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"domain",
"and",
"not",
"logi... | Creates a new user. If login is not specified, the user will be created
without a login. domain, if provided, will be prepended to username.
options can only be a list of strings
CLI Example:
.. code-block:: bash
salt minion mssql.user_create USERNAME database=DBNAME | [
"Creates",
"a",
"new",
"user",
".",
"If",
"login",
"is",
"not",
"specified",
"the",
"user",
"will",
"be",
"created",
"without",
"a",
"login",
".",
"domain",
"if",
"provided",
"will",
"be",
"prepended",
"to",
"username",
".",
"options",
"can",
"only",
"be... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L416-L467 | train |
saltstack/salt | salt/modules/mssql.py | user_remove | def user_remove(username, **kwargs):
'''
Removes an user.
CLI Example:
.. code-block:: bash
salt minion mssql.user_remove USERNAME database=DBNAME
'''
# 'database' argument is mandatory
if 'database' not in kwargs:
return False
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute("DROP USER {0}".format(username))
conn.autocommit(False)
conn.close()
return True
except Exception as e:
return 'Could not create the user: {0}'.format(e) | python | def user_remove(username, **kwargs):
'''
Removes an user.
CLI Example:
.. code-block:: bash
salt minion mssql.user_remove USERNAME database=DBNAME
'''
# 'database' argument is mandatory
if 'database' not in kwargs:
return False
try:
conn = _get_connection(**kwargs)
conn.autocommit(True)
cur = conn.cursor()
cur.execute("DROP USER {0}".format(username))
conn.autocommit(False)
conn.close()
return True
except Exception as e:
return 'Could not create the user: {0}'.format(e) | [
"def",
"user_remove",
"(",
"username",
",",
"*",
"*",
"kwargs",
")",
":",
"# 'database' argument is mandatory",
"if",
"'database'",
"not",
"in",
"kwargs",
":",
"return",
"False",
"try",
":",
"conn",
"=",
"_get_connection",
"(",
"*",
"*",
"kwargs",
")",
"conn... | Removes an user.
CLI Example:
.. code-block:: bash
salt minion mssql.user_remove USERNAME database=DBNAME | [
"Removes",
"an",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mssql.py#L470-L492 | train |
saltstack/salt | salt/states/boto_cloudwatch_alarm.py | present | def present(
name,
attributes,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the cloudwatch alarm exists.
name
Name of the alarm
attributes
A dict of key/value cloudwatch alarm attributes.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
alarm_details = __salt__['boto_cloudwatch.get_alarm'](
name, region, key, keyid, profile
)
# Convert to arn's
for k in ["alarm_actions", "insufficient_data_actions", "ok_actions"]:
if k in attributes:
attributes[k] = __salt__['boto_cloudwatch.convert_to_arn'](
attributes[k], region, key, keyid, profile
)
# Diff the alarm_details with the passed-in attributes, allowing for the
# AWS type transformations
difference = []
if alarm_details:
for k, v in six.iteritems(attributes):
if k not in alarm_details:
difference.append("{0}={1} (new)".format(k, v))
continue
v = salt.utils.data.decode(v)
v2 = salt.utils.data.decode(alarm_details[k])
if v == v2:
continue
if isinstance(v, six.string_types) and v == v2:
continue
if isinstance(v, float) and v == float(v2):
continue
if isinstance(v, int) and v == int(v2):
continue
if isinstance(v, list) and sorted(v) == sorted(v2):
continue
difference.append("{0}='{1}' was: '{2}'".format(k, v, v2))
else:
difference.append("new alarm")
create_or_update_alarm_args = {
"name": name,
"region": region,
"key": key,
"keyid": keyid,
"profile": profile
}
create_or_update_alarm_args.update(attributes)
if alarm_details: # alarm is present. update, or do nothing
# check to see if attributes matches is_present. If so, do nothing.
if not difference:
ret['comment'] = "alarm {0} present and matching".format(name)
return ret
if __opts__['test']:
msg = 'alarm {0} is to be created/updated.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
result = __salt__['boto_cloudwatch.create_or_update_alarm'](
**create_or_update_alarm_args
)
if result:
ret['changes']['diff'] = difference
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} alarm'.format(name)
else: # alarm is absent. create it.
if __opts__['test']:
msg = 'alarm {0} is to be created/updated.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
result = __salt__['boto_cloudwatch.create_or_update_alarm'](
**create_or_update_alarm_args
)
if result:
ret['changes']['new'] = attributes
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} alarm'.format(name)
return ret | python | def present(
name,
attributes,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the cloudwatch alarm exists.
name
Name of the alarm
attributes
A dict of key/value cloudwatch alarm attributes.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
alarm_details = __salt__['boto_cloudwatch.get_alarm'](
name, region, key, keyid, profile
)
# Convert to arn's
for k in ["alarm_actions", "insufficient_data_actions", "ok_actions"]:
if k in attributes:
attributes[k] = __salt__['boto_cloudwatch.convert_to_arn'](
attributes[k], region, key, keyid, profile
)
# Diff the alarm_details with the passed-in attributes, allowing for the
# AWS type transformations
difference = []
if alarm_details:
for k, v in six.iteritems(attributes):
if k not in alarm_details:
difference.append("{0}={1} (new)".format(k, v))
continue
v = salt.utils.data.decode(v)
v2 = salt.utils.data.decode(alarm_details[k])
if v == v2:
continue
if isinstance(v, six.string_types) and v == v2:
continue
if isinstance(v, float) and v == float(v2):
continue
if isinstance(v, int) and v == int(v2):
continue
if isinstance(v, list) and sorted(v) == sorted(v2):
continue
difference.append("{0}='{1}' was: '{2}'".format(k, v, v2))
else:
difference.append("new alarm")
create_or_update_alarm_args = {
"name": name,
"region": region,
"key": key,
"keyid": keyid,
"profile": profile
}
create_or_update_alarm_args.update(attributes)
if alarm_details: # alarm is present. update, or do nothing
# check to see if attributes matches is_present. If so, do nothing.
if not difference:
ret['comment'] = "alarm {0} present and matching".format(name)
return ret
if __opts__['test']:
msg = 'alarm {0} is to be created/updated.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
result = __salt__['boto_cloudwatch.create_or_update_alarm'](
**create_or_update_alarm_args
)
if result:
ret['changes']['diff'] = difference
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} alarm'.format(name)
else: # alarm is absent. create it.
if __opts__['test']:
msg = 'alarm {0} is to be created/updated.'.format(name)
ret['comment'] = msg
ret['result'] = None
return ret
result = __salt__['boto_cloudwatch.create_or_update_alarm'](
**create_or_update_alarm_args
)
if result:
ret['changes']['new'] = attributes
else:
ret['result'] = False
ret['comment'] = 'Failed to create {0} alarm'.format(name)
return ret | [
"def",
"present",
"(",
"name",
",",
"attributes",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'... | Ensure the cloudwatch alarm exists.
name
Name of the alarm
attributes
A dict of key/value cloudwatch alarm attributes.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string)
that contains a dict with region, key and keyid. | [
"Ensure",
"the",
"cloudwatch",
"alarm",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudwatch_alarm.py#L73-L177 | train |
saltstack/salt | salt/states/docker_container.py | _format_comments | def _format_comments(ret, comments):
'''
DRY code for joining comments together and conditionally adding a period at
the end, and adding this comment string to the state return dict.
'''
if isinstance(comments, six.string_types):
ret['comment'] = comments
else:
ret['comment'] = '. '.join(comments)
if len(comments) > 1:
ret['comment'] += '.'
return ret | python | def _format_comments(ret, comments):
'''
DRY code for joining comments together and conditionally adding a period at
the end, and adding this comment string to the state return dict.
'''
if isinstance(comments, six.string_types):
ret['comment'] = comments
else:
ret['comment'] = '. '.join(comments)
if len(comments) > 1:
ret['comment'] += '.'
return ret | [
"def",
"_format_comments",
"(",
"ret",
",",
"comments",
")",
":",
"if",
"isinstance",
"(",
"comments",
",",
"six",
".",
"string_types",
")",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"comments",
"else",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'. '",
"."... | DRY code for joining comments together and conditionally adding a period at
the end, and adding this comment string to the state return dict. | [
"DRY",
"code",
"for",
"joining",
"comments",
"together",
"and",
"conditionally",
"adding",
"a",
"period",
"at",
"the",
"end",
"and",
"adding",
"this",
"comment",
"string",
"to",
"the",
"state",
"return",
"dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_container.py#L79-L90 | train |
saltstack/salt | salt/states/docker_container.py | _check_diff | def _check_diff(changes):
'''
Check the diff for signs of incorrect argument handling in previous
releases, as discovered here:
https://github.com/saltstack/salt/pull/39996#issuecomment-288025200
'''
for conf_dict in changes:
if conf_dict == 'Networks':
continue
for item in changes[conf_dict]:
if changes[conf_dict][item]['new'] is None:
old = changes[conf_dict][item]['old']
if old == '':
return True
else:
try:
if all(x == '' for x in old):
return True
except TypeError:
# Old value is not an iterable type
pass
return False | python | def _check_diff(changes):
'''
Check the diff for signs of incorrect argument handling in previous
releases, as discovered here:
https://github.com/saltstack/salt/pull/39996#issuecomment-288025200
'''
for conf_dict in changes:
if conf_dict == 'Networks':
continue
for item in changes[conf_dict]:
if changes[conf_dict][item]['new'] is None:
old = changes[conf_dict][item]['old']
if old == '':
return True
else:
try:
if all(x == '' for x in old):
return True
except TypeError:
# Old value is not an iterable type
pass
return False | [
"def",
"_check_diff",
"(",
"changes",
")",
":",
"for",
"conf_dict",
"in",
"changes",
":",
"if",
"conf_dict",
"==",
"'Networks'",
":",
"continue",
"for",
"item",
"in",
"changes",
"[",
"conf_dict",
"]",
":",
"if",
"changes",
"[",
"conf_dict",
"]",
"[",
"it... | Check the diff for signs of incorrect argument handling in previous
releases, as discovered here:
https://github.com/saltstack/salt/pull/39996#issuecomment-288025200 | [
"Check",
"the",
"diff",
"for",
"signs",
"of",
"incorrect",
"argument",
"handling",
"in",
"previous",
"releases",
"as",
"discovered",
"here",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_container.py#L93-L115 | train |
saltstack/salt | salt/states/docker_container.py | _parse_networks | def _parse_networks(networks):
'''
Common logic for parsing the networks
'''
networks = salt.utils.args.split_input(networks or [])
if not networks:
networks = {}
else:
# We don't want to recurse the repack, as the values of the kwargs
# being passed when connecting to the network will not be dictlists.
networks = salt.utils.data.repack_dictlist(networks)
if not networks:
raise CommandExecutionError(
'Invalid network configuration (see documentation)'
)
for net_name, net_conf in six.iteritems(networks):
if net_conf is None:
networks[net_name] = {}
else:
networks[net_name] = salt.utils.data.repack_dictlist(net_conf)
if not networks[net_name]:
raise CommandExecutionError(
'Invalid configuration for network \'{0}\' '
'(see documentation)'.format(net_name)
)
for key in ('links', 'aliases'):
try:
networks[net_name][key] = salt.utils.args.split_input(
networks[net_name][key]
)
except KeyError:
continue
# Iterate over the networks again now, looking for
# incorrectly-formatted arguments
errors = []
for net_name, net_conf in six.iteritems(networks):
if net_conf is not None:
for key, val in six.iteritems(net_conf):
if val is None:
errors.append(
'Config option \'{0}\' for network \'{1}\' is '
'missing a value'.format(key, net_name)
)
if errors:
raise CommandExecutionError(
'Invalid network configuration', info=errors)
if networks:
try:
all_networks = [
x['Name'] for x in __salt__['docker.networks']()
if 'Name' in x
]
except CommandExecutionError as exc:
raise CommandExecutionError(
'Failed to get list of existing networks: {0}.'.format(exc)
)
else:
missing_networks = [
x for x in sorted(networks) if x not in all_networks]
if missing_networks:
raise CommandExecutionError(
'The following networks are not present: {0}'.format(
', '.join(missing_networks)
)
)
return networks | python | def _parse_networks(networks):
'''
Common logic for parsing the networks
'''
networks = salt.utils.args.split_input(networks or [])
if not networks:
networks = {}
else:
# We don't want to recurse the repack, as the values of the kwargs
# being passed when connecting to the network will not be dictlists.
networks = salt.utils.data.repack_dictlist(networks)
if not networks:
raise CommandExecutionError(
'Invalid network configuration (see documentation)'
)
for net_name, net_conf in six.iteritems(networks):
if net_conf is None:
networks[net_name] = {}
else:
networks[net_name] = salt.utils.data.repack_dictlist(net_conf)
if not networks[net_name]:
raise CommandExecutionError(
'Invalid configuration for network \'{0}\' '
'(see documentation)'.format(net_name)
)
for key in ('links', 'aliases'):
try:
networks[net_name][key] = salt.utils.args.split_input(
networks[net_name][key]
)
except KeyError:
continue
# Iterate over the networks again now, looking for
# incorrectly-formatted arguments
errors = []
for net_name, net_conf in six.iteritems(networks):
if net_conf is not None:
for key, val in six.iteritems(net_conf):
if val is None:
errors.append(
'Config option \'{0}\' for network \'{1}\' is '
'missing a value'.format(key, net_name)
)
if errors:
raise CommandExecutionError(
'Invalid network configuration', info=errors)
if networks:
try:
all_networks = [
x['Name'] for x in __salt__['docker.networks']()
if 'Name' in x
]
except CommandExecutionError as exc:
raise CommandExecutionError(
'Failed to get list of existing networks: {0}.'.format(exc)
)
else:
missing_networks = [
x for x in sorted(networks) if x not in all_networks]
if missing_networks:
raise CommandExecutionError(
'The following networks are not present: {0}'.format(
', '.join(missing_networks)
)
)
return networks | [
"def",
"_parse_networks",
"(",
"networks",
")",
":",
"networks",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"split_input",
"(",
"networks",
"or",
"[",
"]",
")",
"if",
"not",
"networks",
":",
"networks",
"=",
"{",
"}",
"else",
":",
"# We don't want to r... | Common logic for parsing the networks | [
"Common",
"logic",
"for",
"parsing",
"the",
"networks"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_container.py#L118-L186 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.