repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/boto_cloudtrail.py | list | def list(region=None, key=None, keyid=None, profile=None):
'''
List all trails
Returns list of trails
CLI Example:
.. code-block:: yaml
policies:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
trails = conn.describe_trails()
if not bool(trails.get('trailList')):
log.warning('No trails found')
return {'trails': trails.get('trailList', [])}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list(region=None, key=None, keyid=None, profile=None):
'''
List all trails
Returns list of trails
CLI Example:
.. code-block:: yaml
policies:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
trails = conn.describe_trails()
if not bool(trails.get('trailList')):
log.warning('No trails found')
return {'trails': trails.get('trailList', [])}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
... | List all trails
Returns list of trails
CLI Example:
.. code-block:: yaml
policies:
- {...}
- {...} | [
"List",
"all",
"trails"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L273-L295 | train |
saltstack/salt | salt/modules/boto_cloudtrail.py | update | def update(Name,
S3BucketName, S3KeyPrefix=None,
SnsTopicName=None,
IncludeGlobalServiceEvents=None,
IsMultiRegionTrail=None,
EnableLogFileValidation=None,
CloudWatchLogsLogGroupArn=None,
CloudWatchLogsRoleArn=None,
KmsKeyId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update a trail.
Returns {created: true} if the trail was created and returns
{created: False} if the trail was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.update my_trail my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('S3KeyPrefix', 'SnsTopicName', 'IncludeGlobalServiceEvents',
'IsMultiRegionTrail',
'EnableLogFileValidation', 'CloudWatchLogsLogGroupArn',
'CloudWatchLogsRoleArn', 'KmsKeyId'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
trail = conn.update_trail(Name=Name,
S3BucketName=S3BucketName,
**kwargs)
if trail:
log.info('The updated trail name is %s', trail['Name'])
return {'updated': True, 'name': trail['Name']}
else:
log.warning('Trail was not created')
return {'updated': False}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | python | def update(Name,
S3BucketName, S3KeyPrefix=None,
SnsTopicName=None,
IncludeGlobalServiceEvents=None,
IsMultiRegionTrail=None,
EnableLogFileValidation=None,
CloudWatchLogsLogGroupArn=None,
CloudWatchLogsRoleArn=None,
KmsKeyId=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update a trail.
Returns {created: true} if the trail was created and returns
{created: False} if the trail was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.update my_trail my_bucket
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
for arg in ('S3KeyPrefix', 'SnsTopicName', 'IncludeGlobalServiceEvents',
'IsMultiRegionTrail',
'EnableLogFileValidation', 'CloudWatchLogsLogGroupArn',
'CloudWatchLogsRoleArn', 'KmsKeyId'):
if locals()[arg] is not None:
kwargs[arg] = locals()[arg]
trail = conn.update_trail(Name=Name,
S3BucketName=S3BucketName,
**kwargs)
if trail:
log.info('The updated trail name is %s', trail['Name'])
return {'updated': True, 'name': trail['Name']}
else:
log.warning('Trail was not created')
return {'updated': False}
except ClientError as e:
return {'updated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"update",
"(",
"Name",
",",
"S3BucketName",
",",
"S3KeyPrefix",
"=",
"None",
",",
"SnsTopicName",
"=",
"None",
",",
"IncludeGlobalServiceEvents",
"=",
"None",
",",
"IsMultiRegionTrail",
"=",
"None",
",",
"EnableLogFileValidation",
"=",
"None",
",",
"Cloud... | Given a valid config, update a trail.
Returns {created: true} if the trail was created and returns
{created: False} if the trail was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.update my_trail my_bucket | [
"Given",
"a",
"valid",
"config",
"update",
"a",
"trail",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L298-L342 | train |
saltstack/salt | salt/modules/boto_cloudtrail.py | start_logging | def start_logging(Name,
region=None, key=None, keyid=None, profile=None):
'''
Start logging for a trail
Returns {started: true} if the trail was started and returns
{started: False} if the trail was not started.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.start_logging my_trail
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.start_logging(Name=Name)
return {'started': True}
except ClientError as e:
return {'started': False, 'error': __utils__['boto3.get_error'](e)} | python | def start_logging(Name,
region=None, key=None, keyid=None, profile=None):
'''
Start logging for a trail
Returns {started: true} if the trail was started and returns
{started: False} if the trail was not started.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.start_logging my_trail
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.start_logging(Name=Name)
return {'started': True}
except ClientError as e:
return {'started': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"start_logging",
"(",
"Name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
... | Start logging for a trail
Returns {started: true} if the trail was started and returns
{started: False} if the trail was not started.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.start_logging my_trail | [
"Start",
"logging",
"for",
"a",
"trail"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L345-L366 | train |
saltstack/salt | salt/modules/boto_cloudtrail.py | add_tags | def add_tags(Name,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Add tags to a trail
Returns {tagged: true} if the trail was tagged and returns
{tagged: False} if the trail was not tagged.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.add_tags my_trail tag_a=tag_value tag_b=tag_value
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.add_tags(ResourceId=_get_trail_arn(Name,
region=region, key=key, keyid=keyid,
profile=profile), TagsList=tagslist)
return {'tagged': True}
except ClientError as e:
return {'tagged': False, 'error': __utils__['boto3.get_error'](e)} | python | def add_tags(Name,
region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Add tags to a trail
Returns {tagged: true} if the trail was tagged and returns
{tagged: False} if the trail was not tagged.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.add_tags my_trail tag_a=tag_value tag_b=tag_value
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
tagslist = []
for k, v in six.iteritems(kwargs):
if six.text_type(k).startswith('__'):
continue
tagslist.append({'Key': six.text_type(k), 'Value': six.text_type(v)})
conn.add_tags(ResourceId=_get_trail_arn(Name,
region=region, key=key, keyid=keyid,
profile=profile), TagsList=tagslist)
return {'tagged': True}
except ClientError as e:
return {'tagged': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"add_tags",
"(",
"Name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",... | Add tags to a trail
Returns {tagged: true} if the trail was tagged and returns
{tagged: False} if the trail was not tagged.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.add_tags my_trail tag_a=tag_value tag_b=tag_value | [
"Add",
"tags",
"to",
"a",
"trail"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L407-L435 | train |
saltstack/salt | salt/modules/boto_cloudtrail.py | list_tags | def list_tags(Name,
region=None, key=None, keyid=None, profile=None):
'''
List tags of a trail
Returns:
tags:
- {...}
- {...}
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.list_tags my_trail
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rid = _get_trail_arn(Name,
region=region, key=key, keyid=keyid,
profile=profile)
ret = conn.list_tags(ResourceIdList=[rid])
tlist = ret.get('ResourceTagList', []).pop().get('TagsList')
tagdict = {}
for tag in tlist:
tagdict[tag.get('Key')] = tag.get('Value')
return {'tags': tagdict}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list_tags(Name,
region=None, key=None, keyid=None, profile=None):
'''
List tags of a trail
Returns:
tags:
- {...}
- {...}
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.list_tags my_trail
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rid = _get_trail_arn(Name,
region=region, key=key, keyid=keyid,
profile=profile)
ret = conn.list_tags(ResourceIdList=[rid])
tlist = ret.get('ResourceTagList', []).pop().get('TagsList')
tagdict = {}
for tag in tlist:
tagdict[tag.get('Key')] = tag.get('Value')
return {'tags': tagdict}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list_tags",
"(",
"Name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",... | List tags of a trail
Returns:
tags:
- {...}
- {...}
CLI Example:
.. code-block:: bash
salt myminion boto_cloudtrail.list_tags my_trail | [
"List",
"tags",
"of",
"a",
"trail"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudtrail.py#L469-L499 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | _list_distributions | def _list_distributions(
conn,
name=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Private function that returns an iterator over all CloudFront distributions.
The caller is responsible for all boto-related error handling.
name
(Optional) Only yield the distribution with the given name
'''
for dl_ in conn.get_paginator('list_distributions').paginate():
distribution_list = dl_['DistributionList']
if 'Items' not in distribution_list:
# If there are no items, AWS omits the `Items` key for some reason
continue
for partial_dist in distribution_list['Items']:
tags = conn.list_tags_for_resource(Resource=partial_dist['ARN'])
tags = dict(
(kv['Key'], kv['Value']) for kv in tags['Tags']['Items']
)
id_ = partial_dist['Id']
if 'Name' not in tags:
log.warning('CloudFront distribution %s has no Name tag.', id_)
continue
distribution_name = tags.pop('Name', None)
if name is not None and distribution_name != name:
continue
# NOTE: list_distributions() returns a DistributionList,
# which nominally contains a list of Distribution objects.
# However, they are mangled in that they are missing values
# (`Logging`, `ActiveTrustedSigners`, and `ETag` keys)
# and moreover flatten the normally nested DistributionConfig
# attributes to the top level.
# Hence, we must call get_distribution() to get the full object,
# and we cache these objects to help lessen API calls.
distribution = _cache_id(
'cloudfront',
sub_resource=distribution_name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if distribution:
yield (distribution_name, distribution)
continue
dist_with_etag = conn.get_distribution(Id=id_)
distribution = {
'distribution': dist_with_etag['Distribution'],
'etag': dist_with_etag['ETag'],
'tags': tags,
}
_cache_id(
'cloudfront',
sub_resource=distribution_name,
resource_id=distribution,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
yield (distribution_name, distribution) | python | def _list_distributions(
conn,
name=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Private function that returns an iterator over all CloudFront distributions.
The caller is responsible for all boto-related error handling.
name
(Optional) Only yield the distribution with the given name
'''
for dl_ in conn.get_paginator('list_distributions').paginate():
distribution_list = dl_['DistributionList']
if 'Items' not in distribution_list:
# If there are no items, AWS omits the `Items` key for some reason
continue
for partial_dist in distribution_list['Items']:
tags = conn.list_tags_for_resource(Resource=partial_dist['ARN'])
tags = dict(
(kv['Key'], kv['Value']) for kv in tags['Tags']['Items']
)
id_ = partial_dist['Id']
if 'Name' not in tags:
log.warning('CloudFront distribution %s has no Name tag.', id_)
continue
distribution_name = tags.pop('Name', None)
if name is not None and distribution_name != name:
continue
# NOTE: list_distributions() returns a DistributionList,
# which nominally contains a list of Distribution objects.
# However, they are mangled in that they are missing values
# (`Logging`, `ActiveTrustedSigners`, and `ETag` keys)
# and moreover flatten the normally nested DistributionConfig
# attributes to the top level.
# Hence, we must call get_distribution() to get the full object,
# and we cache these objects to help lessen API calls.
distribution = _cache_id(
'cloudfront',
sub_resource=distribution_name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if distribution:
yield (distribution_name, distribution)
continue
dist_with_etag = conn.get_distribution(Id=id_)
distribution = {
'distribution': dist_with_etag['Distribution'],
'etag': dist_with_etag['ETag'],
'tags': tags,
}
_cache_id(
'cloudfront',
sub_resource=distribution_name,
resource_id=distribution,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
yield (distribution_name, distribution) | [
"def",
"_list_distributions",
"(",
"conn",
",",
"name",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"for",
"dl_",
"in",
"conn",
".",
"get_paginator",
"(",
... | Private function that returns an iterator over all CloudFront distributions.
The caller is responsible for all boto-related error handling.
name
(Optional) Only yield the distribution with the given name | [
"Private",
"function",
"that",
"returns",
"an",
"iterator",
"over",
"all",
"CloudFront",
"distributions",
".",
"The",
"caller",
"is",
"responsible",
"for",
"all",
"boto",
"-",
"related",
"error",
"handling",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L87-L156 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | get_distribution | def get_distribution(name, region=None, key=None, keyid=None, profile=None):
'''
Get information about a CloudFront distribution (configuration, tags) with a given name.
name
Name of the CloudFront distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_distribution name=mydistribution profile=awsprofile
'''
distribution = _cache_id(
'cloudfront',
sub_resource=name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if distribution:
return {'result': distribution}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
for _, dist in _list_distributions(
conn,
name=name,
region=region,
key=key,
keyid=keyid,
profile=profile,
):
# _list_distributions should only return the one distribution
# that we want (with the given name).
# In case of multiple distributions with the same name tag,
# our use of caching means list_distributions will just
# return the first one over and over again,
# so only the first result is useful.
if distribution is not None:
msg = 'More than one distribution found with name {0}'
return {'error': msg.format(name)}
distribution = dist
except botocore.exceptions.ClientError as err:
return {'error': __utils__['boto3.get_error'](err)}
if not distribution:
return {'result': None}
_cache_id(
'cloudfront',
sub_resource=name,
resource_id=distribution,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
return {'result': distribution} | python | def get_distribution(name, region=None, key=None, keyid=None, profile=None):
'''
Get information about a CloudFront distribution (configuration, tags) with a given name.
name
Name of the CloudFront distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_distribution name=mydistribution profile=awsprofile
'''
distribution = _cache_id(
'cloudfront',
sub_resource=name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if distribution:
return {'result': distribution}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
for _, dist in _list_distributions(
conn,
name=name,
region=region,
key=key,
keyid=keyid,
profile=profile,
):
# _list_distributions should only return the one distribution
# that we want (with the given name).
# In case of multiple distributions with the same name tag,
# our use of caching means list_distributions will just
# return the first one over and over again,
# so only the first result is useful.
if distribution is not None:
msg = 'More than one distribution found with name {0}'
return {'error': msg.format(name)}
distribution = dist
except botocore.exceptions.ClientError as err:
return {'error': __utils__['boto3.get_error'](err)}
if not distribution:
return {'result': None}
_cache_id(
'cloudfront',
sub_resource=name,
resource_id=distribution,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
return {'result': distribution} | [
"def",
"get_distribution",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"distribution",
"=",
"_cache_id",
"(",
"'cloudfront'",
",",
"sub_resource",
"=",
"name",
",",
... | Get information about a CloudFront distribution (configuration, tags) with a given name.
name
Name of the CloudFront distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_distribution name=mydistribution profile=awsprofile | [
"Get",
"information",
"about",
"a",
"CloudFront",
"distribution",
"(",
"configuration",
"tags",
")",
"with",
"a",
"given",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L159-L231 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | export_distributions | def export_distributions(region=None, key=None, keyid=None, profile=None):
'''
Get details of all CloudFront distributions.
Produces results that can be used to create an SLS file.
CLI Example:
.. code-block:: bash
salt-call boto_cloudfront.export_distributions --out=txt |\
sed "s/local: //" > cloudfront_distributions.sls
'''
results = OrderedDict()
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
for name, distribution in _list_distributions(
conn,
region=region,
key=key,
keyid=keyid,
profile=profile,
):
config = distribution['distribution']['DistributionConfig']
tags = distribution['tags']
distribution_sls_data = [
{'name': name},
{'config': config},
{'tags': tags},
]
results['Manage CloudFront distribution {0}'.format(name)] = {
'boto_cloudfront.present': distribution_sls_data,
}
except botocore.exceptions.ClientError as err:
# Raise an exception, as this is meant to be user-invoked at the CLI
# as opposed to being called from execution or state modules
raise err
dumper = __utils__['yaml.get_dumper']('IndentedSafeOrderedDumper')
return __utils__['yaml.dump'](
results,
default_flow_style=False,
Dumper=dumper,
) | python | def export_distributions(region=None, key=None, keyid=None, profile=None):
'''
Get details of all CloudFront distributions.
Produces results that can be used to create an SLS file.
CLI Example:
.. code-block:: bash
salt-call boto_cloudfront.export_distributions --out=txt |\
sed "s/local: //" > cloudfront_distributions.sls
'''
results = OrderedDict()
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
for name, distribution in _list_distributions(
conn,
region=region,
key=key,
keyid=keyid,
profile=profile,
):
config = distribution['distribution']['DistributionConfig']
tags = distribution['tags']
distribution_sls_data = [
{'name': name},
{'config': config},
{'tags': tags},
]
results['Manage CloudFront distribution {0}'.format(name)] = {
'boto_cloudfront.present': distribution_sls_data,
}
except botocore.exceptions.ClientError as err:
# Raise an exception, as this is meant to be user-invoked at the CLI
# as opposed to being called from execution or state modules
raise err
dumper = __utils__['yaml.get_dumper']('IndentedSafeOrderedDumper')
return __utils__['yaml.dump'](
results,
default_flow_style=False,
Dumper=dumper,
) | [
"def",
"export_distributions",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"results",
"=",
"OrderedDict",
"(",
")",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | Get details of all CloudFront distributions.
Produces results that can be used to create an SLS file.
CLI Example:
.. code-block:: bash
salt-call boto_cloudfront.export_distributions --out=txt |\
sed "s/local: //" > cloudfront_distributions.sls | [
"Get",
"details",
"of",
"all",
"CloudFront",
"distributions",
".",
"Produces",
"results",
"that",
"can",
"be",
"used",
"to",
"create",
"an",
"SLS",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L234-L278 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | create_distribution | def create_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Create a CloudFront distribution with the given name, config, and (optionally) tags.
name
Name for the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.create_distribution name=mydistribution profile=awsprofile \
config='{"Comment":"partial configuration","Enabled":true}'
'''
if tags is None:
tags = {}
if 'Name' in tags:
# Be lenient and silently accept if names match, else error
if tags['Name'] != name:
return {'error': 'Must not pass `Name` in `tags` but as `name`'}
tags['Name'] = name
tags = {
'Items': [{'Key': k, 'Value': v} for k, v in six.iteritems(tags)]
}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.create_distribution_with_tags(
DistributionConfigWithTags={
'DistributionConfig': config,
'Tags': tags,
},
)
_cache_id(
'cloudfront',
sub_resource=name,
invalidate=True,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
except botocore.exceptions.ClientError as err:
return {'error': __utils__['boto3.get_error'](err)}
return {'result': True} | python | def create_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Create a CloudFront distribution with the given name, config, and (optionally) tags.
name
Name for the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.create_distribution name=mydistribution profile=awsprofile \
config='{"Comment":"partial configuration","Enabled":true}'
'''
if tags is None:
tags = {}
if 'Name' in tags:
# Be lenient and silently accept if names match, else error
if tags['Name'] != name:
return {'error': 'Must not pass `Name` in `tags` but as `name`'}
tags['Name'] = name
tags = {
'Items': [{'Key': k, 'Value': v} for k, v in six.iteritems(tags)]
}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
conn.create_distribution_with_tags(
DistributionConfigWithTags={
'DistributionConfig': config,
'Tags': tags,
},
)
_cache_id(
'cloudfront',
sub_resource=name,
invalidate=True,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
except botocore.exceptions.ClientError as err:
return {'error': __utils__['boto3.get_error'](err)}
return {'result': True} | [
"def",
"create_distribution",
"(",
"name",
",",
"config",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"if",
"tags",
"is",
"None",
":",
"tags",... | Create a CloudFront distribution with the given name, config, and (optionally) tags.
name
Name for the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.create_distribution name=mydistribution profile=awsprofile \
config='{"Comment":"partial configuration","Enabled":true}' | [
"Create",
"a",
"CloudFront",
"distribution",
"with",
"the",
"given",
"name",
"config",
"and",
"(",
"optionally",
")",
"tags",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L281-L353 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | update_distribution | def update_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.update_distribution name=mydistribution profile=awsprofile \
config='{"Comment":"partial configuration","Enabled":true}'
'''
### FIXME - BUG. This function can NEVER work as written...
### Obviously it was never actually tested.
distribution_ret = get_distribution(
name,
region=region,
key=key,
keyid=keyid,
profile=profile
)
if 'error' in distribution_ret:
return distribution_ret
dist_with_tags = distribution_ret['result']
current_distribution = dist_with_tags['distribution']
current_config = current_distribution['DistributionConfig']
current_tags = dist_with_tags['tags']
etag = dist_with_tags['etag']
config_diff = __utils__['dictdiffer.deep_diff'](current_config, config)
if tags:
tags_diff = __utils__['dictdiffer.deep_diff'](current_tags, tags)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
if 'old' in config_diff or 'new' in config_diff:
conn.update_distribution(
DistributionConfig=config,
Id=current_distribution['Id'],
IfMatch=etag,
)
if tags:
arn = current_distribution['ARN']
if 'new' in tags_diff:
tags_to_add = {
'Items': [
{'Key': k, 'Value': v}
for k, v in six.iteritems(tags_diff['new'])
],
}
conn.tag_resource(
Resource=arn,
Tags=tags_to_add,
)
if 'old' in tags_diff:
tags_to_remove = {
'Items': list(tags_diff['old'].keys()),
}
conn.untag_resource(
Resource=arn,
TagKeys=tags_to_remove,
)
except botocore.exceptions.ClientError as err:
return {'error': __utils__['boto3.get_error'](err)}
finally:
_cache_id(
'cloudfront',
sub_resource=name,
invalidate=True,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
return {'result': True} | python | def update_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.update_distribution name=mydistribution profile=awsprofile \
config='{"Comment":"partial configuration","Enabled":true}'
'''
### FIXME - BUG. This function can NEVER work as written...
### Obviously it was never actually tested.
distribution_ret = get_distribution(
name,
region=region,
key=key,
keyid=keyid,
profile=profile
)
if 'error' in distribution_ret:
return distribution_ret
dist_with_tags = distribution_ret['result']
current_distribution = dist_with_tags['distribution']
current_config = current_distribution['DistributionConfig']
current_tags = dist_with_tags['tags']
etag = dist_with_tags['etag']
config_diff = __utils__['dictdiffer.deep_diff'](current_config, config)
if tags:
tags_diff = __utils__['dictdiffer.deep_diff'](current_tags, tags)
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
try:
if 'old' in config_diff or 'new' in config_diff:
conn.update_distribution(
DistributionConfig=config,
Id=current_distribution['Id'],
IfMatch=etag,
)
if tags:
arn = current_distribution['ARN']
if 'new' in tags_diff:
tags_to_add = {
'Items': [
{'Key': k, 'Value': v}
for k, v in six.iteritems(tags_diff['new'])
],
}
conn.tag_resource(
Resource=arn,
Tags=tags_to_add,
)
if 'old' in tags_diff:
tags_to_remove = {
'Items': list(tags_diff['old'].keys()),
}
conn.untag_resource(
Resource=arn,
TagKeys=tags_to_remove,
)
except botocore.exceptions.ClientError as err:
return {'error': __utils__['boto3.get_error'](err)}
finally:
_cache_id(
'cloudfront',
sub_resource=name,
invalidate=True,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
return {'result': True} | [
"def",
"update_distribution",
"(",
"name",
",",
"config",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"### FIXME - BUG. This function can NEVER work as... | Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Secret key to use
keyid
Access key to use
profile
A dict with region, key, and keyid,
or a pillar key (string) that contains such a dict.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.update_distribution name=mydistribution profile=awsprofile \
config='{"Comment":"partial configuration","Enabled":true}' | [
"Update",
"the",
"config",
"(",
"and",
"optionally",
"tags",
")",
"for",
"the",
"CloudFront",
"distribution",
"with",
"the",
"given",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L356-L461 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | list_distributions | def list_distributions(region=None, key=None, keyid=None, profile=None):
'''
List, with moderate information, all CloudFront distributions in the bound account.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.list_distributions
'''
retries = 10
sleep = 6
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Items = []
while retries:
try:
log.debug('Garnering list of CloudFront distributions')
Marker = ''
while Marker is not None:
ret = conn.list_distributions(Marker=Marker)
Items += ret.get('DistributionList', {}).get('Items', [])
Marker = ret.get('DistributionList', {}).get('NextMarker')
return Items
except botocore.exceptions.ParamValidationError as err:
raise SaltInvocationError(str(err))
except botocore.exceptions.ClientError as err:
if retries and err.response.get('Error', {}).get('Code') == 'Throttling':
retries -= 1
log.debug('Throttled by AWS API, retrying in %s seconds...', sleep)
time.sleep(sleep)
continue
log.error('Failed to list CloudFront distributions: %s', err.message)
return None | python | def list_distributions(region=None, key=None, keyid=None, profile=None):
'''
List, with moderate information, all CloudFront distributions in the bound account.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.list_distributions
'''
retries = 10
sleep = 6
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Items = []
while retries:
try:
log.debug('Garnering list of CloudFront distributions')
Marker = ''
while Marker is not None:
ret = conn.list_distributions(Marker=Marker)
Items += ret.get('DistributionList', {}).get('Items', [])
Marker = ret.get('DistributionList', {}).get('NextMarker')
return Items
except botocore.exceptions.ParamValidationError as err:
raise SaltInvocationError(str(err))
except botocore.exceptions.ClientError as err:
if retries and err.response.get('Error', {}).get('Code') == 'Throttling':
retries -= 1
log.debug('Throttled by AWS API, retrying in %s seconds...', sleep)
time.sleep(sleep)
continue
log.error('Failed to list CloudFront distributions: %s', err.message)
return None | [
"def",
"list_distributions",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"retries",
"=",
"10",
"sleep",
"=",
"6",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | List, with moderate information, all CloudFront distributions in the bound account.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.list_distributions | [
"List",
"with",
"moderate",
"information",
"all",
"CloudFront",
"distributions",
"in",
"the",
"bound",
"account",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L564-L609 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | distribution_exists | def distribution_exists(Id, region=None, key=None, keyid=None, profile=None):
'''
Return True if a CloudFront distribution exists with the given Resource ID or False otherwise.
Id
Resource ID of the CloudFront distribution.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.distribution_exists Id=E24RBTSABCDEF0
'''
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
dists = list_distributions(**authargs) or []
return bool([i['Id'] for i in dists if i['Id'] == Id]) | python | def distribution_exists(Id, region=None, key=None, keyid=None, profile=None):
'''
Return True if a CloudFront distribution exists with the given Resource ID or False otherwise.
Id
Resource ID of the CloudFront distribution.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.distribution_exists Id=E24RBTSABCDEF0
'''
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
dists = list_distributions(**authargs) or []
return bool([i['Id'] for i in dists if i['Id'] == Id]) | [
"def",
"distribution_exists",
"(",
"Id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"authargs",
"=",
"{",
"'region'",
":",
"region",
",",
"'key'",
":",
"key",
",",
"'keyid'",... | Return True if a CloudFront distribution exists with the given Resource ID or False otherwise.
Id
Resource ID of the CloudFront distribution.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.distribution_exists Id=E24RBTSABCDEF0 | [
"Return",
"True",
"if",
"a",
"CloudFront",
"distribution",
"exists",
"with",
"the",
"given",
"Resource",
"ID",
"or",
"False",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L612-L640 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | get_distributions_by_comment | def get_distributions_by_comment(Comment, region=None, key=None, keyid=None, profile=None):
'''
Find and return any CloudFront distributions which happen to have a Comment sub-field
either exactly matching the given Comment, or beginning with it AND with the remainder
separated by a colon.
Comment
The string to be matched when searching for the given Distribution. Note that this
will be matched against both the exact value of the Comment sub-field, AND as a
colon-separated initial value for the same Comment sub-field. E.g. given a passed
`Comment` value of `foobar`, this would match a distribution with EITHER a
Comment sub-field of exactly `foobar`, OR a Comment sub-field beginning with
`foobar:`. The intention here is to permit using the Comment field for storing
actual comments, in addition to overloading it to store Salt's `Name` attribute.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_distributions_by_comment 'Comment=foobar'
salt myminion boto_cloudfront.get_distributions_by_comment 'Comment=foobar:Plus a real comment'
'''
log.debug('Dereferincing CloudFront distribution(s) by Comment `%s`.', Comment)
ret = list_distributions(region=region, key=key, keyid=keyid, profile=profile)
if ret is None:
return ret
items = []
for item in ret:
comment = item.get('Comment')
# Comment field is never None, so it can only match if both exist...
if comment == Comment or comment.startswith('{0}:'.format(Comment)):
items += [item]
return items | python | def get_distributions_by_comment(Comment, region=None, key=None, keyid=None, profile=None):
'''
Find and return any CloudFront distributions which happen to have a Comment sub-field
either exactly matching the given Comment, or beginning with it AND with the remainder
separated by a colon.
Comment
The string to be matched when searching for the given Distribution. Note that this
will be matched against both the exact value of the Comment sub-field, AND as a
colon-separated initial value for the same Comment sub-field. E.g. given a passed
`Comment` value of `foobar`, this would match a distribution with EITHER a
Comment sub-field of exactly `foobar`, OR a Comment sub-field beginning with
`foobar:`. The intention here is to permit using the Comment field for storing
actual comments, in addition to overloading it to store Salt's `Name` attribute.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_distributions_by_comment 'Comment=foobar'
salt myminion boto_cloudfront.get_distributions_by_comment 'Comment=foobar:Plus a real comment'
'''
log.debug('Dereferincing CloudFront distribution(s) by Comment `%s`.', Comment)
ret = list_distributions(region=region, key=key, keyid=keyid, profile=profile)
if ret is None:
return ret
items = []
for item in ret:
comment = item.get('Comment')
# Comment field is never None, so it can only match if both exist...
if comment == Comment or comment.startswith('{0}:'.format(Comment)):
items += [item]
return items | [
"def",
"get_distributions_by_comment",
"(",
"Comment",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Dereferincing CloudFront distribution(s) by Comment `%s`.'",
... | Find and return any CloudFront distributions which happen to have a Comment sub-field
either exactly matching the given Comment, or beginning with it AND with the remainder
separated by a colon.
Comment
The string to be matched when searching for the given Distribution. Note that this
will be matched against both the exact value of the Comment sub-field, AND as a
colon-separated initial value for the same Comment sub-field. E.g. given a passed
`Comment` value of `foobar`, this would match a distribution with EITHER a
Comment sub-field of exactly `foobar`, OR a Comment sub-field beginning with
`foobar:`. The intention here is to permit using the Comment field for storing
actual comments, in addition to overloading it to store Salt's `Name` attribute.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_distributions_by_comment 'Comment=foobar'
salt myminion boto_cloudfront.get_distributions_by_comment 'Comment=foobar:Plus a real comment' | [
"Find",
"and",
"return",
"any",
"CloudFront",
"distributions",
"which",
"happen",
"to",
"have",
"a",
"Comment",
"sub",
"-",
"field",
"either",
"exactly",
"matching",
"the",
"given",
"Comment",
"or",
"beginning",
"with",
"it",
"AND",
"with",
"the",
"remainder",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L643-L688 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | disable_distribution | def disable_distribution(region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Set a CloudFront distribution to be disabled.
Id
Id of the distribution to update.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.disable_distribution Id=E24RBTSABCDEF0
'''
retries = 10
sleep = 6
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Id = kwargs.get('Id')
current = get_distribution_v2(Id=Id, **authargs)
if current is None:
log.error('Failed to get current config of CloudFront distribution `%s`.', Id)
return None
if not current['Distribution']['DistributionConfig']['Enabled']:
return current
ETag = current['ETag']
DistributionConfig = current['Distribution']['DistributionConfig']
DistributionConfig['Enabled'] = False
kwargs = {'DistributionConfig': DistributionConfig, 'Id': Id, 'IfMatch': ETag}
kwargs.update(authargs)
while retries:
try:
log.debug('Disabling CloudFront distribution `%s`.', Id)
ret = conn.update_distribution(**kwargs)
return ret
except botocore.exceptions.ParamValidationError as err:
raise SaltInvocationError(str(err))
except botocore.exceptions.ClientError as err:
if retries and err.response.get('Error', {}).get('Code') == 'Throttling':
retries -= 1
log.debug('Throttled by AWS API, retrying in %s seconds...', sleep)
time.sleep(sleep)
continue
log.error('Failed to disable CloudFront distribution `%s`: %s', Comment, err.message)
return None | python | def disable_distribution(region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Set a CloudFront distribution to be disabled.
Id
Id of the distribution to update.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.disable_distribution Id=E24RBTSABCDEF0
'''
retries = 10
sleep = 6
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
Id = kwargs.get('Id')
current = get_distribution_v2(Id=Id, **authargs)
if current is None:
log.error('Failed to get current config of CloudFront distribution `%s`.', Id)
return None
if not current['Distribution']['DistributionConfig']['Enabled']:
return current
ETag = current['ETag']
DistributionConfig = current['Distribution']['DistributionConfig']
DistributionConfig['Enabled'] = False
kwargs = {'DistributionConfig': DistributionConfig, 'Id': Id, 'IfMatch': ETag}
kwargs.update(authargs)
while retries:
try:
log.debug('Disabling CloudFront distribution `%s`.', Id)
ret = conn.update_distribution(**kwargs)
return ret
except botocore.exceptions.ParamValidationError as err:
raise SaltInvocationError(str(err))
except botocore.exceptions.ClientError as err:
if retries and err.response.get('Error', {}).get('Code') == 'Throttling':
retries -= 1
log.debug('Throttled by AWS API, retrying in %s seconds...', sleep)
time.sleep(sleep)
continue
log.error('Failed to disable CloudFront distribution `%s`: %s', Comment, err.message)
return None | [
"def",
"disable_distribution",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"retries",
"=",
"10",
"sleep",
"=",
"6",
"kwargs",
"=",
"{",
"k",
":",
... | Set a CloudFront distribution to be disabled.
Id
Id of the distribution to update.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.disable_distribution Id=E24RBTSABCDEF0 | [
"Set",
"a",
"CloudFront",
"distribution",
"to",
"be",
"disabled",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L978-L1036 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | get_cloud_front_origin_access_identities_by_comment | def get_cloud_front_origin_access_identities_by_comment(Comment, region=None, key=None, keyid=None,
profile=None):
'''
Find and return any CloudFront Origin Access Identities which happen to have a Comment
sub-field either exactly matching the given Comment, or beginning with it AND with the
remainder separate by a colon.
Comment
The string to be matched when searching for the given Origin Access Identity. Note
that this will be matched against both the exact value of the Comment sub-field, AND as
a colon-separated initial value for the same Comment sub-field. E.g. given a passed
`Comment` value of `foobar`, this would match a Origin Access Identity with EITHER a
Comment sub-field of exactly `foobar`, OR a Comment sub-field beginning with
`foobar:`. The intention here is to permit using the Comment field for storing
actual comments, in addition to overloading it to store Salt's `Name` attribute.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_cloud_front_origin_access_identities_by_comment 'Comment=foobar'
salt myminion boto_cloudfront.get_cloud_front_origin_access_identities_by_comment 'Comment=foobar:Plus a real comment'
'''
log.debug('Dereferincing CloudFront origin access identity `%s` by Comment.', Comment)
ret = list_cloud_front_origin_access_identities(region=region, key=key, keyid=keyid,
profile=profile)
if ret is None:
return ret
items = []
for item in ret:
comment = item.get('Comment', '')
if comment == Comment or comment.startswith('{0}:'.format(Comment)):
items += [item]
return items | python | def get_cloud_front_origin_access_identities_by_comment(Comment, region=None, key=None, keyid=None,
profile=None):
'''
Find and return any CloudFront Origin Access Identities which happen to have a Comment
sub-field either exactly matching the given Comment, or beginning with it AND with the
remainder separate by a colon.
Comment
The string to be matched when searching for the given Origin Access Identity. Note
that this will be matched against both the exact value of the Comment sub-field, AND as
a colon-separated initial value for the same Comment sub-field. E.g. given a passed
`Comment` value of `foobar`, this would match a Origin Access Identity with EITHER a
Comment sub-field of exactly `foobar`, OR a Comment sub-field beginning with
`foobar:`. The intention here is to permit using the Comment field for storing
actual comments, in addition to overloading it to store Salt's `Name` attribute.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_cloud_front_origin_access_identities_by_comment 'Comment=foobar'
salt myminion boto_cloudfront.get_cloud_front_origin_access_identities_by_comment 'Comment=foobar:Plus a real comment'
'''
log.debug('Dereferincing CloudFront origin access identity `%s` by Comment.', Comment)
ret = list_cloud_front_origin_access_identities(region=region, key=key, keyid=keyid,
profile=profile)
if ret is None:
return ret
items = []
for item in ret:
comment = item.get('Comment', '')
if comment == Comment or comment.startswith('{0}:'.format(Comment)):
items += [item]
return items | [
"def",
"get_cloud_front_origin_access_identities_by_comment",
"(",
"Comment",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Dereferincing CloudFront origin access ... | Find and return any CloudFront Origin Access Identities which happen to have a Comment
sub-field either exactly matching the given Comment, or beginning with it AND with the
remainder separate by a colon.
Comment
The string to be matched when searching for the given Origin Access Identity. Note
that this will be matched against both the exact value of the Comment sub-field, AND as
a colon-separated initial value for the same Comment sub-field. E.g. given a passed
`Comment` value of `foobar`, this would match a Origin Access Identity with EITHER a
Comment sub-field of exactly `foobar`, OR a Comment sub-field beginning with
`foobar:`. The intention here is to permit using the Comment field for storing
actual comments, in addition to overloading it to store Salt's `Name` attribute.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.get_cloud_front_origin_access_identities_by_comment 'Comment=foobar'
salt myminion boto_cloudfront.get_cloud_front_origin_access_identities_by_comment 'Comment=foobar:Plus a real comment' | [
"Find",
"and",
"return",
"any",
"CloudFront",
"Origin",
"Access",
"Identities",
"which",
"happen",
"to",
"have",
"a",
"Comment",
"sub",
"-",
"field",
"either",
"exactly",
"matching",
"the",
"given",
"Comment",
"or",
"beginning",
"with",
"it",
"AND",
"with",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L1237-L1283 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | cloud_front_origin_access_identity_exists | def cloud_front_origin_access_identity_exists(Id, region=None, key=None, keyid=None, profile=None):
'''
Return True if a CloudFront origin access identity exists with the given Resource ID or False
otherwise.
Id
Resource ID of the CloudFront origin access identity.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.cloud_front_origin_access_identity_exists Id=E30RBTSABCDEF0
'''
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
oais = list_cloud_front_origin_access_identities(**authargs) or []
return bool([i['Id'] for i in oais if i['Id'] == Id]) | python | def cloud_front_origin_access_identity_exists(Id, region=None, key=None, keyid=None, profile=None):
'''
Return True if a CloudFront origin access identity exists with the given Resource ID or False
otherwise.
Id
Resource ID of the CloudFront origin access identity.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.cloud_front_origin_access_identity_exists Id=E30RBTSABCDEF0
'''
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
oais = list_cloud_front_origin_access_identities(**authargs) or []
return bool([i['Id'] for i in oais if i['Id'] == Id]) | [
"def",
"cloud_front_origin_access_identity_exists",
"(",
"Id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"authargs",
"=",
"{",
"'region'",
":",
"region",
",",
"'key'",
":",
"key... | Return True if a CloudFront origin access identity exists with the given Resource ID or False
otherwise.
Id
Resource ID of the CloudFront origin access identity.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.cloud_front_origin_access_identity_exists Id=E30RBTSABCDEF0 | [
"Return",
"True",
"if",
"a",
"CloudFront",
"origin",
"access",
"identity",
"exists",
"with",
"the",
"given",
"Resource",
"ID",
"or",
"False",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L1455-L1484 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | tag_resource | def tag_resource(region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Add tags to a CloudFront resource.
Resource
The ARN of the affected CloudFront resource.
Tags
Dict of {'Tag': 'Value', ...} providing the tags to be set.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.tag_resource Tags='{Owner: Infra, Role: salt_master}' \\
Resource='arn:aws:cloudfront::012345678012:distribution/ETLNABCDEF123'
'''
retries = 10
sleep = 6
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs['Tags'] = {'Items': [{'Key': k, 'Value': v} for k, v in kwargs.get('Tags', {}).items()]}
while retries:
try:
log.debug('Adding tags (%s) to CloudFront resource `%s`.', kwargs['Tags'],
kwargs.get('Resource'))
conn.tag_resource(**kwargs)
return True
except botocore.exceptions.ParamValidationError as err:
raise SaltInvocationError(str(err))
except botocore.exceptions.ClientError as err:
if retries and err.response.get('Error', {}).get('Code') == 'Throttling':
retries -= 1
log.debug('Throttled by AWS API, retrying in %s seconds...', sleep)
time.sleep(sleep)
continue
log.error('Failed to add tags to resource `%s`: %s', kwargs.get('Resource'),
err.message)
return False | python | def tag_resource(region=None, key=None, keyid=None, profile=None, **kwargs):
'''
Add tags to a CloudFront resource.
Resource
The ARN of the affected CloudFront resource.
Tags
Dict of {'Tag': 'Value', ...} providing the tags to be set.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.tag_resource Tags='{Owner: Infra, Role: salt_master}' \\
Resource='arn:aws:cloudfront::012345678012:distribution/ETLNABCDEF123'
'''
retries = 10
sleep = 6
kwargs = {k: v for k, v in kwargs.items() if not k.startswith('_')}
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs['Tags'] = {'Items': [{'Key': k, 'Value': v} for k, v in kwargs.get('Tags', {}).items()]}
while retries:
try:
log.debug('Adding tags (%s) to CloudFront resource `%s`.', kwargs['Tags'],
kwargs.get('Resource'))
conn.tag_resource(**kwargs)
return True
except botocore.exceptions.ParamValidationError as err:
raise SaltInvocationError(str(err))
except botocore.exceptions.ClientError as err:
if retries and err.response.get('Error', {}).get('Code') == 'Throttling':
retries -= 1
log.debug('Throttled by AWS API, retrying in %s seconds...', sleep)
time.sleep(sleep)
continue
log.error('Failed to add tags to resource `%s`: %s', kwargs.get('Resource'),
err.message)
return False | [
"def",
"tag_resource",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"retries",
"=",
"10",
"sleep",
"=",
"6",
"kwargs",
"=",
"{",
"k",
":",
"v",
"... | Add tags to a CloudFront resource.
Resource
The ARN of the affected CloudFront resource.
Tags
Dict of {'Tag': 'Value', ...} providing the tags to be set.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.tag_resource Tags='{Owner: Infra, Role: salt_master}' \\
Resource='arn:aws:cloudfront::012345678012:distribution/ETLNABCDEF123' | [
"Add",
"tags",
"to",
"a",
"CloudFront",
"resource",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L1537-L1588 | train |
saltstack/salt | salt/modules/boto_cloudfront.py | enforce_tags | def enforce_tags(Resource, Tags, region=None, key=None, keyid=None, profile=None):
'''
Enforce a given set of tags on a CloudFront resource: adding, removing, or changing them
as necessary to ensure the resource's tags are exactly and only those specified.
Resource
The ARN of the affected CloudFront resource.
Tags
Dict of {'Tag': 'Value', ...} providing the tags to be enforced.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.enforce_tags Tags='{Owner: Infra, Role: salt_master}' \\
Resource='arn:aws:cloudfront::012345678012:distribution/ETLNABCDEF123'
'''
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = list_tags_for_resource(Resource=Resource, **authargs)
if current is None:
log.error('Failed to list tags for CloudFront resource `%s`.', Resource)
return False
if current == Tags: # Short-ciruits save cycles!
return True
remove = [k for k in current if k not in Tags]
removed = untag_resource(Resource=Resource, TagKeys=remove, **authargs)
if removed is False:
log.error('Failed to remove tags (%s) from CloudFront resource `%s`.', remove, Resource)
return False
add = {k: v for k, v in Tags.items() if current.get(k) != v}
added = tag_resource(Resource=Resource, Tags=add, **authargs)
if added is False:
log.error('Failed to add tags (%s) to CloudFront resource `%s`.', add, Resource)
return False
return True | python | def enforce_tags(Resource, Tags, region=None, key=None, keyid=None, profile=None):
'''
Enforce a given set of tags on a CloudFront resource: adding, removing, or changing them
as necessary to ensure the resource's tags are exactly and only those specified.
Resource
The ARN of the affected CloudFront resource.
Tags
Dict of {'Tag': 'Value', ...} providing the tags to be enforced.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.enforce_tags Tags='{Owner: Infra, Role: salt_master}' \\
Resource='arn:aws:cloudfront::012345678012:distribution/ETLNABCDEF123'
'''
authargs = {'region': region, 'key': key, 'keyid': keyid, 'profile': profile}
current = list_tags_for_resource(Resource=Resource, **authargs)
if current is None:
log.error('Failed to list tags for CloudFront resource `%s`.', Resource)
return False
if current == Tags: # Short-ciruits save cycles!
return True
remove = [k for k in current if k not in Tags]
removed = untag_resource(Resource=Resource, TagKeys=remove, **authargs)
if removed is False:
log.error('Failed to remove tags (%s) from CloudFront resource `%s`.', remove, Resource)
return False
add = {k: v for k, v in Tags.items() if current.get(k) != v}
added = tag_resource(Resource=Resource, Tags=add, **authargs)
if added is False:
log.error('Failed to add tags (%s) to CloudFront resource `%s`.', add, Resource)
return False
return True | [
"def",
"enforce_tags",
"(",
"Resource",
",",
"Tags",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"authargs",
"=",
"{",
"'region'",
":",
"region",
",",
"'key'",
":",
"key",
"... | Enforce a given set of tags on a CloudFront resource: adding, removing, or changing them
as necessary to ensure the resource's tags are exactly and only those specified.
Resource
The ARN of the affected CloudFront resource.
Tags
Dict of {'Tag': 'Value', ...} providing the tags to be enforced.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict, or pillar key pointing to a dict, containing AWS region/key/keyid.
CLI Example:
.. code-block:: bash
salt myminion boto_cloudfront.enforce_tags Tags='{Owner: Infra, Role: salt_master}' \\
Resource='arn:aws:cloudfront::012345678012:distribution/ETLNABCDEF123' | [
"Enforce",
"a",
"given",
"set",
"of",
"tags",
"on",
"a",
"CloudFront",
"resource",
":",
"adding",
"removing",
"or",
"changing",
"them",
"as",
"necessary",
"to",
"ensure",
"the",
"resource",
"s",
"tags",
"are",
"exactly",
"and",
"only",
"those",
"specified",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_cloudfront.py#L1644-L1692 | train |
saltstack/salt | salt/states/pcs.py | _file_read | def _file_read(path):
'''
Read a file and return content
'''
content = False
if os.path.exists(path):
with salt.utils.files.fopen(path, 'r+') as fp_:
content = salt.utils.stringutils.to_unicode(fp_.read())
fp_.close()
return content | python | def _file_read(path):
'''
Read a file and return content
'''
content = False
if os.path.exists(path):
with salt.utils.files.fopen(path, 'r+') as fp_:
content = salt.utils.stringutils.to_unicode(fp_.read())
fp_.close()
return content | [
"def",
"_file_read",
"(",
"path",
")",
":",
"content",
"=",
"False",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'r+'",
")",
"as",
"fp_",
":",
"conten... | Read a file and return content | [
"Read",
"a",
"file",
"and",
"return",
"content"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L191-L200 | train |
saltstack/salt | salt/states/pcs.py | _file_write | def _file_write(path, content):
'''
Write content to a file
'''
with salt.utils.files.fopen(path, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
fp_.close() | python | def _file_write(path, content):
'''
Write content to a file
'''
with salt.utils.files.fopen(path, 'w+') as fp_:
fp_.write(salt.utils.stringutils.to_str(content))
fp_.close() | [
"def",
"_file_write",
"(",
"path",
",",
"content",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"'w+'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_str... | Write content to a file | [
"Write",
"content",
"to",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L203-L209 | train |
saltstack/salt | salt/states/pcs.py | _get_cibpath | def _get_cibpath():
'''
Get the path to the directory on the minion where CIB's are saved
'''
cibpath = os.path.join(__opts__['cachedir'], 'pcs', __env__)
log.trace('cibpath: %s', cibpath)
return cibpath | python | def _get_cibpath():
'''
Get the path to the directory on the minion where CIB's are saved
'''
cibpath = os.path.join(__opts__['cachedir'], 'pcs', __env__)
log.trace('cibpath: %s', cibpath)
return cibpath | [
"def",
"_get_cibpath",
"(",
")",
":",
"cibpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'pcs'",
",",
"__env__",
")",
"log",
".",
"trace",
"(",
"'cibpath: %s'",
",",
"cibpath",
")",
"return",
"cibpath"
] | Get the path to the directory on the minion where CIB's are saved | [
"Get",
"the",
"path",
"to",
"the",
"directory",
"on",
"the",
"minion",
"where",
"CIB",
"s",
"are",
"saved"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L212-L218 | train |
saltstack/salt | salt/states/pcs.py | _get_cibfile | def _get_cibfile(cibname):
'''
Get the full path of a cached CIB-file with the name of the CIB
'''
cibfile = os.path.join(_get_cibpath(), '{0}.{1}'.format(cibname, 'cib'))
log.trace('cibfile: %s', cibfile)
return cibfile | python | def _get_cibfile(cibname):
'''
Get the full path of a cached CIB-file with the name of the CIB
'''
cibfile = os.path.join(_get_cibpath(), '{0}.{1}'.format(cibname, 'cib'))
log.trace('cibfile: %s', cibfile)
return cibfile | [
"def",
"_get_cibfile",
"(",
"cibname",
")",
":",
"cibfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_get_cibpath",
"(",
")",
",",
"'{0}.{1}'",
".",
"format",
"(",
"cibname",
",",
"'cib'",
")",
")",
"log",
".",
"trace",
"(",
"'cibfile: %s'",
",",
"... | Get the full path of a cached CIB-file with the name of the CIB | [
"Get",
"the",
"full",
"path",
"of",
"a",
"cached",
"CIB",
"-",
"file",
"with",
"the",
"name",
"of",
"the",
"CIB"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L221-L227 | train |
saltstack/salt | salt/states/pcs.py | _get_cibfile_tmp | def _get_cibfile_tmp(cibname):
'''
Get the full path of a temporary CIB-file with the name of the CIB
'''
cibfile_tmp = '{0}.tmp'.format(_get_cibfile(cibname))
log.trace('cibfile_tmp: %s', cibfile_tmp)
return cibfile_tmp | python | def _get_cibfile_tmp(cibname):
'''
Get the full path of a temporary CIB-file with the name of the CIB
'''
cibfile_tmp = '{0}.tmp'.format(_get_cibfile(cibname))
log.trace('cibfile_tmp: %s', cibfile_tmp)
return cibfile_tmp | [
"def",
"_get_cibfile_tmp",
"(",
"cibname",
")",
":",
"cibfile_tmp",
"=",
"'{0}.tmp'",
".",
"format",
"(",
"_get_cibfile",
"(",
"cibname",
")",
")",
"log",
".",
"trace",
"(",
"'cibfile_tmp: %s'",
",",
"cibfile_tmp",
")",
"return",
"cibfile_tmp"
] | Get the full path of a temporary CIB-file with the name of the CIB | [
"Get",
"the",
"full",
"path",
"of",
"a",
"temporary",
"CIB",
"-",
"file",
"with",
"the",
"name",
"of",
"the",
"CIB"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L230-L236 | train |
saltstack/salt | salt/states/pcs.py | _get_cibfile_cksum | def _get_cibfile_cksum(cibname):
'''
Get the full path of the file containing a checksum of a CIB-file with the name of the CIB
'''
cibfile_cksum = '{0}.cksum'.format(_get_cibfile(cibname))
log.trace('cibfile_cksum: %s', cibfile_cksum)
return cibfile_cksum | python | def _get_cibfile_cksum(cibname):
'''
Get the full path of the file containing a checksum of a CIB-file with the name of the CIB
'''
cibfile_cksum = '{0}.cksum'.format(_get_cibfile(cibname))
log.trace('cibfile_cksum: %s', cibfile_cksum)
return cibfile_cksum | [
"def",
"_get_cibfile_cksum",
"(",
"cibname",
")",
":",
"cibfile_cksum",
"=",
"'{0}.cksum'",
".",
"format",
"(",
"_get_cibfile",
"(",
"cibname",
")",
")",
"log",
".",
"trace",
"(",
"'cibfile_cksum: %s'",
",",
"cibfile_cksum",
")",
"return",
"cibfile_cksum"
] | Get the full path of the file containing a checksum of a CIB-file with the name of the CIB | [
"Get",
"the",
"full",
"path",
"of",
"the",
"file",
"containing",
"a",
"checksum",
"of",
"a",
"CIB",
"-",
"file",
"with",
"the",
"name",
"of",
"the",
"CIB"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L239-L245 | train |
saltstack/salt | salt/states/pcs.py | _item_present | def _item_present(name, item, item_id, item_type, show='show', create='create', extra_args=None, cibname=None):
'''
Ensure that an item is created
name
Irrelevant, not used
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
show
show command (probably None, default: show)
create
create command (create or set f.e., default: create)
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
item_create_required = True
cibfile = None
if isinstance(cibname, six.string_types):
cibfile = _get_cibfile(cibname)
if not isinstance(extra_args, (list, tuple)):
extra_args = []
# split off key and value (item_id contains =)
item_id_key = item_id
item_id_value = None
if '=' in item_id:
item_id_key = item_id.split('=')[0].strip()
item_id_value = item_id.replace(item_id.split('=')[0] + '=', '').strip()
log.trace('item_id_key=%s item_id_value=%s', item_id_key, item_id_value)
# constraints, properties, resource defaults or resource op defaults
# do not support specifying an id on 'show' command
item_id_show = item_id
if item in ['constraint'] or '=' in item_id:
item_id_show = None
is_existing = __salt__['pcs.item_show'](item=item,
item_id=item_id_show,
item_type=item_type,
show=show,
cibfile=cibfile)
log.trace(
'Output of pcs.item_show item=%s item_id=%s item_type=%s cibfile=%s: %s',
item, item_id_show, item_type, cibfile, is_existing
)
# key,value pairs (item_id contains =) - match key and value
if item_id_value is not None:
for line in is_existing['stdout'].splitlines():
if len(line.split(':')) in [2]:
key = line.split(':')[0].strip()
value = line.split(':')[1].strip()
if item_id_key in [key]:
if item_id_value in [value]:
item_create_required = False
# constraints match on '(id:<id>)'
elif item in ['constraint']:
for line in is_existing['stdout'].splitlines():
if '(id:{0})'.format(item_id) in line:
item_create_required = False
# item_id was provided,
# return code 0 indicates, that resource already exists
else:
if is_existing['retcode'] in [0]:
item_create_required = False
if not item_create_required:
ret['comment'] += '{0} {1} ({2}) is already existing\n'.format(
six.text_type(item), six.text_type(item_id), six.text_type(item_type)
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] += '{0} {1} ({2}) is set to be created\n'.format(
six.text_type(item), six.text_type(item_id), six.text_type(item_type)
)
return ret
item_create = __salt__['pcs.item_create'](
item=item,
item_id=item_id,
item_type=item_type,
create=create,
extra_args=extra_args,
cibfile=cibfile)
log.trace('Output of pcs.item_create: %s', item_create)
if item_create['retcode'] in [0]:
ret['comment'] += 'Created {0} {1} ({2})\n'.format(item, item_id, item_type)
ret['changes'].update({item_id: {'old': '', 'new': six.text_type(item_id)}})
else:
ret['result'] = False
ret['comment'] += 'Failed to create {0} {1} ({2})\n'.format(item, item_id, item_type)
log.trace('ret: %s', ret)
return ret | python | def _item_present(name, item, item_id, item_type, show='show', create='create', extra_args=None, cibname=None):
'''
Ensure that an item is created
name
Irrelevant, not used
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
show
show command (probably None, default: show)
create
create command (create or set f.e., default: create)
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
item_create_required = True
cibfile = None
if isinstance(cibname, six.string_types):
cibfile = _get_cibfile(cibname)
if not isinstance(extra_args, (list, tuple)):
extra_args = []
# split off key and value (item_id contains =)
item_id_key = item_id
item_id_value = None
if '=' in item_id:
item_id_key = item_id.split('=')[0].strip()
item_id_value = item_id.replace(item_id.split('=')[0] + '=', '').strip()
log.trace('item_id_key=%s item_id_value=%s', item_id_key, item_id_value)
# constraints, properties, resource defaults or resource op defaults
# do not support specifying an id on 'show' command
item_id_show = item_id
if item in ['constraint'] or '=' in item_id:
item_id_show = None
is_existing = __salt__['pcs.item_show'](item=item,
item_id=item_id_show,
item_type=item_type,
show=show,
cibfile=cibfile)
log.trace(
'Output of pcs.item_show item=%s item_id=%s item_type=%s cibfile=%s: %s',
item, item_id_show, item_type, cibfile, is_existing
)
# key,value pairs (item_id contains =) - match key and value
if item_id_value is not None:
for line in is_existing['stdout'].splitlines():
if len(line.split(':')) in [2]:
key = line.split(':')[0].strip()
value = line.split(':')[1].strip()
if item_id_key in [key]:
if item_id_value in [value]:
item_create_required = False
# constraints match on '(id:<id>)'
elif item in ['constraint']:
for line in is_existing['stdout'].splitlines():
if '(id:{0})'.format(item_id) in line:
item_create_required = False
# item_id was provided,
# return code 0 indicates, that resource already exists
else:
if is_existing['retcode'] in [0]:
item_create_required = False
if not item_create_required:
ret['comment'] += '{0} {1} ({2}) is already existing\n'.format(
six.text_type(item), six.text_type(item_id), six.text_type(item_type)
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] += '{0} {1} ({2}) is set to be created\n'.format(
six.text_type(item), six.text_type(item_id), six.text_type(item_type)
)
return ret
item_create = __salt__['pcs.item_create'](
item=item,
item_id=item_id,
item_type=item_type,
create=create,
extra_args=extra_args,
cibfile=cibfile)
log.trace('Output of pcs.item_create: %s', item_create)
if item_create['retcode'] in [0]:
ret['comment'] += 'Created {0} {1} ({2})\n'.format(item, item_id, item_type)
ret['changes'].update({item_id: {'old': '', 'new': six.text_type(item_id)}})
else:
ret['result'] = False
ret['comment'] += 'Failed to create {0} {1} ({2})\n'.format(item, item_id, item_type)
log.trace('ret: %s', ret)
return ret | [
"def",
"_item_present",
"(",
"name",
",",
"item",
",",
"item_id",
",",
"item_type",
",",
"show",
"=",
"'show'",
",",
"create",
"=",
"'create'",
",",
"extra_args",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"na... | Ensure that an item is created
name
Irrelevant, not used
item
config, property, resource, constraint etc.
item_id
id of the item
item_type
item type
show
show command (probably None, default: show)
create
create command (create or set f.e., default: create)
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB | [
"Ensure",
"that",
"an",
"item",
"is",
"created"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L248-L357 | train |
saltstack/salt | salt/states/pcs.py | auth | def auth(name, nodes, pcsuser='hacluster', pcspasswd='hacluster', extra_args=None):
'''
Ensure all nodes are authorized to the cluster
name
Irrelevant, not used (recommended: pcs_auth__auth)
nodes
a list of nodes which should be authorized to the cluster
pcsuser
user for communication with pcs (default: hacluster)
pcspasswd
password for pcsuser (default: hacluster)
extra_args
list of extra args for the \'pcs cluster auth\' command
Example:
.. code-block:: yaml
pcs_auth__auth:
pcs.auth:
- nodes:
- node1.example.com
- node2.example.com
- pcsuser: hacluster
- pcspasswd: hoonetorg
- extra_args: []
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
auth_required = False
authorized = __salt__['pcs.is_auth'](nodes=nodes)
log.trace('Output of pcs.is_auth: %s', authorized)
authorized_dict = {}
for line in authorized['stdout'].splitlines():
node = line.split(':')[0].strip()
auth_state = line.split(':')[1].strip()
if node in nodes:
authorized_dict.update({node: auth_state})
log.trace('authorized_dict: %s', authorized_dict)
for node in nodes:
if node in authorized_dict and authorized_dict[node] == 'Already authorized':
ret['comment'] += 'Node {0} is already authorized\n'.format(node)
else:
auth_required = True
if __opts__['test']:
ret['comment'] += 'Node is set to authorize: {0}\n'.format(node)
if not auth_required:
return ret
if __opts__['test']:
ret['result'] = None
return ret
if not isinstance(extra_args, (list, tuple)):
extra_args = []
if '--force' not in extra_args:
extra_args += ['--force']
authorize = __salt__['pcs.auth'](nodes=nodes, pcsuser=pcsuser, pcspasswd=pcspasswd, extra_args=extra_args)
log.trace('Output of pcs.auth: %s', authorize)
authorize_dict = {}
for line in authorize['stdout'].splitlines():
node = line.split(':')[0].strip()
auth_state = line.split(':')[1].strip()
if node in nodes:
authorize_dict.update({node: auth_state})
log.trace('authorize_dict: %s', authorize_dict)
for node in nodes:
if node in authorize_dict and authorize_dict[node] == 'Authorized':
ret['comment'] += 'Authorized {0}\n'.format(node)
ret['changes'].update({node: {'old': '', 'new': 'Authorized'}})
else:
ret['result'] = False
if node in authorized_dict:
ret['comment'] += 'Authorization check for node {0} returned: {1}\n'.format(node, authorized_dict[node])
if node in authorize_dict:
ret['comment'] += 'Failed to authorize {0} with error {1}\n'.format(node, authorize_dict[node])
return ret | python | def auth(name, nodes, pcsuser='hacluster', pcspasswd='hacluster', extra_args=None):
'''
Ensure all nodes are authorized to the cluster
name
Irrelevant, not used (recommended: pcs_auth__auth)
nodes
a list of nodes which should be authorized to the cluster
pcsuser
user for communication with pcs (default: hacluster)
pcspasswd
password for pcsuser (default: hacluster)
extra_args
list of extra args for the \'pcs cluster auth\' command
Example:
.. code-block:: yaml
pcs_auth__auth:
pcs.auth:
- nodes:
- node1.example.com
- node2.example.com
- pcsuser: hacluster
- pcspasswd: hoonetorg
- extra_args: []
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
auth_required = False
authorized = __salt__['pcs.is_auth'](nodes=nodes)
log.trace('Output of pcs.is_auth: %s', authorized)
authorized_dict = {}
for line in authorized['stdout'].splitlines():
node = line.split(':')[0].strip()
auth_state = line.split(':')[1].strip()
if node in nodes:
authorized_dict.update({node: auth_state})
log.trace('authorized_dict: %s', authorized_dict)
for node in nodes:
if node in authorized_dict and authorized_dict[node] == 'Already authorized':
ret['comment'] += 'Node {0} is already authorized\n'.format(node)
else:
auth_required = True
if __opts__['test']:
ret['comment'] += 'Node is set to authorize: {0}\n'.format(node)
if not auth_required:
return ret
if __opts__['test']:
ret['result'] = None
return ret
if not isinstance(extra_args, (list, tuple)):
extra_args = []
if '--force' not in extra_args:
extra_args += ['--force']
authorize = __salt__['pcs.auth'](nodes=nodes, pcsuser=pcsuser, pcspasswd=pcspasswd, extra_args=extra_args)
log.trace('Output of pcs.auth: %s', authorize)
authorize_dict = {}
for line in authorize['stdout'].splitlines():
node = line.split(':')[0].strip()
auth_state = line.split(':')[1].strip()
if node in nodes:
authorize_dict.update({node: auth_state})
log.trace('authorize_dict: %s', authorize_dict)
for node in nodes:
if node in authorize_dict and authorize_dict[node] == 'Authorized':
ret['comment'] += 'Authorized {0}\n'.format(node)
ret['changes'].update({node: {'old': '', 'new': 'Authorized'}})
else:
ret['result'] = False
if node in authorized_dict:
ret['comment'] += 'Authorization check for node {0} returned: {1}\n'.format(node, authorized_dict[node])
if node in authorize_dict:
ret['comment'] += 'Failed to authorize {0} with error {1}\n'.format(node, authorize_dict[node])
return ret | [
"def",
"auth",
"(",
"name",
",",
"nodes",
",",
"pcsuser",
"=",
"'hacluster'",
",",
"pcspasswd",
"=",
"'hacluster'",
",",
"extra_args",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
... | Ensure all nodes are authorized to the cluster
name
Irrelevant, not used (recommended: pcs_auth__auth)
nodes
a list of nodes which should be authorized to the cluster
pcsuser
user for communication with pcs (default: hacluster)
pcspasswd
password for pcsuser (default: hacluster)
extra_args
list of extra args for the \'pcs cluster auth\' command
Example:
.. code-block:: yaml
pcs_auth__auth:
pcs.auth:
- nodes:
- node1.example.com
- node2.example.com
- pcsuser: hacluster
- pcspasswd: hoonetorg
- extra_args: [] | [
"Ensure",
"all",
"nodes",
"are",
"authorized",
"to",
"the",
"cluster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L360-L444 | train |
saltstack/salt | salt/states/pcs.py | cluster_setup | def cluster_setup(name, nodes, pcsclustername='pcscluster', extra_args=None):
'''
Setup Pacemaker cluster on nodes.
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: pcs_setup__setup)
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster
extra_args
list of extra args for the \'pcs cluster setup\' command
Example:
.. code-block:: yaml
pcs_setup__setup:
pcs.cluster_setup:
- nodes:
- node1.example.com
- node2.example.com
- pcsclustername: pcscluster
- extra_args:
- '--start'
- '--enable'
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
setup_required = False
config_show = __salt__['pcs.config_show']()
log.trace('Output of pcs.config_show: %s', config_show)
for line in config_show['stdout'].splitlines():
if len(line.split(':')) in [2]:
key = line.split(':')[0].strip()
value = line.split(':')[1].strip()
if key in ['Cluster Name']:
if value in [pcsclustername]:
ret['comment'] += 'Cluster {0} is already set up\n'.format(pcsclustername)
else:
setup_required = True
if __opts__['test']:
ret['comment'] += 'Cluster {0} is set to set up\n'.format(pcsclustername)
if not setup_required:
return ret
if __opts__['test']:
ret['result'] = None
return ret
if not isinstance(extra_args, (list, tuple)):
extra_args = []
setup = __salt__['pcs.cluster_setup'](nodes=nodes, pcsclustername=pcsclustername, extra_args=extra_args)
log.trace('Output of pcs.cluster_setup: %s', setup)
setup_dict = {}
for line in setup['stdout'].splitlines():
log.trace('line: %s', line)
log.trace('line.split(:).len: %s', len(line.split(':')))
if len(line.split(':')) in [2]:
node = line.split(':')[0].strip()
setup_state = line.split(':')[1].strip()
if node in nodes:
setup_dict.update({node: setup_state})
log.trace('setup_dict: %s', setup_dict)
for node in nodes:
if node in setup_dict and setup_dict[node] in ['Succeeded', 'Success']:
ret['comment'] += 'Set up {0}\n'.format(node)
ret['changes'].update({node: {'old': '', 'new': 'Setup'}})
else:
ret['result'] = False
ret['comment'] += 'Failed to setup {0}\n'.format(node)
if node in setup_dict:
ret['comment'] += '{0}: setup_dict: {1}\n'.format(node, setup_dict[node])
ret['comment'] += six.text_type(setup)
log.trace('ret: %s', ret)
return ret | python | def cluster_setup(name, nodes, pcsclustername='pcscluster', extra_args=None):
'''
Setup Pacemaker cluster on nodes.
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: pcs_setup__setup)
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster
extra_args
list of extra args for the \'pcs cluster setup\' command
Example:
.. code-block:: yaml
pcs_setup__setup:
pcs.cluster_setup:
- nodes:
- node1.example.com
- node2.example.com
- pcsclustername: pcscluster
- extra_args:
- '--start'
- '--enable'
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
setup_required = False
config_show = __salt__['pcs.config_show']()
log.trace('Output of pcs.config_show: %s', config_show)
for line in config_show['stdout'].splitlines():
if len(line.split(':')) in [2]:
key = line.split(':')[0].strip()
value = line.split(':')[1].strip()
if key in ['Cluster Name']:
if value in [pcsclustername]:
ret['comment'] += 'Cluster {0} is already set up\n'.format(pcsclustername)
else:
setup_required = True
if __opts__['test']:
ret['comment'] += 'Cluster {0} is set to set up\n'.format(pcsclustername)
if not setup_required:
return ret
if __opts__['test']:
ret['result'] = None
return ret
if not isinstance(extra_args, (list, tuple)):
extra_args = []
setup = __salt__['pcs.cluster_setup'](nodes=nodes, pcsclustername=pcsclustername, extra_args=extra_args)
log.trace('Output of pcs.cluster_setup: %s', setup)
setup_dict = {}
for line in setup['stdout'].splitlines():
log.trace('line: %s', line)
log.trace('line.split(:).len: %s', len(line.split(':')))
if len(line.split(':')) in [2]:
node = line.split(':')[0].strip()
setup_state = line.split(':')[1].strip()
if node in nodes:
setup_dict.update({node: setup_state})
log.trace('setup_dict: %s', setup_dict)
for node in nodes:
if node in setup_dict and setup_dict[node] in ['Succeeded', 'Success']:
ret['comment'] += 'Set up {0}\n'.format(node)
ret['changes'].update({node: {'old': '', 'new': 'Setup'}})
else:
ret['result'] = False
ret['comment'] += 'Failed to setup {0}\n'.format(node)
if node in setup_dict:
ret['comment'] += '{0}: setup_dict: {1}\n'.format(node, setup_dict[node])
ret['comment'] += six.text_type(setup)
log.trace('ret: %s', ret)
return ret | [
"def",
"cluster_setup",
"(",
"name",
",",
"nodes",
",",
"pcsclustername",
"=",
"'pcscluster'",
",",
"extra_args",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
... | Setup Pacemaker cluster on nodes.
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: pcs_setup__setup)
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster
extra_args
list of extra args for the \'pcs cluster setup\' command
Example:
.. code-block:: yaml
pcs_setup__setup:
pcs.cluster_setup:
- nodes:
- node1.example.com
- node2.example.com
- pcsclustername: pcscluster
- extra_args:
- '--start'
- '--enable' | [
"Setup",
"Pacemaker",
"cluster",
"on",
"nodes",
".",
"Should",
"be",
"run",
"on",
"one",
"cluster",
"node",
"only",
"(",
"there",
"may",
"be",
"races",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L447-L533 | train |
saltstack/salt | salt/states/pcs.py | cluster_node_present | def cluster_node_present(name, node, extra_args=None):
'''
Add a node to the Pacemaker cluster via PCS
Should be run on one cluster node only
(there may be races)
Can only be run on a already setup/added node
name
Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})
node
node that should be added
extra_args
list of extra args for the \'pcs cluster node add\' command
Example:
.. code-block:: yaml
pcs_setup__node_add_node1.example.com:
pcs.cluster_node_present:
- node: node1.example.com
- extra_args:
- '--start'
- '--enable'
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
node_add_required = True
current_nodes = []
is_member_cmd = ['pcs', 'status', 'nodes', 'corosync']
is_member = __salt__['cmd.run_all'](is_member_cmd, output_loglevel='trace', python_shell=False)
log.trace('Output of pcs status nodes corosync: %s', is_member)
for line in is_member['stdout'].splitlines():
try:
key, value = [x.strip() for x in line.split(':')]
except ValueError:
continue
else:
if not value or key not in ('Offline', 'Online'):
continue
values = value.split(':')
if node in values:
node_add_required = False
ret['comment'] += 'Node {0} is already member of the cluster\n'.format(node)
else:
current_nodes += values
if not node_add_required:
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] += 'Node {0} is set to be added to the cluster\n'.format(node)
return ret
if not isinstance(extra_args, (list, tuple)):
extra_args = []
node_add = __salt__['pcs.cluster_node_add'](node=node, extra_args=extra_args)
log.trace('Output of pcs.cluster_node_add: %s', node_add)
node_add_dict = {}
for line in node_add['stdout'].splitlines():
log.trace('line: %s', line)
log.trace('line.split(:).len: %s', len(line.split(':')))
if len(line.split(':')) in [2]:
current_node = line.split(':')[0].strip()
current_node_add_state = line.split(':')[1].strip()
if current_node in current_nodes + [node]:
node_add_dict.update({current_node: current_node_add_state})
log.trace('node_add_dict: %s', node_add_dict)
for current_node in current_nodes:
if current_node in node_add_dict:
if node_add_dict[current_node] not in ['Corosync updated']:
ret['result'] = False
ret['comment'] += 'Failed to update corosync.conf on node {0}\n'.format(current_node)
ret['comment'] += '{0}: node_add_dict: {1}\n'.format(current_node, node_add_dict[current_node])
else:
ret['result'] = False
ret['comment'] += 'Failed to update corosync.conf on node {0}\n'.format(current_node)
if node in node_add_dict and node_add_dict[node] in ['Succeeded', 'Success']:
ret['comment'] += 'Added node {0}\n'.format(node)
ret['changes'].update({node: {'old': '', 'new': 'Added'}})
else:
ret['result'] = False
ret['comment'] += 'Failed to add node{0}\n'.format(node)
if node in node_add_dict:
ret['comment'] += '{0}: node_add_dict: {1}\n'.format(node, node_add_dict[node])
ret['comment'] += six.text_type(node_add)
log.trace('ret: %s', ret)
return ret | python | def cluster_node_present(name, node, extra_args=None):
'''
Add a node to the Pacemaker cluster via PCS
Should be run on one cluster node only
(there may be races)
Can only be run on a already setup/added node
name
Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})
node
node that should be added
extra_args
list of extra args for the \'pcs cluster node add\' command
Example:
.. code-block:: yaml
pcs_setup__node_add_node1.example.com:
pcs.cluster_node_present:
- node: node1.example.com
- extra_args:
- '--start'
- '--enable'
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
node_add_required = True
current_nodes = []
is_member_cmd = ['pcs', 'status', 'nodes', 'corosync']
is_member = __salt__['cmd.run_all'](is_member_cmd, output_loglevel='trace', python_shell=False)
log.trace('Output of pcs status nodes corosync: %s', is_member)
for line in is_member['stdout'].splitlines():
try:
key, value = [x.strip() for x in line.split(':')]
except ValueError:
continue
else:
if not value or key not in ('Offline', 'Online'):
continue
values = value.split(':')
if node in values:
node_add_required = False
ret['comment'] += 'Node {0} is already member of the cluster\n'.format(node)
else:
current_nodes += values
if not node_add_required:
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] += 'Node {0} is set to be added to the cluster\n'.format(node)
return ret
if not isinstance(extra_args, (list, tuple)):
extra_args = []
node_add = __salt__['pcs.cluster_node_add'](node=node, extra_args=extra_args)
log.trace('Output of pcs.cluster_node_add: %s', node_add)
node_add_dict = {}
for line in node_add['stdout'].splitlines():
log.trace('line: %s', line)
log.trace('line.split(:).len: %s', len(line.split(':')))
if len(line.split(':')) in [2]:
current_node = line.split(':')[0].strip()
current_node_add_state = line.split(':')[1].strip()
if current_node in current_nodes + [node]:
node_add_dict.update({current_node: current_node_add_state})
log.trace('node_add_dict: %s', node_add_dict)
for current_node in current_nodes:
if current_node in node_add_dict:
if node_add_dict[current_node] not in ['Corosync updated']:
ret['result'] = False
ret['comment'] += 'Failed to update corosync.conf on node {0}\n'.format(current_node)
ret['comment'] += '{0}: node_add_dict: {1}\n'.format(current_node, node_add_dict[current_node])
else:
ret['result'] = False
ret['comment'] += 'Failed to update corosync.conf on node {0}\n'.format(current_node)
if node in node_add_dict and node_add_dict[node] in ['Succeeded', 'Success']:
ret['comment'] += 'Added node {0}\n'.format(node)
ret['changes'].update({node: {'old': '', 'new': 'Added'}})
else:
ret['result'] = False
ret['comment'] += 'Failed to add node{0}\n'.format(node)
if node in node_add_dict:
ret['comment'] += '{0}: node_add_dict: {1}\n'.format(node, node_add_dict[node])
ret['comment'] += six.text_type(node_add)
log.trace('ret: %s', ret)
return ret | [
"def",
"cluster_node_present",
"(",
"name",
",",
"node",
",",
"extra_args",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"node_add_requir... | Add a node to the Pacemaker cluster via PCS
Should be run on one cluster node only
(there may be races)
Can only be run on a already setup/added node
name
Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})
node
node that should be added
extra_args
list of extra args for the \'pcs cluster node add\' command
Example:
.. code-block:: yaml
pcs_setup__node_add_node1.example.com:
pcs.cluster_node_present:
- node: node1.example.com
- extra_args:
- '--start'
- '--enable' | [
"Add",
"a",
"node",
"to",
"the",
"Pacemaker",
"cluster",
"via",
"PCS",
"Should",
"be",
"run",
"on",
"one",
"cluster",
"node",
"only",
"(",
"there",
"may",
"be",
"races",
")",
"Can",
"only",
"be",
"run",
"on",
"a",
"already",
"setup",
"/",
"added",
"n... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L536-L632 | train |
saltstack/salt | salt/states/pcs.py | cib_present | def cib_present(name, cibname, scope=None, extra_args=None):
'''
Ensure that a CIB-file with the content of the current live CIB is created
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: {{formulaname}}__cib_present_{{cibname}})
cibname
name/path of the file containing the CIB
scope
specific section of the CIB (default:
extra_args
additional options for creating the CIB-file
Example:
.. code-block:: yaml
mysql_pcs__cib_present_cib_for_galera:
pcs.cib_present:
- cibname: cib_for_galera
- scope: None
- extra_args: None
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
cib_hash_form = 'sha256'
cib_create_required = False
cib_cksum_required = False
cib_required = False
cibpath = _get_cibpath()
cibfile = _get_cibfile(cibname)
cibfile_tmp = _get_cibfile_tmp(cibname)
cibfile_cksum = _get_cibfile_cksum(cibname)
if not os.path.exists(cibpath):
os.makedirs(cibpath)
if not isinstance(extra_args, (list, tuple)):
extra_args = []
if os.path.exists(cibfile_tmp):
__salt__['file.remove'](cibfile_tmp)
cib_create = __salt__['pcs.cib_create'](cibfile=cibfile_tmp, scope=scope, extra_args=extra_args)
log.trace('Output of pcs.cib_create: %s', cib_create)
if cib_create['retcode'] not in [0] or not os.path.exists(cibfile_tmp):
ret['result'] = False
ret['comment'] += 'Failed to get live CIB\n'
return ret
cib_hash_live = '{0}:{1}'.format(cib_hash_form, __salt__['file.get_hash'](path=cibfile_tmp, form=cib_hash_form))
log.trace('cib_hash_live: %s', cib_hash_live)
cib_hash_cur = _file_read(path=cibfile_cksum)
if cib_hash_cur not in [cib_hash_live]:
cib_cksum_required = True
log.trace('cib_hash_cur: %s', cib_hash_cur)
if not os.path.exists(cibfile) or not __salt__['file.check_hash'](path=cibfile, file_hash=cib_hash_live):
cib_create_required = True
if cib_cksum_required or cib_create_required:
cib_required = True
if not cib_create_required:
__salt__['file.remove'](cibfile_tmp)
ret['comment'] += 'CIB {0} is already equal to the live CIB\n'.format(cibname)
if not cib_cksum_required:
ret['comment'] += 'CIB {0} checksum is correct\n'.format(cibname)
if not cib_required:
return ret
if __opts__['test']:
__salt__['file.remove'](cibfile_tmp)
ret['result'] = None
if cib_create_required:
ret['comment'] += 'CIB {0} is set to be created/updated\n'.format(cibname)
if cib_cksum_required:
ret['comment'] += 'CIB {0} checksum is set to be created/updated\n'.format(cibname)
return ret
if cib_create_required:
__salt__['file.move'](cibfile_tmp, cibfile)
if __salt__['file.check_hash'](path=cibfile, file_hash=cib_hash_live):
ret['comment'] += 'Created/updated CIB {0}\n'.format(cibname)
ret['changes'].update({'cibfile': cibfile})
else:
ret['result'] = False
ret['comment'] += 'Failed to create/update CIB {0}\n'.format(cibname)
if cib_cksum_required:
_file_write(cibfile_cksum, cib_hash_live)
if _file_read(cibfile_cksum) in [cib_hash_live]:
ret['comment'] += 'Created/updated checksum {0} of CIB {1}\n'.format(cib_hash_live, cibname)
ret['changes'].update({'cibcksum': cib_hash_live})
else:
ret['result'] = False
ret['comment'] += 'Failed to create/update checksum {0} CIB {1}\n'.format(cib_hash_live, cibname)
log.trace('ret: %s', ret)
return ret | python | def cib_present(name, cibname, scope=None, extra_args=None):
'''
Ensure that a CIB-file with the content of the current live CIB is created
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: {{formulaname}}__cib_present_{{cibname}})
cibname
name/path of the file containing the CIB
scope
specific section of the CIB (default:
extra_args
additional options for creating the CIB-file
Example:
.. code-block:: yaml
mysql_pcs__cib_present_cib_for_galera:
pcs.cib_present:
- cibname: cib_for_galera
- scope: None
- extra_args: None
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
cib_hash_form = 'sha256'
cib_create_required = False
cib_cksum_required = False
cib_required = False
cibpath = _get_cibpath()
cibfile = _get_cibfile(cibname)
cibfile_tmp = _get_cibfile_tmp(cibname)
cibfile_cksum = _get_cibfile_cksum(cibname)
if not os.path.exists(cibpath):
os.makedirs(cibpath)
if not isinstance(extra_args, (list, tuple)):
extra_args = []
if os.path.exists(cibfile_tmp):
__salt__['file.remove'](cibfile_tmp)
cib_create = __salt__['pcs.cib_create'](cibfile=cibfile_tmp, scope=scope, extra_args=extra_args)
log.trace('Output of pcs.cib_create: %s', cib_create)
if cib_create['retcode'] not in [0] or not os.path.exists(cibfile_tmp):
ret['result'] = False
ret['comment'] += 'Failed to get live CIB\n'
return ret
cib_hash_live = '{0}:{1}'.format(cib_hash_form, __salt__['file.get_hash'](path=cibfile_tmp, form=cib_hash_form))
log.trace('cib_hash_live: %s', cib_hash_live)
cib_hash_cur = _file_read(path=cibfile_cksum)
if cib_hash_cur not in [cib_hash_live]:
cib_cksum_required = True
log.trace('cib_hash_cur: %s', cib_hash_cur)
if not os.path.exists(cibfile) or not __salt__['file.check_hash'](path=cibfile, file_hash=cib_hash_live):
cib_create_required = True
if cib_cksum_required or cib_create_required:
cib_required = True
if not cib_create_required:
__salt__['file.remove'](cibfile_tmp)
ret['comment'] += 'CIB {0} is already equal to the live CIB\n'.format(cibname)
if not cib_cksum_required:
ret['comment'] += 'CIB {0} checksum is correct\n'.format(cibname)
if not cib_required:
return ret
if __opts__['test']:
__salt__['file.remove'](cibfile_tmp)
ret['result'] = None
if cib_create_required:
ret['comment'] += 'CIB {0} is set to be created/updated\n'.format(cibname)
if cib_cksum_required:
ret['comment'] += 'CIB {0} checksum is set to be created/updated\n'.format(cibname)
return ret
if cib_create_required:
__salt__['file.move'](cibfile_tmp, cibfile)
if __salt__['file.check_hash'](path=cibfile, file_hash=cib_hash_live):
ret['comment'] += 'Created/updated CIB {0}\n'.format(cibname)
ret['changes'].update({'cibfile': cibfile})
else:
ret['result'] = False
ret['comment'] += 'Failed to create/update CIB {0}\n'.format(cibname)
if cib_cksum_required:
_file_write(cibfile_cksum, cib_hash_live)
if _file_read(cibfile_cksum) in [cib_hash_live]:
ret['comment'] += 'Created/updated checksum {0} of CIB {1}\n'.format(cib_hash_live, cibname)
ret['changes'].update({'cibcksum': cib_hash_live})
else:
ret['result'] = False
ret['comment'] += 'Failed to create/update checksum {0} CIB {1}\n'.format(cib_hash_live, cibname)
log.trace('ret: %s', ret)
return ret | [
"def",
"cib_present",
"(",
"name",
",",
"cibname",
",",
"scope",
"=",
"None",
",",
"extra_args",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"... | Ensure that a CIB-file with the content of the current live CIB is created
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: {{formulaname}}__cib_present_{{cibname}})
cibname
name/path of the file containing the CIB
scope
specific section of the CIB (default:
extra_args
additional options for creating the CIB-file
Example:
.. code-block:: yaml
mysql_pcs__cib_present_cib_for_galera:
pcs.cib_present:
- cibname: cib_for_galera
- scope: None
- extra_args: None | [
"Ensure",
"that",
"a",
"CIB",
"-",
"file",
"with",
"the",
"content",
"of",
"the",
"current",
"live",
"CIB",
"is",
"created"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L635-L748 | train |
saltstack/salt | salt/states/pcs.py | cib_pushed | def cib_pushed(name, cibname, scope=None, extra_args=None):
'''
Ensure that a CIB-file is pushed if it is changed since the creation of it with pcs.cib_present
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: {{formulaname}}__cib_pushed_{{cibname}})
cibname
name/path of the file containing the CIB
scope
specific section of the CIB
extra_args
additional options for creating the CIB-file
Example:
.. code-block:: yaml
mysql_pcs__cib_pushed_cib_for_galera:
pcs.cib_pushed:
- cibname: cib_for_galera
- scope: None
- extra_args: None
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
cib_hash_form = 'sha256'
cib_push_required = False
cibfile = _get_cibfile(cibname)
cibfile_cksum = _get_cibfile_cksum(cibname)
if not isinstance(extra_args, (list, tuple)):
extra_args = []
if not os.path.exists(cibfile):
ret['result'] = False
ret['comment'] += 'CIB-file {0} does not exist\n'.format(cibfile)
return ret
cib_hash_cibfile = '{0}:{1}'.format(cib_hash_form, __salt__['file.get_hash'](path=cibfile, form=cib_hash_form))
log.trace('cib_hash_cibfile: %s', cib_hash_cibfile)
if _file_read(cibfile_cksum) not in [cib_hash_cibfile]:
cib_push_required = True
if not cib_push_required:
ret['comment'] += 'CIB {0} is not changed since creation through pcs.cib_present\n'.format(cibname)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] += 'CIB {0} is set to be pushed as the new live CIB\n'.format(cibname)
return ret
cib_push = __salt__['pcs.cib_push'](cibfile=cibfile, scope=scope, extra_args=extra_args)
log.trace('Output of pcs.cib_push: %s', cib_push)
if cib_push['retcode'] in [0]:
ret['comment'] += 'Pushed CIB {0}\n'.format(cibname)
ret['changes'].update({'cibfile_pushed': cibfile})
else:
ret['result'] = False
ret['comment'] += 'Failed to push CIB {0}\n'.format(cibname)
log.trace('ret: %s', ret)
return ret | python | def cib_pushed(name, cibname, scope=None, extra_args=None):
'''
Ensure that a CIB-file is pushed if it is changed since the creation of it with pcs.cib_present
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: {{formulaname}}__cib_pushed_{{cibname}})
cibname
name/path of the file containing the CIB
scope
specific section of the CIB
extra_args
additional options for creating the CIB-file
Example:
.. code-block:: yaml
mysql_pcs__cib_pushed_cib_for_galera:
pcs.cib_pushed:
- cibname: cib_for_galera
- scope: None
- extra_args: None
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
cib_hash_form = 'sha256'
cib_push_required = False
cibfile = _get_cibfile(cibname)
cibfile_cksum = _get_cibfile_cksum(cibname)
if not isinstance(extra_args, (list, tuple)):
extra_args = []
if not os.path.exists(cibfile):
ret['result'] = False
ret['comment'] += 'CIB-file {0} does not exist\n'.format(cibfile)
return ret
cib_hash_cibfile = '{0}:{1}'.format(cib_hash_form, __salt__['file.get_hash'](path=cibfile, form=cib_hash_form))
log.trace('cib_hash_cibfile: %s', cib_hash_cibfile)
if _file_read(cibfile_cksum) not in [cib_hash_cibfile]:
cib_push_required = True
if not cib_push_required:
ret['comment'] += 'CIB {0} is not changed since creation through pcs.cib_present\n'.format(cibname)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] += 'CIB {0} is set to be pushed as the new live CIB\n'.format(cibname)
return ret
cib_push = __salt__['pcs.cib_push'](cibfile=cibfile, scope=scope, extra_args=extra_args)
log.trace('Output of pcs.cib_push: %s', cib_push)
if cib_push['retcode'] in [0]:
ret['comment'] += 'Pushed CIB {0}\n'.format(cibname)
ret['changes'].update({'cibfile_pushed': cibfile})
else:
ret['result'] = False
ret['comment'] += 'Failed to push CIB {0}\n'.format(cibname)
log.trace('ret: %s', ret)
return ret | [
"def",
"cib_pushed",
"(",
"name",
",",
"cibname",
",",
"scope",
"=",
"None",
",",
"extra_args",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}... | Ensure that a CIB-file is pushed if it is changed since the creation of it with pcs.cib_present
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: {{formulaname}}__cib_pushed_{{cibname}})
cibname
name/path of the file containing the CIB
scope
specific section of the CIB
extra_args
additional options for creating the CIB-file
Example:
.. code-block:: yaml
mysql_pcs__cib_pushed_cib_for_galera:
pcs.cib_pushed:
- cibname: cib_for_galera
- scope: None
- extra_args: None | [
"Ensure",
"that",
"a",
"CIB",
"-",
"file",
"is",
"pushed",
"if",
"it",
"is",
"changed",
"since",
"the",
"creation",
"of",
"it",
"with",
"pcs",
".",
"cib_present"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L751-L821 | train |
saltstack/salt | salt/states/pcs.py | prop_has_value | def prop_has_value(name, prop, value, extra_args=None, cibname=None):
'''
Ensure that a property in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: pcs_properties__prop_has_value_{{prop}})
prop
name of the property
value
value of the property
extra_args
additional options for the pcs property command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__prop_has_value_no-quorum-policy:
pcs.prop_has_value:
- prop: no-quorum-policy
- value: ignore
- cibname: cib_for_cluster_settings
'''
return _item_present(name=name,
item='property',
item_id='{0}={1}'.format(prop, value),
item_type=None,
create='set',
extra_args=extra_args,
cibname=cibname) | python | def prop_has_value(name, prop, value, extra_args=None, cibname=None):
'''
Ensure that a property in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: pcs_properties__prop_has_value_{{prop}})
prop
name of the property
value
value of the property
extra_args
additional options for the pcs property command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__prop_has_value_no-quorum-policy:
pcs.prop_has_value:
- prop: no-quorum-policy
- value: ignore
- cibname: cib_for_cluster_settings
'''
return _item_present(name=name,
item='property',
item_id='{0}={1}'.format(prop, value),
item_type=None,
create='set',
extra_args=extra_args,
cibname=cibname) | [
"def",
"prop_has_value",
"(",
"name",
",",
"prop",
",",
"value",
",",
"extra_args",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'property'",
",",
"item_id",
"=",
"'{0}={1}'",... | Ensure that a property in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
name
Irrelevant, not used (recommended: pcs_properties__prop_has_value_{{prop}})
prop
name of the property
value
value of the property
extra_args
additional options for the pcs property command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__prop_has_value_no-quorum-policy:
pcs.prop_has_value:
- prop: no-quorum-policy
- value: ignore
- cibname: cib_for_cluster_settings | [
"Ensure",
"that",
"a",
"property",
"in",
"the",
"cluster",
"is",
"set",
"to",
"a",
"given",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L824-L858 | train |
saltstack/salt | salt/states/pcs.py | resource_defaults_to | def resource_defaults_to(name, default, value, extra_args=None, cibname=None):
'''
Ensure a resource default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_defaults_to_{{default}})
default
name of the default resource property
value
value of the default resource property
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__resource_defaults_to_resource-stickiness:
pcs.resource_defaults_to:
- default: resource-stickiness
- value: 100
- cibname: cib_for_cluster_settings
'''
return _item_present(name=name,
item='resource',
item_id='{0}={1}'.format(default, value),
item_type=None,
show='defaults',
create='defaults',
extra_args=extra_args,
cibname=cibname) | python | def resource_defaults_to(name, default, value, extra_args=None, cibname=None):
'''
Ensure a resource default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_defaults_to_{{default}})
default
name of the default resource property
value
value of the default resource property
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__resource_defaults_to_resource-stickiness:
pcs.resource_defaults_to:
- default: resource-stickiness
- value: 100
- cibname: cib_for_cluster_settings
'''
return _item_present(name=name,
item='resource',
item_id='{0}={1}'.format(default, value),
item_type=None,
show='defaults',
create='defaults',
extra_args=extra_args,
cibname=cibname) | [
"def",
"resource_defaults_to",
"(",
"name",
",",
"default",
",",
"value",
",",
"extra_args",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'resource'",
",",
"item_id",
"=",
"'{... | Ensure a resource default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_defaults_to_{{default}})
default
name of the default resource property
value
value of the default resource property
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__resource_defaults_to_resource-stickiness:
pcs.resource_defaults_to:
- default: resource-stickiness
- value: 100
- cibname: cib_for_cluster_settings | [
"Ensure",
"a",
"resource",
"default",
"in",
"the",
"cluster",
"is",
"set",
"to",
"a",
"given",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L861-L897 | train |
saltstack/salt | salt/states/pcs.py | resource_op_defaults_to | def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
'''
Ensure a resource operation default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_op_defaults_to_{{op_default}})
op_default
name of the operation default resource property
value
value of the operation default resource property
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__resource_op_defaults_to_monitor-interval:
pcs.resource_op_defaults_to:
- op_default: monitor-interval
- value: 60s
- cibname: cib_for_cluster_settings
'''
return _item_present(name=name,
item='resource',
item_id='{0}={1}'.format(op_default, value),
item_type=None,
show=['op', 'defaults'],
create=['op', 'defaults'],
extra_args=extra_args,
cibname=cibname) | python | def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
'''
Ensure a resource operation default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_op_defaults_to_{{op_default}})
op_default
name of the operation default resource property
value
value of the operation default resource property
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__resource_op_defaults_to_monitor-interval:
pcs.resource_op_defaults_to:
- op_default: monitor-interval
- value: 60s
- cibname: cib_for_cluster_settings
'''
return _item_present(name=name,
item='resource',
item_id='{0}={1}'.format(op_default, value),
item_type=None,
show=['op', 'defaults'],
create=['op', 'defaults'],
extra_args=extra_args,
cibname=cibname) | [
"def",
"resource_op_defaults_to",
"(",
"name",
",",
"op_default",
",",
"value",
",",
"extra_args",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'resource'",
",",
"item_id",
"=",... | Ensure a resource operation default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_properties__resource_op_defaults_to_{{op_default}})
op_default
name of the operation default resource property
value
value of the operation default resource property
extra_args
additional options for the pcs command
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_properties__resource_op_defaults_to_monitor-interval:
pcs.resource_op_defaults_to:
- op_default: monitor-interval
- value: 60s
- cibname: cib_for_cluster_settings | [
"Ensure",
"a",
"resource",
"operation",
"default",
"in",
"the",
"cluster",
"is",
"set",
"to",
"a",
"given",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L900-L936 | train |
saltstack/salt | salt/states/pcs.py | stonith_present | def stonith_present(name, stonith_id, stonith_device_type, stonith_device_options=None, cibname=None):
'''
Ensure that a fencing resource is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_stonith__created_{{stonith_id}})
stonith_id
name for the stonith resource
stonith_device_type
name of the stonith agent fence_eps, fence_xvm f.e.
stonith_device_options
additional options for creating the stonith resource
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_stonith__created_eps_fence:
pcs.stonith_present:
- stonith_id: eps_fence
- stonith_device_type: fence_eps
- stonith_device_options:
- 'pcmk_host_map=node1.example.org:01;node2.example.org:02'
- 'ipaddr=myepsdevice.example.org'
- 'power_wait=5'
- 'verbose=1'
- 'debug=/var/log/pcsd/eps_fence.log'
- 'login=hidden'
- 'passwd=hoonetorg'
- cibname: cib_for_stonith
'''
return _item_present(name=name,
item='stonith',
item_id=stonith_id,
item_type=stonith_device_type,
extra_args=stonith_device_options,
cibname=cibname) | python | def stonith_present(name, stonith_id, stonith_device_type, stonith_device_options=None, cibname=None):
'''
Ensure that a fencing resource is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_stonith__created_{{stonith_id}})
stonith_id
name for the stonith resource
stonith_device_type
name of the stonith agent fence_eps, fence_xvm f.e.
stonith_device_options
additional options for creating the stonith resource
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_stonith__created_eps_fence:
pcs.stonith_present:
- stonith_id: eps_fence
- stonith_device_type: fence_eps
- stonith_device_options:
- 'pcmk_host_map=node1.example.org:01;node2.example.org:02'
- 'ipaddr=myepsdevice.example.org'
- 'power_wait=5'
- 'verbose=1'
- 'debug=/var/log/pcsd/eps_fence.log'
- 'login=hidden'
- 'passwd=hoonetorg'
- cibname: cib_for_stonith
'''
return _item_present(name=name,
item='stonith',
item_id=stonith_id,
item_type=stonith_device_type,
extra_args=stonith_device_options,
cibname=cibname) | [
"def",
"stonith_present",
"(",
"name",
",",
"stonith_id",
",",
"stonith_device_type",
",",
"stonith_device_options",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'stonith'",
",",
... | Ensure that a fencing resource is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: pcs_stonith__created_{{stonith_id}})
stonith_id
name for the stonith resource
stonith_device_type
name of the stonith agent fence_eps, fence_xvm f.e.
stonith_device_options
additional options for creating the stonith resource
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
pcs_stonith__created_eps_fence:
pcs.stonith_present:
- stonith_id: eps_fence
- stonith_device_type: fence_eps
- stonith_device_options:
- 'pcmk_host_map=node1.example.org:01;node2.example.org:02'
- 'ipaddr=myepsdevice.example.org'
- 'power_wait=5'
- 'verbose=1'
- 'debug=/var/log/pcsd/eps_fence.log'
- 'login=hidden'
- 'passwd=hoonetorg'
- cibname: cib_for_stonith | [
"Ensure",
"that",
"a",
"fencing",
"resource",
"is",
"created"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L939-L981 | train |
saltstack/salt | salt/states/pcs.py | resource_present | def resource_present(name, resource_id, resource_type, resource_options=None, cibname=None):
'''
Ensure that a resource is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: {{formulaname}}__resource_present_{{resource_id}})
resource_id
name for the resource
resource_type
resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)
resource_options
additional options for creating the resource
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
mysql_pcs__resource_present_galera:
pcs.resource_present:
- resource_id: galera
- resource_type: "ocf:heartbeat:galera"
- resource_options:
- 'wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org'
- '--master'
- cibname: cib_for_galera
'''
return _item_present(name=name,
item='resource',
item_id=resource_id,
item_type=resource_type,
extra_args=resource_options,
cibname=cibname) | python | def resource_present(name, resource_id, resource_type, resource_options=None, cibname=None):
'''
Ensure that a resource is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: {{formulaname}}__resource_present_{{resource_id}})
resource_id
name for the resource
resource_type
resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)
resource_options
additional options for creating the resource
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
mysql_pcs__resource_present_galera:
pcs.resource_present:
- resource_id: galera
- resource_type: "ocf:heartbeat:galera"
- resource_options:
- 'wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org'
- '--master'
- cibname: cib_for_galera
'''
return _item_present(name=name,
item='resource',
item_id=resource_id,
item_type=resource_type,
extra_args=resource_options,
cibname=cibname) | [
"def",
"resource_present",
"(",
"name",
",",
"resource_id",
",",
"resource_type",
",",
"resource_options",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'resource'",
",",
"item_id"... | Ensure that a resource is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: {{formulaname}}__resource_present_{{resource_id}})
resource_id
name for the resource
resource_type
resource type (f.e. ocf:heartbeat:IPaddr2 or VirtualIP)
resource_options
additional options for creating the resource
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
mysql_pcs__resource_present_galera:
pcs.resource_present:
- resource_id: galera
- resource_type: "ocf:heartbeat:galera"
- resource_options:
- 'wsrep_cluster_address=gcomm://node1.example.org,node2.example.org,node3.example.org'
- '--master'
- cibname: cib_for_galera | [
"Ensure",
"that",
"a",
"resource",
"is",
"created"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L984-L1021 | train |
saltstack/salt | salt/states/pcs.py | constraint_present | def constraint_present(name, constraint_id, constraint_type, constraint_options=None, cibname=None):
'''
Ensure that a constraint is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: {{formulaname}}__constraint_present_{{constraint_id}})
constraint_id
name for the constraint (try first to create manually to find out the autocreated name)
constraint_type
constraint type (location, colocation, order)
constraint_options
options for creating the constraint
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
haproxy_pcs__constraint_present_colocation-vip_galera-haproxy-clone-INFINITY:
pcs.constraint_present:
- constraint_id: colocation-vip_galera-haproxy-clone-INFINITY
- constraint_type: colocation
- constraint_options:
- 'add'
- 'vip_galera'
- 'with'
- 'haproxy-clone'
- cibname: cib_for_haproxy
'''
return _item_present(name=name,
item='constraint',
item_id=constraint_id,
item_type=constraint_type,
create=None,
extra_args=constraint_options,
cibname=cibname) | python | def constraint_present(name, constraint_id, constraint_type, constraint_options=None, cibname=None):
'''
Ensure that a constraint is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: {{formulaname}}__constraint_present_{{constraint_id}})
constraint_id
name for the constraint (try first to create manually to find out the autocreated name)
constraint_type
constraint type (location, colocation, order)
constraint_options
options for creating the constraint
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
haproxy_pcs__constraint_present_colocation-vip_galera-haproxy-clone-INFINITY:
pcs.constraint_present:
- constraint_id: colocation-vip_galera-haproxy-clone-INFINITY
- constraint_type: colocation
- constraint_options:
- 'add'
- 'vip_galera'
- 'with'
- 'haproxy-clone'
- cibname: cib_for_haproxy
'''
return _item_present(name=name,
item='constraint',
item_id=constraint_id,
item_type=constraint_type,
create=None,
extra_args=constraint_options,
cibname=cibname) | [
"def",
"constraint_present",
"(",
"name",
",",
"constraint_id",
",",
"constraint_type",
",",
"constraint_options",
"=",
"None",
",",
"cibname",
"=",
"None",
")",
":",
"return",
"_item_present",
"(",
"name",
"=",
"name",
",",
"item",
"=",
"'constraint'",
",",
... | Ensure that a constraint is created
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
Irrelevant, not used (recommended: {{formulaname}}__constraint_present_{{constraint_id}})
constraint_id
name for the constraint (try first to create manually to find out the autocreated name)
constraint_type
constraint type (location, colocation, order)
constraint_options
options for creating the constraint
cibname
use a cached CIB-file named like cibname instead of the live CIB
Example:
.. code-block:: yaml
haproxy_pcs__constraint_present_colocation-vip_galera-haproxy-clone-INFINITY:
pcs.constraint_present:
- constraint_id: colocation-vip_galera-haproxy-clone-INFINITY
- constraint_type: colocation
- constraint_options:
- 'add'
- 'vip_galera'
- 'with'
- 'haproxy-clone'
- cibname: cib_for_haproxy | [
"Ensure",
"that",
"a",
"constraint",
"is",
"created"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pcs.py#L1024-L1064 | train |
saltstack/salt | salt/pillar/makostack.py | _parse_top_cfg | def _parse_top_cfg(content, filename):
'''
Allow top_cfg to be YAML
'''
try:
obj = salt.utils.yaml.safe_load(content)
if isinstance(obj, list):
log.debug('MakoStack cfg `%s` parsed as YAML', filename)
return obj
except Exception as err:
pass
log.debug('MakoStack cfg `%s` parsed as plain text', filename)
return content.splitlines() | python | def _parse_top_cfg(content, filename):
'''
Allow top_cfg to be YAML
'''
try:
obj = salt.utils.yaml.safe_load(content)
if isinstance(obj, list):
log.debug('MakoStack cfg `%s` parsed as YAML', filename)
return obj
except Exception as err:
pass
log.debug('MakoStack cfg `%s` parsed as plain text', filename)
return content.splitlines() | [
"def",
"_parse_top_cfg",
"(",
"content",
",",
"filename",
")",
":",
"try",
":",
"obj",
"=",
"salt",
".",
"utils",
".",
"yaml",
".",
"safe_load",
"(",
"content",
")",
"if",
"isinstance",
"(",
"obj",
",",
"list",
")",
":",
"log",
".",
"debug",
"(",
"... | Allow top_cfg to be YAML | [
"Allow",
"top_cfg",
"to",
"be",
"YAML"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/makostack.py#L564-L576 | train |
saltstack/salt | salt/modules/freebsdjail.py | is_enabled | def is_enabled():
'''
See if jail service is actually enabled on boot
CLI Example:
.. code-block:: bash
salt '*' jail.is_enabled <jail name>
'''
cmd = 'service -e'
services = __salt__['cmd.run'](cmd, python_shell=False)
for service in services.split('\\n'):
if re.search('jail', service):
return True
return False | python | def is_enabled():
'''
See if jail service is actually enabled on boot
CLI Example:
.. code-block:: bash
salt '*' jail.is_enabled <jail name>
'''
cmd = 'service -e'
services = __salt__['cmd.run'](cmd, python_shell=False)
for service in services.split('\\n'):
if re.search('jail', service):
return True
return False | [
"def",
"is_enabled",
"(",
")",
":",
"cmd",
"=",
"'service -e'",
"services",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"for",
"service",
"in",
"services",
".",
"split",
"(",
"'\\\\n'",
")",
":",
"if",
"r... | See if jail service is actually enabled on boot
CLI Example:
.. code-block:: bash
salt '*' jail.is_enabled <jail name> | [
"See",
"if",
"jail",
"service",
"is",
"actually",
"enabled",
"on",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdjail.py#L73-L88 | train |
saltstack/salt | salt/modules/freebsdjail.py | get_enabled | def get_enabled():
'''
Return which jails are set to be run
CLI Example:
.. code-block:: bash
salt '*' jail.get_enabled
'''
ret = []
for rconf in ('/etc/rc.conf', '/etc/rc.conf.local'):
if os.access(rconf, os.R_OK):
with salt.utils.files.fopen(rconf, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if not line.strip():
continue
if not line.startswith('jail_list='):
continue
jails = line.split('"')[1].split()
for j in jails:
ret.append(j)
return ret | python | def get_enabled():
'''
Return which jails are set to be run
CLI Example:
.. code-block:: bash
salt '*' jail.get_enabled
'''
ret = []
for rconf in ('/etc/rc.conf', '/etc/rc.conf.local'):
if os.access(rconf, os.R_OK):
with salt.utils.files.fopen(rconf, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if not line.strip():
continue
if not line.startswith('jail_list='):
continue
jails = line.split('"')[1].split()
for j in jails:
ret.append(j)
return ret | [
"def",
"get_enabled",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"rconf",
"in",
"(",
"'/etc/rc.conf'",
",",
"'/etc/rc.conf.local'",
")",
":",
"if",
"os",
".",
"access",
"(",
"rconf",
",",
"os",
".",
"R_OK",
")",
":",
"with",
"salt",
".",
"utils",
... | Return which jails are set to be run
CLI Example:
.. code-block:: bash
salt '*' jail.get_enabled | [
"Return",
"which",
"jails",
"are",
"set",
"to",
"be",
"run"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdjail.py#L91-L114 | train |
saltstack/salt | salt/modules/freebsdjail.py | show_config | def show_config(jail):
'''
Display specified jail's configuration
CLI Example:
.. code-block:: bash
salt '*' jail.show_config <jail name>
'''
ret = {}
if subprocess.call(["jls", "-nq", "-j", jail]) == 0:
jls = subprocess.check_output(["jls", "-nq", "-j", jail]) # pylint: disable=minimum-python-version
jailopts = salt.utils.args.shlex_split(salt.utils.stringutils.to_unicode(jls))
for jailopt in jailopts:
if '=' not in jailopt:
ret[jailopt.strip().rstrip(";")] = '1'
else:
key = jailopt.split('=')[0].strip()
value = jailopt.split('=')[-1].strip().strip("\"")
ret[key] = value
else:
for rconf in ('/etc/rc.conf', '/etc/rc.conf.local'):
if os.access(rconf, os.R_OK):
with salt.utils.files.fopen(rconf, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if not line.strip():
continue
if not line.startswith('jail_{0}_'.format(jail)):
continue
key, value = line.split('=')
ret[key.split('_', 2)[2]] = value.split('"')[1]
for jconf in ('/etc/jail.conf', '/usr/local/etc/jail.conf'):
if os.access(jconf, os.R_OK):
with salt.utils.files.fopen(jconf, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
line = line.partition('#')[0].strip()
if line:
if line.split()[-1] == '{':
if line.split()[0] != jail and line.split()[0] != '*':
while line.split()[-1] != '}':
line = next(_fp)
line = line.partition('#')[0].strip()
else:
continue
if line.split()[-1] == '}':
continue
if '=' not in line:
ret[line.strip().rstrip(";")] = '1'
else:
key = line.split('=')[0].strip()
value = line.split('=')[-1].strip().strip(";'\"")
ret[key] = value
return ret | python | def show_config(jail):
'''
Display specified jail's configuration
CLI Example:
.. code-block:: bash
salt '*' jail.show_config <jail name>
'''
ret = {}
if subprocess.call(["jls", "-nq", "-j", jail]) == 0:
jls = subprocess.check_output(["jls", "-nq", "-j", jail]) # pylint: disable=minimum-python-version
jailopts = salt.utils.args.shlex_split(salt.utils.stringutils.to_unicode(jls))
for jailopt in jailopts:
if '=' not in jailopt:
ret[jailopt.strip().rstrip(";")] = '1'
else:
key = jailopt.split('=')[0].strip()
value = jailopt.split('=')[-1].strip().strip("\"")
ret[key] = value
else:
for rconf in ('/etc/rc.conf', '/etc/rc.conf.local'):
if os.access(rconf, os.R_OK):
with salt.utils.files.fopen(rconf, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if not line.strip():
continue
if not line.startswith('jail_{0}_'.format(jail)):
continue
key, value = line.split('=')
ret[key.split('_', 2)[2]] = value.split('"')[1]
for jconf in ('/etc/jail.conf', '/usr/local/etc/jail.conf'):
if os.access(jconf, os.R_OK):
with salt.utils.files.fopen(jconf, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
line = line.partition('#')[0].strip()
if line:
if line.split()[-1] == '{':
if line.split()[0] != jail and line.split()[0] != '*':
while line.split()[-1] != '}':
line = next(_fp)
line = line.partition('#')[0].strip()
else:
continue
if line.split()[-1] == '}':
continue
if '=' not in line:
ret[line.strip().rstrip(";")] = '1'
else:
key = line.split('=')[0].strip()
value = line.split('=')[-1].strip().strip(";'\"")
ret[key] = value
return ret | [
"def",
"show_config",
"(",
"jail",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"subprocess",
".",
"call",
"(",
"[",
"\"jls\"",
",",
"\"-nq\"",
",",
"\"-j\"",
",",
"jail",
"]",
")",
"==",
"0",
":",
"jls",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
... | Display specified jail's configuration
CLI Example:
.. code-block:: bash
salt '*' jail.show_config <jail name> | [
"Display",
"specified",
"jail",
"s",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdjail.py#L117-L172 | train |
saltstack/salt | salt/modules/freebsdjail.py | fstab | def fstab(jail):
'''
Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name>
'''
ret = []
config = show_config(jail)
if 'fstab' in config:
c_fstab = config['fstab']
elif 'mount.fstab' in config:
c_fstab = config['mount.fstab']
if 'fstab' in config or 'mount.fstab' in config:
if os.access(c_fstab, os.R_OK):
with salt.utils.files.fopen(c_fstab, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
line = line.strip()
if not line:
continue
if line.startswith('#'):
continue
try:
device, mpoint, fstype, opts, dump, pas_ = line.split()
except ValueError:
# Gracefully continue on invalid lines
continue
ret.append({
'device': device,
'mountpoint': mpoint,
'fstype': fstype,
'options': opts,
'dump': dump,
'pass': pas_
})
if not ret:
ret = False
return ret | python | def fstab(jail):
'''
Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name>
'''
ret = []
config = show_config(jail)
if 'fstab' in config:
c_fstab = config['fstab']
elif 'mount.fstab' in config:
c_fstab = config['mount.fstab']
if 'fstab' in config or 'mount.fstab' in config:
if os.access(c_fstab, os.R_OK):
with salt.utils.files.fopen(c_fstab, 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
line = line.strip()
if not line:
continue
if line.startswith('#'):
continue
try:
device, mpoint, fstype, opts, dump, pas_ = line.split()
except ValueError:
# Gracefully continue on invalid lines
continue
ret.append({
'device': device,
'mountpoint': mpoint,
'fstype': fstype,
'options': opts,
'dump': dump,
'pass': pas_
})
if not ret:
ret = False
return ret | [
"def",
"fstab",
"(",
"jail",
")",
":",
"ret",
"=",
"[",
"]",
"config",
"=",
"show_config",
"(",
"jail",
")",
"if",
"'fstab'",
"in",
"config",
":",
"c_fstab",
"=",
"config",
"[",
"'fstab'",
"]",
"elif",
"'mount.fstab'",
"in",
"config",
":",
"c_fstab",
... | Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name> | [
"Display",
"contents",
"of",
"a",
"fstab",
"(",
"5",
")",
"file",
"defined",
"in",
"specified",
"jail",
"s",
"configuration",
".",
"If",
"no",
"file",
"is",
"defined",
"return",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdjail.py#L175-L217 | train |
saltstack/salt | salt/modules/freebsdjail.py | status | def status(jail):
'''
See if specified jail is currently running
CLI Example:
.. code-block:: bash
salt '*' jail.status <jail name>
'''
cmd = 'jls'
found_jails = __salt__['cmd.run'](cmd, python_shell=False)
for found_jail in found_jails.split('\\n'):
if re.search(jail, found_jail):
return True
return False | python | def status(jail):
'''
See if specified jail is currently running
CLI Example:
.. code-block:: bash
salt '*' jail.status <jail name>
'''
cmd = 'jls'
found_jails = __salt__['cmd.run'](cmd, python_shell=False)
for found_jail in found_jails.split('\\n'):
if re.search(jail, found_jail):
return True
return False | [
"def",
"status",
"(",
"jail",
")",
":",
"cmd",
"=",
"'jls'",
"found_jails",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
"for",
"found_jail",
"in",
"found_jails",
".",
"split",
"(",
"'\\\\n'",
")",
":",
"i... | See if specified jail is currently running
CLI Example:
.. code-block:: bash
salt '*' jail.status <jail name> | [
"See",
"if",
"specified",
"jail",
"is",
"currently",
"running"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdjail.py#L220-L235 | train |
saltstack/salt | salt/modules/freebsdjail.py | sysctl | def sysctl():
'''
Dump all jail related kernel states (sysctl)
CLI Example:
.. code-block:: bash
salt '*' jail.sysctl
'''
ret = {}
sysctl_jail = __salt__['cmd.run']('sysctl security.jail')
for line in sysctl_jail.splitlines():
key, value = line.split(':', 1)
ret[key.strip()] = value.strip()
return ret | python | def sysctl():
'''
Dump all jail related kernel states (sysctl)
CLI Example:
.. code-block:: bash
salt '*' jail.sysctl
'''
ret = {}
sysctl_jail = __salt__['cmd.run']('sysctl security.jail')
for line in sysctl_jail.splitlines():
key, value = line.split(':', 1)
ret[key.strip()] = value.strip()
return ret | [
"def",
"sysctl",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"sysctl_jail",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'sysctl security.jail'",
")",
"for",
"line",
"in",
"sysctl_jail",
".",
"splitlines",
"(",
")",
":",
"key",
",",
"value",
"=",
"line",
"."... | Dump all jail related kernel states (sysctl)
CLI Example:
.. code-block:: bash
salt '*' jail.sysctl | [
"Dump",
"all",
"jail",
"related",
"kernel",
"states",
"(",
"sysctl",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsdjail.py#L238-L253 | train |
saltstack/salt | salt/modules/pecl.py | _pecl | def _pecl(command, defaults=False):
'''
Execute the command passed with pecl
'''
cmdline = 'pecl {0}'.format(command)
if salt.utils.data.is_true(defaults):
cmdline = 'yes ' "''" + ' | ' + cmdline
ret = __salt__['cmd.run_all'](cmdline, python_shell=True)
if ret['retcode'] == 0:
return ret['stdout']
else:
log.error('Problem running pecl. Is php-pear installed?')
return '' | python | def _pecl(command, defaults=False):
'''
Execute the command passed with pecl
'''
cmdline = 'pecl {0}'.format(command)
if salt.utils.data.is_true(defaults):
cmdline = 'yes ' "''" + ' | ' + cmdline
ret = __salt__['cmd.run_all'](cmdline, python_shell=True)
if ret['retcode'] == 0:
return ret['stdout']
else:
log.error('Problem running pecl. Is php-pear installed?')
return '' | [
"def",
"_pecl",
"(",
"command",
",",
"defaults",
"=",
"False",
")",
":",
"cmdline",
"=",
"'pecl {0}'",
".",
"format",
"(",
"command",
")",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"defaults",
")",
":",
"cmdline",
"=",
"'yes '",
"... | Execute the command passed with pecl | [
"Execute",
"the",
"command",
"passed",
"with",
"pecl"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pecl.py#L40-L54 | train |
saltstack/salt | salt/modules/pecl.py | install | def install(pecls, defaults=False, force=False, preferred_state='stable'):
'''
.. versionadded:: 0.17.0
Installs one or several pecl extensions.
pecls
The pecl extensions to install.
defaults
Use default answers for extensions such as pecl_http which ask
questions before installation. Without this option, the pecl.installed
state will hang indefinitely when trying to install these extensions.
force
Whether to force the installed version or not
CLI Example:
.. code-block:: bash
salt '*' pecl.install fuse
'''
if isinstance(pecls, six.string_types):
pecls = [pecls]
preferred_state = '-d preferred_state={0}'.format(_cmd_quote(preferred_state))
if force:
return _pecl('{0} install -f {1}'.format(preferred_state, _cmd_quote(' '.join(pecls))),
defaults=defaults)
else:
_pecl('{0} install {1}'.format(preferred_state, _cmd_quote(' '.join(pecls))),
defaults=defaults)
if not isinstance(pecls, list):
pecls = [pecls]
for pecl in pecls:
found = False
if '/' in pecl:
channel, pecl = pecl.split('/')
else:
channel = None
installed_pecls = list_(channel)
for pecl in installed_pecls:
installed_pecl_with_version = '{0}-{1}'.format(
pecl,
installed_pecls.get(pecl)[0]
)
if pecl in installed_pecl_with_version:
found = True
if not found:
return False
return True | python | def install(pecls, defaults=False, force=False, preferred_state='stable'):
'''
.. versionadded:: 0.17.0
Installs one or several pecl extensions.
pecls
The pecl extensions to install.
defaults
Use default answers for extensions such as pecl_http which ask
questions before installation. Without this option, the pecl.installed
state will hang indefinitely when trying to install these extensions.
force
Whether to force the installed version or not
CLI Example:
.. code-block:: bash
salt '*' pecl.install fuse
'''
if isinstance(pecls, six.string_types):
pecls = [pecls]
preferred_state = '-d preferred_state={0}'.format(_cmd_quote(preferred_state))
if force:
return _pecl('{0} install -f {1}'.format(preferred_state, _cmd_quote(' '.join(pecls))),
defaults=defaults)
else:
_pecl('{0} install {1}'.format(preferred_state, _cmd_quote(' '.join(pecls))),
defaults=defaults)
if not isinstance(pecls, list):
pecls = [pecls]
for pecl in pecls:
found = False
if '/' in pecl:
channel, pecl = pecl.split('/')
else:
channel = None
installed_pecls = list_(channel)
for pecl in installed_pecls:
installed_pecl_with_version = '{0}-{1}'.format(
pecl,
installed_pecls.get(pecl)[0]
)
if pecl in installed_pecl_with_version:
found = True
if not found:
return False
return True | [
"def",
"install",
"(",
"pecls",
",",
"defaults",
"=",
"False",
",",
"force",
"=",
"False",
",",
"preferred_state",
"=",
"'stable'",
")",
":",
"if",
"isinstance",
"(",
"pecls",
",",
"six",
".",
"string_types",
")",
":",
"pecls",
"=",
"[",
"pecls",
"]",
... | .. versionadded:: 0.17.0
Installs one or several pecl extensions.
pecls
The pecl extensions to install.
defaults
Use default answers for extensions such as pecl_http which ask
questions before installation. Without this option, the pecl.installed
state will hang indefinitely when trying to install these extensions.
force
Whether to force the installed version or not
CLI Example:
.. code-block:: bash
salt '*' pecl.install fuse | [
"..",
"versionadded",
"::",
"0",
".",
"17",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pecl.py#L57-L107 | train |
saltstack/salt | salt/modules/pecl.py | uninstall | def uninstall(pecls):
'''
Uninstall one or several pecl extensions.
pecls
The pecl extensions to uninstall.
CLI Example:
.. code-block:: bash
salt '*' pecl.uninstall fuse
'''
if isinstance(pecls, six.string_types):
pecls = [pecls]
return _pecl('uninstall {0}'.format(_cmd_quote(' '.join(pecls)))) | python | def uninstall(pecls):
'''
Uninstall one or several pecl extensions.
pecls
The pecl extensions to uninstall.
CLI Example:
.. code-block:: bash
salt '*' pecl.uninstall fuse
'''
if isinstance(pecls, six.string_types):
pecls = [pecls]
return _pecl('uninstall {0}'.format(_cmd_quote(' '.join(pecls)))) | [
"def",
"uninstall",
"(",
"pecls",
")",
":",
"if",
"isinstance",
"(",
"pecls",
",",
"six",
".",
"string_types",
")",
":",
"pecls",
"=",
"[",
"pecls",
"]",
"return",
"_pecl",
"(",
"'uninstall {0}'",
".",
"format",
"(",
"_cmd_quote",
"(",
"' '",
".",
"joi... | Uninstall one or several pecl extensions.
pecls
The pecl extensions to uninstall.
CLI Example:
.. code-block:: bash
salt '*' pecl.uninstall fuse | [
"Uninstall",
"one",
"or",
"several",
"pecl",
"extensions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pecl.py#L110-L125 | train |
saltstack/salt | salt/modules/pecl.py | list_ | def list_(channel=None):
'''
List installed pecl extensions.
CLI Example:
.. code-block:: bash
salt '*' pecl.list
'''
pecl_channel_pat = re.compile('^([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)')
pecls = {}
command = 'list'
if channel:
command = '{0} -c {1}'.format(command, _cmd_quote(channel))
lines = _pecl(command).splitlines()
lines = (l for l in lines if pecl_channel_pat.match(l))
for line in lines:
match = pecl_channel_pat.match(line)
if match:
pecls[match.group(1)] = [match.group(2), match.group(3)]
return pecls | python | def list_(channel=None):
'''
List installed pecl extensions.
CLI Example:
.. code-block:: bash
salt '*' pecl.list
'''
pecl_channel_pat = re.compile('^([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)')
pecls = {}
command = 'list'
if channel:
command = '{0} -c {1}'.format(command, _cmd_quote(channel))
lines = _pecl(command).splitlines()
lines = (l for l in lines if pecl_channel_pat.match(l))
for line in lines:
match = pecl_channel_pat.match(line)
if match:
pecls[match.group(1)] = [match.group(2), match.group(3)]
return pecls | [
"def",
"list_",
"(",
"channel",
"=",
"None",
")",
":",
"pecl_channel_pat",
"=",
"re",
".",
"compile",
"(",
"'^([^ ]+)[ ]+([^ ]+)[ ]+([^ ]+)'",
")",
"pecls",
"=",
"{",
"}",
"command",
"=",
"'list'",
"if",
"channel",
":",
"command",
"=",
"'{0} -c {1}'",
".",
... | List installed pecl extensions.
CLI Example:
.. code-block:: bash
salt '*' pecl.list | [
"List",
"installed",
"pecl",
"extensions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pecl.py#L146-L169 | train |
saltstack/salt | salt/runners/cloud.py | _get_client | def _get_client():
'''
Return cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud')
)
return client | python | def _get_client():
'''
Return cloud client
'''
client = salt.cloud.CloudClient(
os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud')
)
return client | [
"def",
"_get_client",
"(",
")",
":",
"client",
"=",
"salt",
".",
"cloud",
".",
"CloudClient",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
",",
"'cloud'",
")",
")",
"ret... | Return cloud client | [
"Return",
"cloud",
"client"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L24-L31 | train |
saltstack/salt | salt/runners/cloud.py | profile | def profile(prof=None, instances=None, opts=None, **kwargs):
'''
Create a cloud vm with the given profile and instances, instances can be a
list or comma-delimited string
CLI Example:
.. code-block:: bash
salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3
'''
if prof is None and 'profile' in kwargs:
prof = kwargs['profile']
if prof is None:
return {'Error': 'A profile (or prof) must be defined'}
if instances is None and 'names' in kwargs:
instances = kwargs['names']
if instances is None:
return {'Error': 'One or more instances (comma-delimited) must be set'}
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(prof, instances, **salt.utils.args.clean_kwargs(**kwargs))
return info | python | def profile(prof=None, instances=None, opts=None, **kwargs):
'''
Create a cloud vm with the given profile and instances, instances can be a
list or comma-delimited string
CLI Example:
.. code-block:: bash
salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3
'''
if prof is None and 'profile' in kwargs:
prof = kwargs['profile']
if prof is None:
return {'Error': 'A profile (or prof) must be defined'}
if instances is None and 'names' in kwargs:
instances = kwargs['names']
if instances is None:
return {'Error': 'One or more instances (comma-delimited) must be set'}
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.profile(prof, instances, **salt.utils.args.clean_kwargs(**kwargs))
return info | [
"def",
"profile",
"(",
"prof",
"=",
"None",
",",
"instances",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"prof",
"is",
"None",
"and",
"'profile'",
"in",
"kwargs",
":",
"prof",
"=",
"kwargs",
"[",
"'profile'",
"]... | Create a cloud vm with the given profile and instances, instances can be a
list or comma-delimited string
CLI Example:
.. code-block:: bash
salt-run cloud.profile prof=my-ec2 instances=node1,node2,node3 | [
"Create",
"a",
"cloud",
"vm",
"with",
"the",
"given",
"profile",
"and",
"instances",
"instances",
"can",
"be",
"a",
"list",
"or",
"comma",
"-",
"delimited",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L88-L115 | train |
saltstack/salt | salt/runners/cloud.py | map_run | def map_run(path=None, opts=None, **kwargs):
'''
Execute a salt cloud map file
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.map_run(path, **salt.utils.args.clean_kwargs(**kwargs))
return info | python | def map_run(path=None, opts=None, **kwargs):
'''
Execute a salt cloud map file
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.map_run(path, **salt.utils.args.clean_kwargs(**kwargs))
return info | [
"def",
"map_run",
"(",
"path",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"client",
".",
"opts",
".",
"update",
"(",
"o... | Execute a salt cloud map file | [
"Execute",
"a",
"salt",
"cloud",
"map",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L118-L126 | train |
saltstack/salt | salt/runners/cloud.py | destroy | def destroy(instances, opts=None):
'''
Destroy the named vm(s)
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.destroy(instances)
return info | python | def destroy(instances, opts=None):
'''
Destroy the named vm(s)
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.destroy(instances)
return info | [
"def",
"destroy",
"(",
"instances",
",",
"opts",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"client",
".",
"opts",
".",
"update",
"(",
"opts",
")",
"info",
"=",
"client",
"... | Destroy the named vm(s) | [
"Destroy",
"the",
"named",
"vm",
"(",
"s",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L129-L137 | train |
saltstack/salt | salt/runners/cloud.py | action | def action(func=None,
cloudmap=None,
instances=None,
provider=None,
instance=None,
opts=None,
**kwargs):
'''
Execute a single action on the given map/provider/instance
CLI Example:
.. code-block:: bash
salt-run cloud.action start my-salt-vm
'''
info = {}
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
try:
info = client.action(
func,
cloudmap,
instances,
provider,
instance,
salt.utils.args.clean_kwargs(**kwargs)
)
except SaltCloudConfigError as err:
log.error(err)
return info | python | def action(func=None,
cloudmap=None,
instances=None,
provider=None,
instance=None,
opts=None,
**kwargs):
'''
Execute a single action on the given map/provider/instance
CLI Example:
.. code-block:: bash
salt-run cloud.action start my-salt-vm
'''
info = {}
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
try:
info = client.action(
func,
cloudmap,
instances,
provider,
instance,
salt.utils.args.clean_kwargs(**kwargs)
)
except SaltCloudConfigError as err:
log.error(err)
return info | [
"def",
"action",
"(",
"func",
"=",
"None",
",",
"cloudmap",
"=",
"None",
",",
"instances",
"=",
"None",
",",
"provider",
"=",
"None",
",",
"instance",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"info",
"=",
"{",
"}"... | Execute a single action on the given map/provider/instance
CLI Example:
.. code-block:: bash
salt-run cloud.action start my-salt-vm | [
"Execute",
"a",
"single",
"action",
"on",
"the",
"given",
"map",
"/",
"provider",
"/",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L140-L171 | train |
saltstack/salt | salt/runners/cloud.py | create | def create(provider, instances, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt-run cloud.create my-ec2-config myinstance \
image=ami-1624987f size='t1.micro' ssh_username=ec2-user \
securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, instances, **salt.utils.args.clean_kwargs(**kwargs))
return info | python | def create(provider, instances, opts=None, **kwargs):
'''
Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt-run cloud.create my-ec2-config myinstance \
image=ami-1624987f size='t1.micro' ssh_username=ec2-user \
securitygroup=default delvol_on_destroy=True
'''
client = _get_client()
if isinstance(opts, dict):
client.opts.update(opts)
info = client.create(provider, instances, **salt.utils.args.clean_kwargs(**kwargs))
return info | [
"def",
"create",
"(",
"provider",
",",
"instances",
",",
"opts",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"if",
"isinstance",
"(",
"opts",
",",
"dict",
")",
":",
"client",
".",
"opts",
".",
"update",
"... | Create an instance using Salt Cloud
CLI Example:
.. code-block:: bash
salt-run cloud.create my-ec2-config myinstance \
image=ami-1624987f size='t1.micro' ssh_username=ec2-user \
securitygroup=default delvol_on_destroy=True | [
"Create",
"an",
"instance",
"using",
"Salt",
"Cloud"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/cloud.py#L174-L190 | train |
saltstack/salt | salt/modules/splunk_search.py | _get_splunk_search_props | def _get_splunk_search_props(search):
'''
Get splunk search properties from an object
'''
props = search.content
props["app"] = search.access.app
props["sharing"] = search.access.sharing
return props | python | def _get_splunk_search_props(search):
'''
Get splunk search properties from an object
'''
props = search.content
props["app"] = search.access.app
props["sharing"] = search.access.sharing
return props | [
"def",
"_get_splunk_search_props",
"(",
"search",
")",
":",
"props",
"=",
"search",
".",
"content",
"props",
"[",
"\"app\"",
"]",
"=",
"search",
".",
"access",
".",
"app",
"props",
"[",
"\"sharing\"",
"]",
"=",
"search",
".",
"access",
".",
"sharing",
"r... | Get splunk search properties from an object | [
"Get",
"splunk",
"search",
"properties",
"from",
"an",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L82-L89 | train |
saltstack/salt | salt/modules/splunk_search.py | get | def get(name, profile="splunk"):
'''
Get a splunk search
CLI Example:
splunk_search.get 'my search name'
'''
client = _get_splunk(profile)
search = None
# uglyness of splunk lib
try:
search = client.saved_searches[name]
except KeyError:
pass
return search | python | def get(name, profile="splunk"):
'''
Get a splunk search
CLI Example:
splunk_search.get 'my search name'
'''
client = _get_splunk(profile)
search = None
# uglyness of splunk lib
try:
search = client.saved_searches[name]
except KeyError:
pass
return search | [
"def",
"get",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"search",
"=",
"None",
"# uglyness of splunk lib",
"try",
":",
"search",
"=",
"client",
".",
"saved_searches",
"[",
"name",
"]",
"exc... | Get a splunk search
CLI Example:
splunk_search.get 'my search name' | [
"Get",
"a",
"splunk",
"search"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L92-L107 | train |
saltstack/salt | salt/modules/splunk_search.py | update | def update(name, profile="splunk", **kwargs):
'''
Update a splunk search
CLI Example:
splunk_search.update 'my search name' sharing=app
'''
client = _get_splunk(profile)
search = client.saved_searches[name]
props = _get_splunk_search_props(search)
updates = kwargs
update_needed = False
update_set = dict()
diffs = []
for key in sorted(kwargs):
old_value = props.get(key, None)
new_value = updates.get(key, None)
if isinstance(old_value, six.string_types):
old_value = old_value.strip()
if isinstance(new_value, six.string_types):
new_value = new_value.strip()
if old_value != new_value:
update_set[key] = new_value
update_needed = True
diffs.append("{0}: '{1}' => '{2}'".format(
key, old_value, new_value
))
if update_needed:
search.update(**update_set).refresh()
return update_set, diffs
return False | python | def update(name, profile="splunk", **kwargs):
'''
Update a splunk search
CLI Example:
splunk_search.update 'my search name' sharing=app
'''
client = _get_splunk(profile)
search = client.saved_searches[name]
props = _get_splunk_search_props(search)
updates = kwargs
update_needed = False
update_set = dict()
diffs = []
for key in sorted(kwargs):
old_value = props.get(key, None)
new_value = updates.get(key, None)
if isinstance(old_value, six.string_types):
old_value = old_value.strip()
if isinstance(new_value, six.string_types):
new_value = new_value.strip()
if old_value != new_value:
update_set[key] = new_value
update_needed = True
diffs.append("{0}: '{1}' => '{2}'".format(
key, old_value, new_value
))
if update_needed:
search.update(**update_set).refresh()
return update_set, diffs
return False | [
"def",
"update",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"search",
"=",
"client",
".",
"saved_searches",
"[",
"name",
"]",
"props",
"=",
"_get_splunk_search_props... | Update a splunk search
CLI Example:
splunk_search.update 'my search name' sharing=app | [
"Update",
"a",
"splunk",
"search"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L110-L141 | train |
saltstack/salt | salt/modules/splunk_search.py | create | def create(name, profile="splunk", **kwargs):
'''
Create a splunk search
CLI Example:
splunk_search.create 'my search name' search='error msg'
'''
client = _get_splunk(profile)
search = client.saved_searches.create(name, **kwargs)
# use the REST API to set owner and permissions
# this is hard-coded for now; all managed searches are app scope and
# readable by all
config = __salt__['config.option'](profile)
url = "https://{0}:{1}".format(config.get('host'), config.get('port'))
auth = (config.get('username'), config.get('password'))
data = {
"owner": config.get("username"),
"sharing": "app",
"perms.read": "*",
}
_req_url = "{0}/servicesNS/{1}/search/saved/searches/{2}/acl".format(
url, config.get("username"), urllib.quote(name)
)
requests.post(_req_url, auth=auth, verify=True, data=data)
return _get_splunk_search_props(search) | python | def create(name, profile="splunk", **kwargs):
'''
Create a splunk search
CLI Example:
splunk_search.create 'my search name' search='error msg'
'''
client = _get_splunk(profile)
search = client.saved_searches.create(name, **kwargs)
# use the REST API to set owner and permissions
# this is hard-coded for now; all managed searches are app scope and
# readable by all
config = __salt__['config.option'](profile)
url = "https://{0}:{1}".format(config.get('host'), config.get('port'))
auth = (config.get('username'), config.get('password'))
data = {
"owner": config.get("username"),
"sharing": "app",
"perms.read": "*",
}
_req_url = "{0}/servicesNS/{1}/search/saved/searches/{2}/acl".format(
url, config.get("username"), urllib.quote(name)
)
requests.post(_req_url, auth=auth, verify=True, data=data)
return _get_splunk_search_props(search) | [
"def",
"create",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"search",
"=",
"client",
".",
"saved_searches",
".",
"create",
"(",
"name",
",",
"*",
"*",
"kwargs",
... | Create a splunk search
CLI Example:
splunk_search.create 'my search name' search='error msg' | [
"Create",
"a",
"splunk",
"search"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L144-L170 | train |
saltstack/salt | salt/modules/splunk_search.py | delete | def delete(name, profile="splunk"):
'''
Delete a splunk search
CLI Example:
splunk_search.delete 'my search name'
'''
client = _get_splunk(profile)
try:
client.saved_searches.delete(name)
return True
except KeyError:
return None | python | def delete(name, profile="splunk"):
'''
Delete a splunk search
CLI Example:
splunk_search.delete 'my search name'
'''
client = _get_splunk(profile)
try:
client.saved_searches.delete(name)
return True
except KeyError:
return None | [
"def",
"delete",
"(",
"name",
",",
"profile",
"=",
"\"splunk\"",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"try",
":",
"client",
".",
"saved_searches",
".",
"delete",
"(",
"name",
")",
"return",
"True",
"except",
"KeyError",
":",
"retu... | Delete a splunk search
CLI Example:
splunk_search.delete 'my search name' | [
"Delete",
"a",
"splunk",
"search"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L173-L186 | train |
saltstack/salt | salt/modules/splunk_search.py | list_ | def list_(profile="splunk"):
'''
List splunk searches (names only)
CLI Example:
splunk_search.list
'''
client = _get_splunk(profile)
searches = [x['name'] for x in client.saved_searches]
return searches | python | def list_(profile="splunk"):
'''
List splunk searches (names only)
CLI Example:
splunk_search.list
'''
client = _get_splunk(profile)
searches = [x['name'] for x in client.saved_searches]
return searches | [
"def",
"list_",
"(",
"profile",
"=",
"\"splunk\"",
")",
":",
"client",
"=",
"_get_splunk",
"(",
"profile",
")",
"searches",
"=",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"client",
".",
"saved_searches",
"]",
"return",
"searches"
] | List splunk searches (names only)
CLI Example:
splunk_search.list | [
"List",
"splunk",
"searches",
"(",
"names",
"only",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L189-L198 | train |
saltstack/salt | salt/modules/splunk_search.py | list_all | def list_all(prefix=None, app=None, owner=None, description_contains=None,
name_not_contains=None, profile="splunk"):
'''
Get all splunk search details. Produces results that can be used to create
an sls file.
if app or owner are specified, results will be limited to matching saved
searches.
if description_contains is specified, results will be limited to those
where "description_contains in description" is true if name_not_contains is
specified, results will be limited to those where "name_not_contains not in
name" is true.
If prefix parameter is given, alarm names in the output will be prepended
with the prefix; alarms that have the prefix will be skipped. This can be
used to convert existing alarms to be managed by salt, as follows:
CLI example:
1. Make a "backup" of all existing searches
$ salt-call splunk_search.list_all --out=txt | sed "s/local: //" > legacy_searches.sls
2. Get all searches with new prefixed names
$ salt-call splunk_search.list_all "prefix=**MANAGED BY SALT** " --out=txt | sed "s/local: //" > managed_searches.sls
3. Insert the managed searches into splunk
$ salt-call state.sls managed_searches.sls
4. Manually verify that the new searches look right
5. Delete the original searches
$ sed s/present/absent/ legacy_searches.sls > remove_legacy_searches.sls
$ salt-call state.sls remove_legacy_searches.sls
6. Get all searches again, verify no changes
$ salt-call splunk_search.list_all --out=txt | sed "s/local: //" > final_searches.sls
$ diff final_searches.sls managed_searches.sls
'''
client = _get_splunk(profile)
# splunklib doesn't provide the default settings for saved searches.
# so, in order to get the defaults, we create a search with no
# configuration, get that search, and then delete it. We use its contents
# as the default settings
name = "splunk_search.list_all get defaults"
try:
client.saved_searches.delete(name)
except Exception:
pass
search = client.saved_searches.create(name, search="nothing")
defaults = dict(search.content)
client.saved_searches.delete(name)
# stuff that splunk returns but that you should not attempt to set.
# cf http://dev.splunk.com/view/python-sdk/SP-CAAAEK2
readonly_keys = ("triggered_alert_count",
"action.email",
"action.populate_lookup",
"action.rss",
"action.script",
"action.summary_index",
"qualifiedSearch",
"next_scheduled_time")
results = OrderedDict()
# sort the splunk searches by name, so we get consistent output
searches = sorted([(s.name, s) for s in client.saved_searches])
for name, search in searches:
if app and search.access.app != app:
continue
if owner and search.access.owner != owner:
continue
if name_not_contains and name_not_contains in name:
continue
if prefix:
if name.startswith(prefix):
continue
name = prefix + name
# put name in the OrderedDict first
d = [{"name": name}]
# add the rest of the splunk settings, ignoring any defaults
description = ''
for (k, v) in sorted(search.content.items()):
if k in readonly_keys:
continue
if k.startswith("display."):
continue
if not v:
continue
if k in defaults and defaults[k] == v:
continue
d.append({k: v})
if k == 'description':
description = v
if description_contains and description_contains not in description:
continue
results["manage splunk search " + name] = {"splunk_search.present": d}
return salt.utils.yaml.safe_dump(results, default_flow_style=False, width=120) | python | def list_all(prefix=None, app=None, owner=None, description_contains=None,
name_not_contains=None, profile="splunk"):
'''
Get all splunk search details. Produces results that can be used to create
an sls file.
if app or owner are specified, results will be limited to matching saved
searches.
if description_contains is specified, results will be limited to those
where "description_contains in description" is true if name_not_contains is
specified, results will be limited to those where "name_not_contains not in
name" is true.
If prefix parameter is given, alarm names in the output will be prepended
with the prefix; alarms that have the prefix will be skipped. This can be
used to convert existing alarms to be managed by salt, as follows:
CLI example:
1. Make a "backup" of all existing searches
$ salt-call splunk_search.list_all --out=txt | sed "s/local: //" > legacy_searches.sls
2. Get all searches with new prefixed names
$ salt-call splunk_search.list_all "prefix=**MANAGED BY SALT** " --out=txt | sed "s/local: //" > managed_searches.sls
3. Insert the managed searches into splunk
$ salt-call state.sls managed_searches.sls
4. Manually verify that the new searches look right
5. Delete the original searches
$ sed s/present/absent/ legacy_searches.sls > remove_legacy_searches.sls
$ salt-call state.sls remove_legacy_searches.sls
6. Get all searches again, verify no changes
$ salt-call splunk_search.list_all --out=txt | sed "s/local: //" > final_searches.sls
$ diff final_searches.sls managed_searches.sls
'''
client = _get_splunk(profile)
# splunklib doesn't provide the default settings for saved searches.
# so, in order to get the defaults, we create a search with no
# configuration, get that search, and then delete it. We use its contents
# as the default settings
name = "splunk_search.list_all get defaults"
try:
client.saved_searches.delete(name)
except Exception:
pass
search = client.saved_searches.create(name, search="nothing")
defaults = dict(search.content)
client.saved_searches.delete(name)
# stuff that splunk returns but that you should not attempt to set.
# cf http://dev.splunk.com/view/python-sdk/SP-CAAAEK2
readonly_keys = ("triggered_alert_count",
"action.email",
"action.populate_lookup",
"action.rss",
"action.script",
"action.summary_index",
"qualifiedSearch",
"next_scheduled_time")
results = OrderedDict()
# sort the splunk searches by name, so we get consistent output
searches = sorted([(s.name, s) for s in client.saved_searches])
for name, search in searches:
if app and search.access.app != app:
continue
if owner and search.access.owner != owner:
continue
if name_not_contains and name_not_contains in name:
continue
if prefix:
if name.startswith(prefix):
continue
name = prefix + name
# put name in the OrderedDict first
d = [{"name": name}]
# add the rest of the splunk settings, ignoring any defaults
description = ''
for (k, v) in sorted(search.content.items()):
if k in readonly_keys:
continue
if k.startswith("display."):
continue
if not v:
continue
if k in defaults and defaults[k] == v:
continue
d.append({k: v})
if k == 'description':
description = v
if description_contains and description_contains not in description:
continue
results["manage splunk search " + name] = {"splunk_search.present": d}
return salt.utils.yaml.safe_dump(results, default_flow_style=False, width=120) | [
"def",
"list_all",
"(",
"prefix",
"=",
"None",
",",
"app",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"description_contains",
"=",
"None",
",",
"name_not_contains",
"=",
"None",
",",
"profile",
"=",
"\"splunk\"",
")",
":",
"client",
"=",
"_get_splunk",
... | Get all splunk search details. Produces results that can be used to create
an sls file.
if app or owner are specified, results will be limited to matching saved
searches.
if description_contains is specified, results will be limited to those
where "description_contains in description" is true if name_not_contains is
specified, results will be limited to those where "name_not_contains not in
name" is true.
If prefix parameter is given, alarm names in the output will be prepended
with the prefix; alarms that have the prefix will be skipped. This can be
used to convert existing alarms to be managed by salt, as follows:
CLI example:
1. Make a "backup" of all existing searches
$ salt-call splunk_search.list_all --out=txt | sed "s/local: //" > legacy_searches.sls
2. Get all searches with new prefixed names
$ salt-call splunk_search.list_all "prefix=**MANAGED BY SALT** " --out=txt | sed "s/local: //" > managed_searches.sls
3. Insert the managed searches into splunk
$ salt-call state.sls managed_searches.sls
4. Manually verify that the new searches look right
5. Delete the original searches
$ sed s/present/absent/ legacy_searches.sls > remove_legacy_searches.sls
$ salt-call state.sls remove_legacy_searches.sls
6. Get all searches again, verify no changes
$ salt-call splunk_search.list_all --out=txt | sed "s/local: //" > final_searches.sls
$ diff final_searches.sls managed_searches.sls | [
"Get",
"all",
"splunk",
"search",
"details",
".",
"Produces",
"results",
"that",
"can",
"be",
"used",
"to",
"create",
"an",
"sls",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/splunk_search.py#L201-L300 | train |
saltstack/salt | salt/states/ipset.py | set_present | def set_present(name, set_type, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Verify the set exists.
name
A user-defined set name.
set_type
The type for the set.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check_set'](name)
if set_check is True:
ret['result'] = True
ret['comment'] = ('ipset set {0} already exists for {1}'
.format(name, family))
return ret
if __opts__['test']:
ret['comment'] = 'ipset set {0} would be added for {1}'.format(
name,
family)
return ret
command = __salt__['ipset.new_set'](name, set_type, family, **kwargs)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('ipset set {0} created successfully for {1}'
.format(name, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create set {0} for {2}: {1}'.format(
name,
command.strip(),
family
)
return ret | python | def set_present(name, set_type, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Verify the set exists.
name
A user-defined set name.
set_type
The type for the set.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check_set'](name)
if set_check is True:
ret['result'] = True
ret['comment'] = ('ipset set {0} already exists for {1}'
.format(name, family))
return ret
if __opts__['test']:
ret['comment'] = 'ipset set {0} would be added for {1}'.format(
name,
family)
return ret
command = __salt__['ipset.new_set'](name, set_type, family, **kwargs)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('ipset set {0} created successfully for {1}'
.format(name, family))
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to create set {0} for {2}: {1}'.format(
name,
command.strip(),
family
)
return ret | [
"def",
"set_present",
"(",
"name",
",",
"set_type",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",... | .. versionadded:: 2014.7.0
Verify the set exists.
name
A user-defined set name.
set_type
The type for the set.
family
Networking family, either ipv4 or ipv6 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipset.py#L68-L115 | train |
saltstack/salt | salt/states/ipset.py | set_absent | def set_absent(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Verify the set is absent.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check_set'](name, family)
if not set_check:
ret['result'] = True
ret['comment'] = ('ipset set {0} for {1} is already absent'
.format(name, family))
return ret
if __opts__['test']:
ret['comment'] = 'ipset set {0} for {1} would be removed'.format(
name,
family)
return ret
flush_set = __salt__['ipset.flush'](name, family)
if flush_set:
command = __salt__['ipset.delete_set'](name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('ipset set {0} deleted successfully for family {1}'
.format(name, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete set {0} for {2}: {1}'
.format(name, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush set {0} for {2}: {1}'.format(
name,
flush_set.strip(),
family
)
return ret | python | def set_absent(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Verify the set is absent.
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check_set'](name, family)
if not set_check:
ret['result'] = True
ret['comment'] = ('ipset set {0} for {1} is already absent'
.format(name, family))
return ret
if __opts__['test']:
ret['comment'] = 'ipset set {0} for {1} would be removed'.format(
name,
family)
return ret
flush_set = __salt__['ipset.flush'](name, family)
if flush_set:
command = __salt__['ipset.delete_set'](name, family)
if command is True:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = ('ipset set {0} deleted successfully for family {1}'
.format(name, family))
else:
ret['result'] = False
ret['comment'] = ('Failed to delete set {0} for {2}: {1}'
.format(name, command.strip(), family))
else:
ret['result'] = False
ret['comment'] = 'Failed to flush set {0} for {2}: {1}'.format(
name,
flush_set.strip(),
family
)
return ret | [
"def",
"set_absent",
"(",
"name",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"set_check",... | .. versionadded:: 2014.7.0
Verify the set is absent.
family
Networking family, either ipv4 or ipv6 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipset.py#L118-L163 | train |
saltstack/salt | salt/states/ipset.py | absent | def absent(name, entry=None, entries=None, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Remove a entry or entries from a chain
name
A user-defined name to call this entry by in another part of a state or
formula. This should not be an actual entry.
family
Network family, ipv4 or ipv6.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if not entry:
ret['result'] = False
ret['comment'] = ('ipset entry must be specified')
return ret
entries = []
if isinstance(entry, list):
entries = entry
else:
entries.append(entry)
for entry in entries:
entry_opts = ''
if ' ' in entry:
entry, entry_opts = entry.split(' ', 1)
if 'timeout' in kwargs and 'timeout' not in entry_opts:
entry_opts = 'timeout {0} {1}'.format(kwargs['timeout'], entry_opts)
if 'comment' in kwargs and 'comment' not in entry_opts:
entry_opts = '{0} comment "{1}"'.format(entry_opts, kwargs['comment'])
_entry = ' '.join([entry, entry_opts]).strip()
log.debug('_entry %s', _entry)
if not __salt__['ipset.check'](kwargs['set_name'],
_entry,
family) is True:
ret['result'] = True
ret['comment'] += 'ipset entry for {0} not present in set {1} for {2}\n'.format(
_entry,
kwargs['set_name'],
family)
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] += 'ipset entry {0} would be removed from set {1} for {2}\n'.format(
entry,
kwargs['set_name'],
family)
else:
command = __salt__['ipset.delete'](kwargs['set_name'], entry, family, **kwargs)
if 'Error' not in command:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] += 'ipset entry {1} removed from set {0} for {2}\n'.format(
kwargs['set_name'],
_entry,
family)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete ipset entry from set {0} for {2}. ' \
'Attempted entry was {1}.\n' \
'{3}\n'.format(kwargs['set_name'], _entry, family, command)
return ret | python | def absent(name, entry=None, entries=None, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Remove a entry or entries from a chain
name
A user-defined name to call this entry by in another part of a state or
formula. This should not be an actual entry.
family
Network family, ipv4 or ipv6.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if not entry:
ret['result'] = False
ret['comment'] = ('ipset entry must be specified')
return ret
entries = []
if isinstance(entry, list):
entries = entry
else:
entries.append(entry)
for entry in entries:
entry_opts = ''
if ' ' in entry:
entry, entry_opts = entry.split(' ', 1)
if 'timeout' in kwargs and 'timeout' not in entry_opts:
entry_opts = 'timeout {0} {1}'.format(kwargs['timeout'], entry_opts)
if 'comment' in kwargs and 'comment' not in entry_opts:
entry_opts = '{0} comment "{1}"'.format(entry_opts, kwargs['comment'])
_entry = ' '.join([entry, entry_opts]).strip()
log.debug('_entry %s', _entry)
if not __salt__['ipset.check'](kwargs['set_name'],
_entry,
family) is True:
ret['result'] = True
ret['comment'] += 'ipset entry for {0} not present in set {1} for {2}\n'.format(
_entry,
kwargs['set_name'],
family)
else:
if __opts__['test']:
ret['result'] = None
ret['comment'] += 'ipset entry {0} would be removed from set {1} for {2}\n'.format(
entry,
kwargs['set_name'],
family)
else:
command = __salt__['ipset.delete'](kwargs['set_name'], entry, family, **kwargs)
if 'Error' not in command:
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] += 'ipset entry {1} removed from set {0} for {2}\n'.format(
kwargs['set_name'],
_entry,
family)
else:
ret['result'] = False
ret['comment'] = 'Failed to delete ipset entry from set {0} for {2}. ' \
'Attempted entry was {1}.\n' \
'{3}\n'.format(kwargs['set_name'], _entry, family, command)
return ret | [
"def",
"absent",
"(",
"name",
",",
"entry",
"=",
"None",
",",
"entries",
"=",
"None",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
... | .. versionadded:: 2014.7.0
Remove a entry or entries from a chain
name
A user-defined name to call this entry by in another part of a state or
formula. This should not be an actual entry.
family
Network family, ipv4 or ipv6. | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipset.py#L239-L309 | train |
saltstack/salt | salt/states/ipset.py | flush | def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current ipset set
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check_set'](name)
if set_check is False:
ret['result'] = False
ret['comment'] = ('ipset set {0} does not exist for {1}'
.format(name, family))
return ret
if __opts__['test']:
ret['comment'] = 'ipset entries in set {0} for {1} would be flushed'.format(
name,
family)
return ret
if __salt__['ipset.flush'](name, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flushed ipset entries from set {0} for {1}'.format(
name,
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush ipset entries from set {0} for {1}' \
''.format(name, family)
return ret | python | def flush(name, family='ipv4', **kwargs):
'''
.. versionadded:: 2014.7.0
Flush current ipset set
family
Networking family, either ipv4 or ipv6
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
set_check = __salt__['ipset.check_set'](name)
if set_check is False:
ret['result'] = False
ret['comment'] = ('ipset set {0} does not exist for {1}'
.format(name, family))
return ret
if __opts__['test']:
ret['comment'] = 'ipset entries in set {0} for {1} would be flushed'.format(
name,
family)
return ret
if __salt__['ipset.flush'](name, family):
ret['changes'] = {'locale': name}
ret['result'] = True
ret['comment'] = 'Flushed ipset entries from set {0} for {1}'.format(
name,
family
)
return ret
else:
ret['result'] = False
ret['comment'] = 'Failed to flush ipset entries from set {0} for {1}' \
''.format(name, family)
return ret | [
"def",
"flush",
"(",
"name",
",",
"family",
"=",
"'ipv4'",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"set_check",
"=... | .. versionadded:: 2014.7.0
Flush current ipset set
family
Networking family, either ipv4 or ipv6 | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/ipset.py#L312-L351 | train |
saltstack/salt | salt/states/gem.py | installed | def installed(name, # pylint: disable=C0103
ruby=None,
gem_bin=None,
user=None,
version=None,
rdoc=False,
ri=False,
pre_releases=False,
proxy=None,
source=None): # pylint: disable=C0103
'''
Make sure that a gem is installed.
name
The name of the gem to install
ruby: None
Only for RVM or rbenv installations: the ruby version and gemset to
target.
gem_bin: None
Custom ``gem`` command to run instead of the default.
Use this to install gems to a non-default ruby install. If you are
using rvm or rbenv use the ruby argument instead.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
version : None
Specify the version to install for the gem.
Doesn't play nice with multiple gems at once
rdoc : False
Generate RDoc documentation for the gem(s).
ri : False
Generate RI documentation for the gem(s).
pre_releases : False
Install pre-release version of gem(s) if available.
proxy : None
Use the specified HTTP proxy server for all outgoing traffic.
Format: http://hostname[:port]
source : None
Use the specified HTTP gem source server to download gem.
Format: http://hostname[:port]
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if ruby is not None and not(__salt__['rvm.is_installed'](runas=user) or __salt__['rbenv.is_installed'](runas=user)):
log.warning(
'Use of argument ruby found, but neither rvm or rbenv is installed'
)
gems = __salt__['gem.list'](name, ruby, gem_bin=gem_bin, runas=user)
if name in gems and version is not None:
versions = list([x.replace('default: ', '') for x in gems[name]])
match = re.match(r'(>=|>|<|<=)', version)
if match:
# Grab the comparison
cmpr = match.group()
# Clear out 'default:' and any whitespace
installed_version = re.sub('default: ', '', gems[name][0]).strip()
# Clear out comparison from version and whitespace
desired_version = re.sub(cmpr, '', version).strip()
if salt.utils.versions.compare(installed_version,
cmpr,
desired_version):
ret['result'] = True
ret['comment'] = 'Installed Gem meets version requirements.'
return ret
elif str(version) in versions:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
else:
if str(version) in gems[name]:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
elif name in gems and version is None:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem {0} would have been installed'.format(name)
return ret
if __salt__['gem.install'](name,
ruby=ruby,
gem_bin=gem_bin,
runas=user,
version=version,
rdoc=rdoc,
ri=ri,
pre_releases=pre_releases,
proxy=proxy,
source=source):
ret['result'] = True
ret['changes'][name] = 'Installed'
ret['comment'] = 'Gem was successfully installed'
else:
ret['result'] = False
ret['comment'] = 'Could not install gem.'
return ret | python | def installed(name, # pylint: disable=C0103
ruby=None,
gem_bin=None,
user=None,
version=None,
rdoc=False,
ri=False,
pre_releases=False,
proxy=None,
source=None): # pylint: disable=C0103
'''
Make sure that a gem is installed.
name
The name of the gem to install
ruby: None
Only for RVM or rbenv installations: the ruby version and gemset to
target.
gem_bin: None
Custom ``gem`` command to run instead of the default.
Use this to install gems to a non-default ruby install. If you are
using rvm or rbenv use the ruby argument instead.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
version : None
Specify the version to install for the gem.
Doesn't play nice with multiple gems at once
rdoc : False
Generate RDoc documentation for the gem(s).
ri : False
Generate RI documentation for the gem(s).
pre_releases : False
Install pre-release version of gem(s) if available.
proxy : None
Use the specified HTTP proxy server for all outgoing traffic.
Format: http://hostname[:port]
source : None
Use the specified HTTP gem source server to download gem.
Format: http://hostname[:port]
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if ruby is not None and not(__salt__['rvm.is_installed'](runas=user) or __salt__['rbenv.is_installed'](runas=user)):
log.warning(
'Use of argument ruby found, but neither rvm or rbenv is installed'
)
gems = __salt__['gem.list'](name, ruby, gem_bin=gem_bin, runas=user)
if name in gems and version is not None:
versions = list([x.replace('default: ', '') for x in gems[name]])
match = re.match(r'(>=|>|<|<=)', version)
if match:
# Grab the comparison
cmpr = match.group()
# Clear out 'default:' and any whitespace
installed_version = re.sub('default: ', '', gems[name][0]).strip()
# Clear out comparison from version and whitespace
desired_version = re.sub(cmpr, '', version).strip()
if salt.utils.versions.compare(installed_version,
cmpr,
desired_version):
ret['result'] = True
ret['comment'] = 'Installed Gem meets version requirements.'
return ret
elif str(version) in versions:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
else:
if str(version) in gems[name]:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
elif name in gems and version is None:
ret['result'] = True
ret['comment'] = 'Gem is already installed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem {0} would have been installed'.format(name)
return ret
if __salt__['gem.install'](name,
ruby=ruby,
gem_bin=gem_bin,
runas=user,
version=version,
rdoc=rdoc,
ri=ri,
pre_releases=pre_releases,
proxy=proxy,
source=source):
ret['result'] = True
ret['changes'][name] = 'Installed'
ret['comment'] = 'Gem was successfully installed'
else:
ret['result'] = False
ret['comment'] = 'Could not install gem.'
return ret | [
"def",
"installed",
"(",
"name",
",",
"# pylint: disable=C0103",
"ruby",
"=",
"None",
",",
"gem_bin",
"=",
"None",
",",
"user",
"=",
"None",
",",
"version",
"=",
"None",
",",
"rdoc",
"=",
"False",
",",
"ri",
"=",
"False",
",",
"pre_releases",
"=",
"Fal... | Make sure that a gem is installed.
name
The name of the gem to install
ruby: None
Only for RVM or rbenv installations: the ruby version and gemset to
target.
gem_bin: None
Custom ``gem`` command to run instead of the default.
Use this to install gems to a non-default ruby install. If you are
using rvm or rbenv use the ruby argument instead.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
version : None
Specify the version to install for the gem.
Doesn't play nice with multiple gems at once
rdoc : False
Generate RDoc documentation for the gem(s).
ri : False
Generate RI documentation for the gem(s).
pre_releases : False
Install pre-release version of gem(s) if available.
proxy : None
Use the specified HTTP proxy server for all outgoing traffic.
Format: http://hostname[:port]
source : None
Use the specified HTTP gem source server to download gem.
Format: http://hostname[:port] | [
"Make",
"sure",
"that",
"a",
"gem",
"is",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gem.py#L33-L143 | train |
saltstack/salt | salt/states/gem.py | removed | def removed(name, ruby=None, user=None, gem_bin=None):
'''
Make sure that a gem is not installed.
name
The name of the gem to uninstall
gem_bin : None
Full path to ``gem`` binary to use.
ruby : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name not in __salt__['gem.list'](name, ruby, gem_bin=gem_bin, runas=user):
ret['result'] = True
ret['comment'] = 'Gem is not installed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem {0} would have been removed'.format(name)
return ret
if __salt__['gem.uninstall'](name, ruby, gem_bin=gem_bin, runas=user):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Gem was successfully removed.'
else:
ret['result'] = False
ret['comment'] = 'Could not remove gem.'
return ret | python | def removed(name, ruby=None, user=None, gem_bin=None):
'''
Make sure that a gem is not installed.
name
The name of the gem to uninstall
gem_bin : None
Full path to ``gem`` binary to use.
ruby : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name not in __salt__['gem.list'](name, ruby, gem_bin=gem_bin, runas=user):
ret['result'] = True
ret['comment'] = 'Gem is not installed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem {0} would have been removed'.format(name)
return ret
if __salt__['gem.uninstall'](name, ruby, gem_bin=gem_bin, runas=user):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Gem was successfully removed.'
else:
ret['result'] = False
ret['comment'] = 'Could not remove gem.'
return ret | [
"def",
"removed",
"(",
"name",
",",
"ruby",
"=",
"None",
",",
"user",
"=",
"None",
",",
"gem_bin",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{... | Make sure that a gem is not installed.
name
The name of the gem to uninstall
gem_bin : None
Full path to ``gem`` binary to use.
ruby : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0 | [
"Make",
"sure",
"that",
"a",
"gem",
"is",
"not",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gem.py#L146-L182 | train |
saltstack/salt | salt/states/gem.py | sources_add | def sources_add(name, ruby=None, user=None):
'''
Make sure that a gem source is added.
name
The URL of the gem source to be added
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name in __salt__['gem.sources_list'](ruby, runas=user):
ret['result'] = True
ret['comment'] = 'Gem source is already added.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem source {0} would have been added.'.format(name)
return ret
if __salt__['gem.sources_add'](source_uri=name, ruby=ruby, runas=user):
ret['result'] = True
ret['changes'][name] = 'Installed'
ret['comment'] = 'Gem source was successfully added.'
else:
ret['result'] = False
ret['comment'] = 'Could not add gem source.'
return ret | python | def sources_add(name, ruby=None, user=None):
'''
Make sure that a gem source is added.
name
The URL of the gem source to be added
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name in __salt__['gem.sources_list'](ruby, runas=user):
ret['result'] = True
ret['comment'] = 'Gem source is already added.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem source {0} would have been added.'.format(name)
return ret
if __salt__['gem.sources_add'](source_uri=name, ruby=ruby, runas=user):
ret['result'] = True
ret['changes'][name] = 'Installed'
ret['comment'] = 'Gem source was successfully added.'
else:
ret['result'] = False
ret['comment'] = 'Could not add gem source.'
return ret | [
"def",
"sources_add",
"(",
"name",
",",
"ruby",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"name"... | Make sure that a gem source is added.
name
The URL of the gem source to be added
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0 | [
"Make",
"sure",
"that",
"a",
"gem",
"source",
"is",
"added",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gem.py#L185-L216 | train |
saltstack/salt | salt/states/gem.py | sources_remove | def sources_remove(name, ruby=None, user=None):
'''
Make sure that a gem source is removed.
name
The URL of the gem source to be removed
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name not in __salt__['gem.sources_list'](ruby, runas=user):
ret['result'] = True
ret['comment'] = 'Gem source is already removed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem source would have been removed.'
return ret
if __salt__['gem.sources_remove'](source_uri=name, ruby=ruby, runas=user):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Gem source was successfully removed.'
else:
ret['result'] = False
ret['comment'] = 'Could not remove gem source.'
return ret | python | def sources_remove(name, ruby=None, user=None):
'''
Make sure that a gem source is removed.
name
The URL of the gem source to be removed
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
if name not in __salt__['gem.sources_list'](ruby, runas=user):
ret['result'] = True
ret['comment'] = 'Gem source is already removed.'
return ret
if __opts__['test']:
ret['comment'] = 'The gem source would have been removed.'
return ret
if __salt__['gem.sources_remove'](source_uri=name, ruby=ruby, runas=user):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Gem source was successfully removed.'
else:
ret['result'] = False
ret['comment'] = 'Could not remove gem source.'
return ret | [
"def",
"sources_remove",
"(",
"name",
",",
"ruby",
"=",
"None",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"if",
"na... | Make sure that a gem source is removed.
name
The URL of the gem source to be removed
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
.. versionadded:: 0.17.0 | [
"Make",
"sure",
"that",
"a",
"gem",
"source",
"is",
"removed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gem.py#L219-L252 | train |
saltstack/salt | salt/states/rabbitmq_cluster.py | joined | def joined(name, host, user='rabbit', ram_node=None, runas='root'):
'''
Ensure the current node joined to a cluster with node user@host
name
Irrelevant, not used (recommended: user@host)
user
The user of node to join to (default: rabbit)
host
The host of node to join to
ram_node
Join node as a RAM node
runas
The user to run the rabbitmq command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
status = __salt__['rabbitmq.cluster_status']()
if '{0}@{1}'.format(user, host) in status:
ret['comment'] = 'Already in cluster'
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.join_cluster'](host,
user,
ram_node,
runas=runas)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Join' in result:
ret['comment'] = result['Join']
# If we've reached this far before returning, we have changes.
ret['changes'] = {'old': '', 'new': '{0}@{1}'.format(user, host)}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Node is set to join cluster {0}@{1}'.format(
user, host)
return ret | python | def joined(name, host, user='rabbit', ram_node=None, runas='root'):
'''
Ensure the current node joined to a cluster with node user@host
name
Irrelevant, not used (recommended: user@host)
user
The user of node to join to (default: rabbit)
host
The host of node to join to
ram_node
Join node as a RAM node
runas
The user to run the rabbitmq command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
status = __salt__['rabbitmq.cluster_status']()
if '{0}@{1}'.format(user, host) in status:
ret['comment'] = 'Already in cluster'
return ret
if not __opts__['test']:
result = __salt__['rabbitmq.join_cluster'](host,
user,
ram_node,
runas=runas)
if 'Error' in result:
ret['result'] = False
ret['comment'] = result['Error']
return ret
elif 'Join' in result:
ret['comment'] = result['Join']
# If we've reached this far before returning, we have changes.
ret['changes'] = {'old': '', 'new': '{0}@{1}'.format(user, host)}
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Node is set to join cluster {0}@{1}'.format(
user, host)
return ret | [
"def",
"joined",
"(",
"name",
",",
"host",
",",
"user",
"=",
"'rabbit'",
",",
"ram_node",
"=",
"None",
",",
"runas",
"=",
"'root'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
... | Ensure the current node joined to a cluster with node user@host
name
Irrelevant, not used (recommended: user@host)
user
The user of node to join to (default: rabbit)
host
The host of node to join to
ram_node
Join node as a RAM node
runas
The user to run the rabbitmq command as | [
"Ensure",
"the",
"current",
"node",
"joined",
"to",
"a",
"cluster",
"with",
"node",
"user@host"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rabbitmq_cluster.py#L34-L77 | train |
saltstack/salt | salt/modules/glanceng.py | image_create | def image_create(auth=None, **kwargs):
'''
Create an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw
salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw hw_scsi_model=virtio-scsi hw_disk_bus=scsi
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(keep_name=True, **kwargs)
return cloud.create_image(**kwargs) | python | def image_create(auth=None, **kwargs):
'''
Create an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw
salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw hw_scsi_model=virtio-scsi hw_disk_bus=scsi
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(keep_name=True, **kwargs)
return cloud.create_image(**kwargs) | [
"def",
"image_create",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"keep_name",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".... | Create an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw
salt '*' glanceng.image_create name=cirros file=cirros.raw disk_format=raw hw_scsi_model=virtio-scsi hw_disk_bus=scsi | [
"Create",
"an",
"image"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L108-L121 | train |
saltstack/salt | salt/modules/glanceng.py | image_delete | def image_delete(auth=None, **kwargs):
'''
Delete an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_delete name=image1
salt '*' glanceng.image_delete name=0e4febc2a5ab4f2c8f374b054162506d
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_image(**kwargs) | python | def image_delete(auth=None, **kwargs):
'''
Delete an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_delete name=image1
salt '*' glanceng.image_delete name=0e4febc2a5ab4f2c8f374b054162506d
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_image(**kwargs) | [
"def",
"image_delete",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"delete_image",
"(",
"*",
"*... | Delete an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_delete name=image1
salt '*' glanceng.image_delete name=0e4febc2a5ab4f2c8f374b054162506d | [
"Delete",
"an",
"image"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L124-L137 | train |
saltstack/salt | salt/modules/glanceng.py | image_list | def image_list(auth=None, **kwargs):
'''
List images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_list
salt '*' glanceng.image_list
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_images(**kwargs) | python | def image_list(auth=None, **kwargs):
'''
List images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_list
salt '*' glanceng.image_list
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_images(**kwargs) | [
"def",
"image_list",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"list_images",
"(",
"*",
"*",
... | List images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_list
salt '*' glanceng.image_list | [
"List",
"images"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L140-L153 | train |
saltstack/salt | salt/modules/glanceng.py | image_search | def image_search(auth=None, **kwargs):
'''
Search for images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_search name=image1
salt '*' glanceng.image_search
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_images(**kwargs) | python | def image_search(auth=None, **kwargs):
'''
Search for images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_search name=image1
salt '*' glanceng.image_search
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.search_images(**kwargs) | [
"def",
"image_search",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"search_images",
"(",
"*",
"... | Search for images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_search name=image1
salt '*' glanceng.image_search | [
"Search",
"for",
"images"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L156-L169 | train |
saltstack/salt | salt/modules/glanceng.py | image_get | def image_get(auth=None, **kwargs):
'''
Get a single image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_get name=image1
salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_image(**kwargs) | python | def image_get(auth=None, **kwargs):
'''
Get a single image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_get name=image1
salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_image(**kwargs) | [
"def",
"image_get",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"get_image",
"(",
"*",
"*",
"... | Get a single image
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_get name=image1
salt '*' glanceng.image_get name=0e4febc2a5ab4f2c8f374b054162506d | [
"Get",
"a",
"single",
"image"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L172-L185 | train |
saltstack/salt | salt/modules/glanceng.py | update_image_properties | def update_image_properties(auth=None, **kwargs):
'''
Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.update_image_properties(**kwargs) | python | def update_image_properties(auth=None, **kwargs):
'''
Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.update_image_properties(**kwargs) | [
"def",
"update_image_properties",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_operator_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"update_image_propertie... | Update properties for an image
CLI Example:
.. code-block:: bash
salt '*' glanceng.update_image_properties name=image1 hw_scsi_model=virtio-scsi hw_disk_bus=scsi
salt '*' glanceng.update_image_properties name=0e4febc2a5ab4f2c8f374b054162506d min_ram=1024 | [
"Update",
"properties",
"for",
"an",
"image"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/glanceng.py#L188-L201 | train |
saltstack/salt | salt/runners/vistara.py | delete_device | def delete_device(name, safety_on=True):
'''
Deletes a device from Vistara based on DNS name or partial name. By default,
delete_device will only perform the delete if a single host is returned. Set
safety_on=False to delete all matches (up to default API search page size)
CLI Example:
.. code-block:: bash
salt-run vistara.delete_device 'hostname-101.mycompany.com'
salt-run vistara.delete_device 'hostname-101'
salt-run vistara.delete_device 'hostname-1' safety_on=False
'''
config = _get_vistara_configuration()
if not config:
return False
access_token = _get_oath2_access_token(config['client_key'], config['client_secret'])
if not access_token:
return 'Vistara access token not available'
query_string = 'dnsName:{0}'.format(name)
devices = _search_devices(query_string, config['client_id'], access_token)
if not devices:
return "No devices found"
device_count = len(devices)
if safety_on and device_count != 1:
return "Expected to delete 1 device and found {0}. "\
"Set safety_on=False to override.".format(device_count)
delete_responses = []
for device in devices:
device_id = device['id']
log.debug(device_id)
delete_response = _delete_resource(device_id, config['client_id'], access_token)
if not delete_response:
return False
delete_responses.append(delete_response)
return delete_responses | python | def delete_device(name, safety_on=True):
'''
Deletes a device from Vistara based on DNS name or partial name. By default,
delete_device will only perform the delete if a single host is returned. Set
safety_on=False to delete all matches (up to default API search page size)
CLI Example:
.. code-block:: bash
salt-run vistara.delete_device 'hostname-101.mycompany.com'
salt-run vistara.delete_device 'hostname-101'
salt-run vistara.delete_device 'hostname-1' safety_on=False
'''
config = _get_vistara_configuration()
if not config:
return False
access_token = _get_oath2_access_token(config['client_key'], config['client_secret'])
if not access_token:
return 'Vistara access token not available'
query_string = 'dnsName:{0}'.format(name)
devices = _search_devices(query_string, config['client_id'], access_token)
if not devices:
return "No devices found"
device_count = len(devices)
if safety_on and device_count != 1:
return "Expected to delete 1 device and found {0}. "\
"Set safety_on=False to override.".format(device_count)
delete_responses = []
for device in devices:
device_id = device['id']
log.debug(device_id)
delete_response = _delete_resource(device_id, config['client_id'], access_token)
if not delete_response:
return False
delete_responses.append(delete_response)
return delete_responses | [
"def",
"delete_device",
"(",
"name",
",",
"safety_on",
"=",
"True",
")",
":",
"config",
"=",
"_get_vistara_configuration",
"(",
")",
"if",
"not",
"config",
":",
"return",
"False",
"access_token",
"=",
"_get_oath2_access_token",
"(",
"config",
"[",
"'client_key'"... | Deletes a device from Vistara based on DNS name or partial name. By default,
delete_device will only perform the delete if a single host is returned. Set
safety_on=False to delete all matches (up to default API search page size)
CLI Example:
.. code-block:: bash
salt-run vistara.delete_device 'hostname-101.mycompany.com'
salt-run vistara.delete_device 'hostname-101'
salt-run vistara.delete_device 'hostname-1' safety_on=False | [
"Deletes",
"a",
"device",
"from",
"Vistara",
"based",
"on",
"DNS",
"name",
"or",
"partial",
"name",
".",
"By",
"default",
"delete_device",
"will",
"only",
"perform",
"the",
"delete",
"if",
"a",
"single",
"host",
"is",
"returned",
".",
"Set",
"safety_on",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vistara.py#L67-L114 | train |
saltstack/salt | salt/runners/vistara.py | _get_oath2_access_token | def _get_oath2_access_token(client_key, client_secret):
'''
Query the vistara API and get an access_token
'''
if not client_key and not client_secret:
log.error(
"client_key and client_secret have not been specified "
"and are required parameters."
)
return False
method = 'POST'
url = 'https://api.vistara.io/auth/oauth/token'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
params = {
'grant_type': 'client_credentials',
'client_id': client_key,
'client_secret': client_secret
}
resp = salt.utils.http.query(
url=url,
method=method,
header_dict=headers,
params=params,
opts=__opts__
)
respbody = resp.get('body', None)
if not respbody:
return False
access_token = salt.utils.json.loads(respbody)['access_token']
return access_token | python | def _get_oath2_access_token(client_key, client_secret):
'''
Query the vistara API and get an access_token
'''
if not client_key and not client_secret:
log.error(
"client_key and client_secret have not been specified "
"and are required parameters."
)
return False
method = 'POST'
url = 'https://api.vistara.io/auth/oauth/token'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
params = {
'grant_type': 'client_credentials',
'client_id': client_key,
'client_secret': client_secret
}
resp = salt.utils.http.query(
url=url,
method=method,
header_dict=headers,
params=params,
opts=__opts__
)
respbody = resp.get('body', None)
if not respbody:
return False
access_token = salt.utils.json.loads(respbody)['access_token']
return access_token | [
"def",
"_get_oath2_access_token",
"(",
"client_key",
",",
"client_secret",
")",
":",
"if",
"not",
"client_key",
"and",
"not",
"client_secret",
":",
"log",
".",
"error",
"(",
"\"client_key and client_secret have not been specified \"",
"\"and are required parameters.\"",
")"... | Query the vistara API and get an access_token | [
"Query",
"the",
"vistara",
"API",
"and",
"get",
"an",
"access_token"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/vistara.py#L181-L220 | train |
saltstack/salt | salt/modules/apache.py | version | def version():
'''
Return server version (``apachectl -v``)
CLI Example:
.. code-block:: bash
salt '*' apache.version
'''
cmd = '{0} -v'.format(_detect_os())
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split(': ')
return ret[1] | python | def version():
'''
Return server version (``apachectl -v``)
CLI Example:
.. code-block:: bash
salt '*' apache.version
'''
cmd = '{0} -v'.format(_detect_os())
out = __salt__['cmd.run'](cmd).splitlines()
ret = out[0].split(': ')
return ret[1] | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"'{0} -v'",
".",
"format",
"(",
"_detect_os",
"(",
")",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"ret",
"=",
"out",
"[",
"0",
"]",
".",
"split",... | Return server version (``apachectl -v``)
CLI Example:
.. code-block:: bash
salt '*' apache.version | [
"Return",
"server",
"version",
"(",
"apachectl",
"-",
"v",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L65-L78 | train |
saltstack/salt | salt/modules/apache.py | fullversion | def fullversion():
'''
Return server version (``apachectl -V``)
CLI Example:
.. code-block:: bash
salt '*' apache.fullversion
'''
cmd = '{0} -V'.format(_detect_os())
ret = {}
ret['compiled_with'] = []
out = __salt__['cmd.run'](cmd).splitlines()
# Example
# -D APR_HAS_MMAP
define_re = re.compile(r'^\s+-D\s+')
for line in out:
if ': ' in line:
comps = line.split(': ')
if not comps:
continue
ret[comps[0].strip().lower().replace(' ', '_')] = comps[1].strip()
elif ' -D' in line:
cwith = define_re.sub('', line)
ret['compiled_with'].append(cwith)
return ret | python | def fullversion():
'''
Return server version (``apachectl -V``)
CLI Example:
.. code-block:: bash
salt '*' apache.fullversion
'''
cmd = '{0} -V'.format(_detect_os())
ret = {}
ret['compiled_with'] = []
out = __salt__['cmd.run'](cmd).splitlines()
# Example
# -D APR_HAS_MMAP
define_re = re.compile(r'^\s+-D\s+')
for line in out:
if ': ' in line:
comps = line.split(': ')
if not comps:
continue
ret[comps[0].strip().lower().replace(' ', '_')] = comps[1].strip()
elif ' -D' in line:
cwith = define_re.sub('', line)
ret['compiled_with'].append(cwith)
return ret | [
"def",
"fullversion",
"(",
")",
":",
"cmd",
"=",
"'{0} -V'",
".",
"format",
"(",
"_detect_os",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'compiled_with'",
"]",
"=",
"[",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
... | Return server version (``apachectl -V``)
CLI Example:
.. code-block:: bash
salt '*' apache.fullversion | [
"Return",
"server",
"version",
"(",
"apachectl",
"-",
"V",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L81-L107 | train |
saltstack/salt | salt/modules/apache.py | modules | def modules():
'''
Return list of static and shared modules (``apachectl -M``)
CLI Example:
.. code-block:: bash
salt '*' apache.modules
'''
cmd = '{0} -M'.format(_detect_os())
ret = {}
ret['static'] = []
ret['shared'] = []
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.split()
if not comps:
continue
if '(static)' in line:
ret['static'].append(comps[0])
if '(shared)' in line:
ret['shared'].append(comps[0])
return ret | python | def modules():
'''
Return list of static and shared modules (``apachectl -M``)
CLI Example:
.. code-block:: bash
salt '*' apache.modules
'''
cmd = '{0} -M'.format(_detect_os())
ret = {}
ret['static'] = []
ret['shared'] = []
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
comps = line.split()
if not comps:
continue
if '(static)' in line:
ret['static'].append(comps[0])
if '(shared)' in line:
ret['shared'].append(comps[0])
return ret | [
"def",
"modules",
"(",
")",
":",
"cmd",
"=",
"'{0} -M'",
".",
"format",
"(",
"_detect_os",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'static'",
"]",
"=",
"[",
"]",
"ret",
"[",
"'shared'",
"]",
"=",
"[",
"]",
"out",
"=",
"__salt__",
"[",... | Return list of static and shared modules (``apachectl -M``)
CLI Example:
.. code-block:: bash
salt '*' apache.modules | [
"Return",
"list",
"of",
"static",
"and",
"shared",
"modules",
"(",
"apachectl",
"-",
"M",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L110-L133 | train |
saltstack/salt | salt/modules/apache.py | servermods | def servermods():
'''
Return list of modules compiled into the server (``apachectl -l``)
CLI Example:
.. code-block:: bash
salt '*' apache.servermods
'''
cmd = '{0} -l'.format(_detect_os())
ret = []
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if '.c' in line:
ret.append(line.strip())
return ret | python | def servermods():
'''
Return list of modules compiled into the server (``apachectl -l``)
CLI Example:
.. code-block:: bash
salt '*' apache.servermods
'''
cmd = '{0} -l'.format(_detect_os())
ret = []
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
if not line:
continue
if '.c' in line:
ret.append(line.strip())
return ret | [
"def",
"servermods",
"(",
")",
":",
"cmd",
"=",
"'{0} -l'",
".",
"format",
"(",
"_detect_os",
"(",
")",
")",
"ret",
"=",
"[",
"]",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"... | Return list of modules compiled into the server (``apachectl -l``)
CLI Example:
.. code-block:: bash
salt '*' apache.servermods | [
"Return",
"list",
"of",
"modules",
"compiled",
"into",
"the",
"server",
"(",
"apachectl",
"-",
"l",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L136-L154 | train |
saltstack/salt | salt/modules/apache.py | directives | def directives():
'''
Return list of directives together with expected arguments
and places where the directive is valid (``apachectl -L``)
CLI Example:
.. code-block:: bash
salt '*' apache.directives
'''
cmd = '{0} -L'.format(_detect_os())
ret = {}
out = __salt__['cmd.run'](cmd)
out = out.replace('\n\t', '\t')
for line in out.splitlines():
if not line:
continue
comps = line.split('\t')
desc = '\n'.join(comps[1:])
ret[comps[0]] = desc
return ret | python | def directives():
'''
Return list of directives together with expected arguments
and places where the directive is valid (``apachectl -L``)
CLI Example:
.. code-block:: bash
salt '*' apache.directives
'''
cmd = '{0} -L'.format(_detect_os())
ret = {}
out = __salt__['cmd.run'](cmd)
out = out.replace('\n\t', '\t')
for line in out.splitlines():
if not line:
continue
comps = line.split('\t')
desc = '\n'.join(comps[1:])
ret[comps[0]] = desc
return ret | [
"def",
"directives",
"(",
")",
":",
"cmd",
"=",
"'{0} -L'",
".",
"format",
"(",
"_detect_os",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"out",
"=",
"out",
".",
"replace",
"(",
"'\\n\\t'",
... | Return list of directives together with expected arguments
and places where the directive is valid (``apachectl -L``)
CLI Example:
.. code-block:: bash
salt '*' apache.directives | [
"Return",
"list",
"of",
"directives",
"together",
"with",
"expected",
"arguments",
"and",
"places",
"where",
"the",
"directive",
"is",
"valid",
"(",
"apachectl",
"-",
"L",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L157-L178 | train |
saltstack/salt | salt/modules/apache.py | vhosts | def vhosts():
'''
Show the settings as parsed from the config file (currently
only shows the virtualhost settings) (``apachectl -S``).
Because each additional virtual host adds to the execution
time, this command may require a long timeout be specified
by using ``-t 10``.
CLI Example:
.. code-block:: bash
salt -t 10 '*' apache.vhosts
'''
cmd = '{0} -S'.format(_detect_os())
ret = {}
namevhost = ''
out = __salt__['cmd.run'](cmd)
for line in out.splitlines():
if not line:
continue
comps = line.split()
if 'is a NameVirtualHost' in line:
namevhost = comps[0]
ret[namevhost] = {}
else:
if comps[0] == 'default':
ret[namevhost]['default'] = {}
ret[namevhost]['default']['vhost'] = comps[2]
ret[namevhost]['default']['conf'] = re.sub(
r'\(|\)',
'',
comps[3]
)
if comps[0] == 'port':
ret[namevhost][comps[3]] = {}
ret[namevhost][comps[3]]['vhost'] = comps[3]
ret[namevhost][comps[3]]['conf'] = re.sub(
r'\(|\)',
'',
comps[4]
)
ret[namevhost][comps[3]]['port'] = comps[1]
return ret | python | def vhosts():
'''
Show the settings as parsed from the config file (currently
only shows the virtualhost settings) (``apachectl -S``).
Because each additional virtual host adds to the execution
time, this command may require a long timeout be specified
by using ``-t 10``.
CLI Example:
.. code-block:: bash
salt -t 10 '*' apache.vhosts
'''
cmd = '{0} -S'.format(_detect_os())
ret = {}
namevhost = ''
out = __salt__['cmd.run'](cmd)
for line in out.splitlines():
if not line:
continue
comps = line.split()
if 'is a NameVirtualHost' in line:
namevhost = comps[0]
ret[namevhost] = {}
else:
if comps[0] == 'default':
ret[namevhost]['default'] = {}
ret[namevhost]['default']['vhost'] = comps[2]
ret[namevhost]['default']['conf'] = re.sub(
r'\(|\)',
'',
comps[3]
)
if comps[0] == 'port':
ret[namevhost][comps[3]] = {}
ret[namevhost][comps[3]]['vhost'] = comps[3]
ret[namevhost][comps[3]]['conf'] = re.sub(
r'\(|\)',
'',
comps[4]
)
ret[namevhost][comps[3]]['port'] = comps[1]
return ret | [
"def",
"vhosts",
"(",
")",
":",
"cmd",
"=",
"'{0} -S'",
".",
"format",
"(",
"_detect_os",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"namevhost",
"=",
"''",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"for",
"line",
"in",
"out",
"."... | Show the settings as parsed from the config file (currently
only shows the virtualhost settings) (``apachectl -S``).
Because each additional virtual host adds to the execution
time, this command may require a long timeout be specified
by using ``-t 10``.
CLI Example:
.. code-block:: bash
salt -t 10 '*' apache.vhosts | [
"Show",
"the",
"settings",
"as",
"parsed",
"from",
"the",
"config",
"file",
"(",
"currently",
"only",
"shows",
"the",
"virtualhost",
"settings",
")",
"(",
"apachectl",
"-",
"S",
")",
".",
"Because",
"each",
"additional",
"virtual",
"host",
"adds",
"to",
"t... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L181-L224 | train |
saltstack/salt | salt/modules/apache.py | signal | def signal(signal=None):
'''
Signals httpd to start, restart, or stop.
CLI Example:
.. code-block:: bash
salt '*' apache.signal restart
'''
no_extra_args = ('configtest', 'status', 'fullstatus')
valid_signals = ('start', 'stop', 'restart', 'graceful', 'graceful-stop')
if signal not in valid_signals and signal not in no_extra_args:
return
# Make sure you use the right arguments
if signal in valid_signals:
arguments = ' -k {0}'.format(signal)
else:
arguments = ' {0}'.format(signal)
cmd = _detect_os() + arguments
out = __salt__['cmd.run_all'](cmd)
# A non-zero return code means fail
if out['retcode'] and out['stderr']:
ret = out['stderr'].strip()
# 'apachectl configtest' returns 'Syntax OK' to stderr
elif out['stderr']:
ret = out['stderr'].strip()
elif out['stdout']:
ret = out['stdout'].strip()
# No output for something like: apachectl graceful
else:
ret = 'Command: "{0}" completed successfully!'.format(cmd)
return ret | python | def signal(signal=None):
'''
Signals httpd to start, restart, or stop.
CLI Example:
.. code-block:: bash
salt '*' apache.signal restart
'''
no_extra_args = ('configtest', 'status', 'fullstatus')
valid_signals = ('start', 'stop', 'restart', 'graceful', 'graceful-stop')
if signal not in valid_signals and signal not in no_extra_args:
return
# Make sure you use the right arguments
if signal in valid_signals:
arguments = ' -k {0}'.format(signal)
else:
arguments = ' {0}'.format(signal)
cmd = _detect_os() + arguments
out = __salt__['cmd.run_all'](cmd)
# A non-zero return code means fail
if out['retcode'] and out['stderr']:
ret = out['stderr'].strip()
# 'apachectl configtest' returns 'Syntax OK' to stderr
elif out['stderr']:
ret = out['stderr'].strip()
elif out['stdout']:
ret = out['stdout'].strip()
# No output for something like: apachectl graceful
else:
ret = 'Command: "{0}" completed successfully!'.format(cmd)
return ret | [
"def",
"signal",
"(",
"signal",
"=",
"None",
")",
":",
"no_extra_args",
"=",
"(",
"'configtest'",
",",
"'status'",
",",
"'fullstatus'",
")",
"valid_signals",
"=",
"(",
"'start'",
",",
"'stop'",
",",
"'restart'",
",",
"'graceful'",
",",
"'graceful-stop'",
")"... | Signals httpd to start, restart, or stop.
CLI Example:
.. code-block:: bash
salt '*' apache.signal restart | [
"Signals",
"httpd",
"to",
"start",
"restart",
"or",
"stop",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L227-L261 | train |
saltstack/salt | salt/modules/apache.py | useradd | def useradd(pwfile, user, password, opts=''):
'''
Add HTTP user using the ``htpasswd`` command. If the ``htpasswd`` file does not
exist, it will be created. Valid options that can be passed are:
.. code-block:: text
n Don't update file; display results on stdout.
m Force MD5 hashing of the password (default).
d Force CRYPT(3) hashing of the password.
p Do not hash the password (plaintext).
s Force SHA1 hashing of the password.
CLI Examples:
.. code-block:: bash
salt '*' apache.useradd /etc/httpd/htpasswd larry badpassword
salt '*' apache.useradd /etc/httpd/htpasswd larry badpass opts=ns
'''
return __salt__['webutil.useradd'](pwfile, user, password, opts) | python | def useradd(pwfile, user, password, opts=''):
'''
Add HTTP user using the ``htpasswd`` command. If the ``htpasswd`` file does not
exist, it will be created. Valid options that can be passed are:
.. code-block:: text
n Don't update file; display results on stdout.
m Force MD5 hashing of the password (default).
d Force CRYPT(3) hashing of the password.
p Do not hash the password (plaintext).
s Force SHA1 hashing of the password.
CLI Examples:
.. code-block:: bash
salt '*' apache.useradd /etc/httpd/htpasswd larry badpassword
salt '*' apache.useradd /etc/httpd/htpasswd larry badpass opts=ns
'''
return __salt__['webutil.useradd'](pwfile, user, password, opts) | [
"def",
"useradd",
"(",
"pwfile",
",",
"user",
",",
"password",
",",
"opts",
"=",
"''",
")",
":",
"return",
"__salt__",
"[",
"'webutil.useradd'",
"]",
"(",
"pwfile",
",",
"user",
",",
"password",
",",
"opts",
")"
] | Add HTTP user using the ``htpasswd`` command. If the ``htpasswd`` file does not
exist, it will be created. Valid options that can be passed are:
.. code-block:: text
n Don't update file; display results on stdout.
m Force MD5 hashing of the password (default).
d Force CRYPT(3) hashing of the password.
p Do not hash the password (plaintext).
s Force SHA1 hashing of the password.
CLI Examples:
.. code-block:: bash
salt '*' apache.useradd /etc/httpd/htpasswd larry badpassword
salt '*' apache.useradd /etc/httpd/htpasswd larry badpass opts=ns | [
"Add",
"HTTP",
"user",
"using",
"the",
"htpasswd",
"command",
".",
"If",
"the",
"htpasswd",
"file",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
".",
"Valid",
"options",
"that",
"can",
"be",
"passed",
"are",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L264-L284 | train |
saltstack/salt | salt/modules/apache.py | server_status | def server_status(profile='default'):
'''
Get Information from the Apache server-status handler
.. note::
The server-status handler is disabled by default.
In order for this function to work it needs to be enabled.
See http://httpd.apache.org/docs/2.2/mod/mod_status.html
The following configuration needs to exists in pillar/grains.
Each entry nested in ``apache.server-status`` is a profile of a vhost/server.
This would give support for multiple apache servers/vhosts.
.. code-block:: yaml
apache.server-status:
default:
url: http://localhost/server-status
user: someuser
pass: password
realm: 'authentication realm for digest passwords'
timeout: 5
CLI Examples:
.. code-block:: bash
salt '*' apache.server_status
salt '*' apache.server_status other-profile
'''
ret = {
'Scoreboard': {
'_': 0,
'S': 0,
'R': 0,
'W': 0,
'K': 0,
'D': 0,
'C': 0,
'L': 0,
'G': 0,
'I': 0,
'.': 0,
},
}
# Get configuration from pillar
url = __salt__['config.get'](
'apache.server-status:{0}:url'.format(profile),
'http://localhost/server-status'
)
user = __salt__['config.get'](
'apache.server-status:{0}:user'.format(profile),
''
)
passwd = __salt__['config.get'](
'apache.server-status:{0}:pass'.format(profile),
''
)
realm = __salt__['config.get'](
'apache.server-status:{0}:realm'.format(profile),
''
)
timeout = __salt__['config.get'](
'apache.server-status:{0}:timeout'.format(profile),
5
)
# create authentication handler if configuration exists
if user and passwd:
basic = _HTTPBasicAuthHandler()
basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)
_install_opener(_build_opener(basic, digest))
# get http data
url += '?auto'
try:
response = _urlopen(url, timeout=timeout).read().splitlines()
except URLError:
return 'error'
# parse the data
for line in response:
splt = line.split(':', 1)
splt[0] = splt[0].strip()
splt[1] = splt[1].strip()
if splt[0] == 'Scoreboard':
for c in splt[1]:
ret['Scoreboard'][c] += 1
else:
if splt[1].isdigit():
ret[splt[0]] = int(splt[1])
else:
ret[splt[0]] = float(splt[1])
# return the good stuff
return ret | python | def server_status(profile='default'):
'''
Get Information from the Apache server-status handler
.. note::
The server-status handler is disabled by default.
In order for this function to work it needs to be enabled.
See http://httpd.apache.org/docs/2.2/mod/mod_status.html
The following configuration needs to exists in pillar/grains.
Each entry nested in ``apache.server-status`` is a profile of a vhost/server.
This would give support for multiple apache servers/vhosts.
.. code-block:: yaml
apache.server-status:
default:
url: http://localhost/server-status
user: someuser
pass: password
realm: 'authentication realm for digest passwords'
timeout: 5
CLI Examples:
.. code-block:: bash
salt '*' apache.server_status
salt '*' apache.server_status other-profile
'''
ret = {
'Scoreboard': {
'_': 0,
'S': 0,
'R': 0,
'W': 0,
'K': 0,
'D': 0,
'C': 0,
'L': 0,
'G': 0,
'I': 0,
'.': 0,
},
}
# Get configuration from pillar
url = __salt__['config.get'](
'apache.server-status:{0}:url'.format(profile),
'http://localhost/server-status'
)
user = __salt__['config.get'](
'apache.server-status:{0}:user'.format(profile),
''
)
passwd = __salt__['config.get'](
'apache.server-status:{0}:pass'.format(profile),
''
)
realm = __salt__['config.get'](
'apache.server-status:{0}:realm'.format(profile),
''
)
timeout = __salt__['config.get'](
'apache.server-status:{0}:timeout'.format(profile),
5
)
# create authentication handler if configuration exists
if user and passwd:
basic = _HTTPBasicAuthHandler()
basic.add_password(realm=realm, uri=url, user=user, passwd=passwd)
digest = _HTTPDigestAuthHandler()
digest.add_password(realm=realm, uri=url, user=user, passwd=passwd)
_install_opener(_build_opener(basic, digest))
# get http data
url += '?auto'
try:
response = _urlopen(url, timeout=timeout).read().splitlines()
except URLError:
return 'error'
# parse the data
for line in response:
splt = line.split(':', 1)
splt[0] = splt[0].strip()
splt[1] = splt[1].strip()
if splt[0] == 'Scoreboard':
for c in splt[1]:
ret['Scoreboard'][c] += 1
else:
if splt[1].isdigit():
ret[splt[0]] = int(splt[1])
else:
ret[splt[0]] = float(splt[1])
# return the good stuff
return ret | [
"def",
"server_status",
"(",
"profile",
"=",
"'default'",
")",
":",
"ret",
"=",
"{",
"'Scoreboard'",
":",
"{",
"'_'",
":",
"0",
",",
"'S'",
":",
"0",
",",
"'R'",
":",
"0",
",",
"'W'",
":",
"0",
",",
"'K'",
":",
"0",
",",
"'D'",
":",
"0",
",",... | Get Information from the Apache server-status handler
.. note::
The server-status handler is disabled by default.
In order for this function to work it needs to be enabled.
See http://httpd.apache.org/docs/2.2/mod/mod_status.html
The following configuration needs to exists in pillar/grains.
Each entry nested in ``apache.server-status`` is a profile of a vhost/server.
This would give support for multiple apache servers/vhosts.
.. code-block:: yaml
apache.server-status:
default:
url: http://localhost/server-status
user: someuser
pass: password
realm: 'authentication realm for digest passwords'
timeout: 5
CLI Examples:
.. code-block:: bash
salt '*' apache.server_status
salt '*' apache.server_status other-profile | [
"Get",
"Information",
"from",
"the",
"Apache",
"server",
"-",
"status",
"handler"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L300-L400 | train |
saltstack/salt | salt/modules/apache.py | _parse_config | def _parse_config(conf, slot=None):
'''
Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed
'''
ret = cStringIO()
if isinstance(conf, six.string_types):
if slot:
print('{0} {1}'.format(slot, conf), file=ret, end='')
else:
print('{0}'.format(conf), file=ret, end='')
elif isinstance(conf, list):
is_section = False
for item in conf:
if 'this' in item:
is_section = True
slot_this = six.text_type(item['this'])
if is_section:
print('<{0} {1}>'.format(slot, slot_this), file=ret)
for item in conf:
for key, val in item.items():
if key != 'this':
print(_parse_config(val, six.text_type(key)), file=ret)
print('</{0}>'.format(slot), file=ret)
else:
for value in conf:
print(_parse_config(value, six.text_type(slot)), file=ret)
elif isinstance(conf, dict):
try:
print('<{0} {1}>'.format(slot, conf['this']), file=ret)
except KeyError:
raise SaltException('Apache section container "<{0}>" expects attribute. '
'Specify it using key "this".'.format(slot))
for key, value in six.iteritems(conf):
if key != 'this':
if isinstance(value, six.string_types):
print('{0} {1}'.format(key, value), file=ret)
elif isinstance(value, list):
print(_parse_config(value, key), file=ret)
elif isinstance(value, dict):
print(_parse_config(value, key), file=ret)
print('</{0}>'.format(slot), file=ret)
ret.seek(0)
return ret.read() | python | def _parse_config(conf, slot=None):
'''
Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed
'''
ret = cStringIO()
if isinstance(conf, six.string_types):
if slot:
print('{0} {1}'.format(slot, conf), file=ret, end='')
else:
print('{0}'.format(conf), file=ret, end='')
elif isinstance(conf, list):
is_section = False
for item in conf:
if 'this' in item:
is_section = True
slot_this = six.text_type(item['this'])
if is_section:
print('<{0} {1}>'.format(slot, slot_this), file=ret)
for item in conf:
for key, val in item.items():
if key != 'this':
print(_parse_config(val, six.text_type(key)), file=ret)
print('</{0}>'.format(slot), file=ret)
else:
for value in conf:
print(_parse_config(value, six.text_type(slot)), file=ret)
elif isinstance(conf, dict):
try:
print('<{0} {1}>'.format(slot, conf['this']), file=ret)
except KeyError:
raise SaltException('Apache section container "<{0}>" expects attribute. '
'Specify it using key "this".'.format(slot))
for key, value in six.iteritems(conf):
if key != 'this':
if isinstance(value, six.string_types):
print('{0} {1}'.format(key, value), file=ret)
elif isinstance(value, list):
print(_parse_config(value, key), file=ret)
elif isinstance(value, dict):
print(_parse_config(value, key), file=ret)
print('</{0}>'.format(slot), file=ret)
ret.seek(0)
return ret.read() | [
"def",
"_parse_config",
"(",
"conf",
",",
"slot",
"=",
"None",
")",
":",
"ret",
"=",
"cStringIO",
"(",
")",
"if",
"isinstance",
"(",
"conf",
",",
"six",
".",
"string_types",
")",
":",
"if",
"slot",
":",
"print",
"(",
"'{0} {1}'",
".",
"format",
"(",
... | Recursively goes through config structure and builds final Apache configuration
:param conf: defined config structure
:param slot: name of section container if needed | [
"Recursively",
"goes",
"through",
"config",
"structure",
"and",
"builds",
"final",
"Apache",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L403-L449 | train |
saltstack/salt | salt/modules/apache.py | config | def config(name, config, edit=True):
'''
Create VirtualHost configuration files
name
File for the virtual host
config
VirtualHost configurations
.. note::
This function is not meant to be used from the command line.
Config is meant to be an ordered dict of all of the apache configs.
CLI Example:
.. code-block:: bash
salt '*' apache.config /etc/httpd/conf.d/ports.conf config="[{'Listen': '22'}]"
'''
configs = []
for entry in config:
key = next(six.iterkeys(entry))
configs.append(_parse_config(entry[key], key))
# Python auto-correct line endings
configstext = '\n'.join(salt.utils.data.decode(configs))
if edit:
with salt.utils.files.fopen(name, 'w') as configfile:
configfile.write('# This file is managed by Salt.\n')
configfile.write(salt.utils.stringutils.to_str(configstext))
return configstext | python | def config(name, config, edit=True):
'''
Create VirtualHost configuration files
name
File for the virtual host
config
VirtualHost configurations
.. note::
This function is not meant to be used from the command line.
Config is meant to be an ordered dict of all of the apache configs.
CLI Example:
.. code-block:: bash
salt '*' apache.config /etc/httpd/conf.d/ports.conf config="[{'Listen': '22'}]"
'''
configs = []
for entry in config:
key = next(six.iterkeys(entry))
configs.append(_parse_config(entry[key], key))
# Python auto-correct line endings
configstext = '\n'.join(salt.utils.data.decode(configs))
if edit:
with salt.utils.files.fopen(name, 'w') as configfile:
configfile.write('# This file is managed by Salt.\n')
configfile.write(salt.utils.stringutils.to_str(configstext))
return configstext | [
"def",
"config",
"(",
"name",
",",
"config",
",",
"edit",
"=",
"True",
")",
":",
"configs",
"=",
"[",
"]",
"for",
"entry",
"in",
"config",
":",
"key",
"=",
"next",
"(",
"six",
".",
"iterkeys",
"(",
"entry",
")",
")",
"configs",
".",
"append",
"("... | Create VirtualHost configuration files
name
File for the virtual host
config
VirtualHost configurations
.. note::
This function is not meant to be used from the command line.
Config is meant to be an ordered dict of all of the apache configs.
CLI Example:
.. code-block:: bash
salt '*' apache.config /etc/httpd/conf.d/ports.conf config="[{'Listen': '22'}]" | [
"Create",
"VirtualHost",
"configuration",
"files"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apache.py#L452-L484 | train |
saltstack/salt | salt/states/boto_sqs.py | present | def present(
name,
attributes=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the SQS queue exists.
name
Name of the SQS queue.
attributes
A dict of key/value SQS 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': {},
}
r = __salt__['boto_sqs.exists'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(r['error'])
return ret
if r['result']:
ret['comment'].append('SQS queue {0} present.'.format(name))
else:
if __opts__['test']:
ret['result'] = None
ret['comment'].append(
'SQS queue {0} is set to be created.'.format(name),
)
ret['changes'] = {'old': None, 'new': name}
return ret
r = __salt__['boto_sqs.create'](
name,
attributes=attributes,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(
'Failed to create SQS queue {0}: {1}'.format(name, r['error']),
)
return ret
ret['comment'].append('SQS queue {0} created.'.format(name))
ret['changes']['old'] = None
ret['changes']['new'] = name
# Return immediately, as the create call also set all attributes
return ret
if not attributes:
return ret
r = __salt__['boto_sqs.get_attributes'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(
'Failed to get queue attributes: {0}'.format(r['error']),
)
return ret
current_attributes = r['result']
attrs_to_set = {}
for attr, val in six.iteritems(attributes):
_val = current_attributes.get(attr, None)
if attr == 'Policy':
# Normalize by brute force
if isinstance(_val, six.string_types):
_val = salt.utils.json.loads(_val)
if isinstance(val, six.string_types):
val = salt.utils.json.loads(val)
if _val != val:
log.debug('Policies differ:\n%s\n%s', _val, val)
attrs_to_set[attr] = salt.utils.json.dumps(val, sort_keys=True)
elif six.text_type(_val) != six.text_type(val):
log.debug('Attributes differ:\n%s\n%s', _val, val)
attrs_to_set[attr] = val
attr_names = ', '.join(attrs_to_set)
if not attrs_to_set:
ret['comment'].append('Queue attributes already set correctly.')
return ret
final_attributes = current_attributes.copy()
final_attributes.update(attrs_to_set)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper = __utils__['yaml.get_dumper']('IndentedSafeOrderedDumper')
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
attributes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(current_attributes).splitlines(True),
_yaml_safe_dump(final_attributes).splitlines(True),
))
if __opts__['test']:
ret['result'] = None
ret['comment'].append(
'Attribute(s) {0} set to be updated:\n{1}'.format(
attr_names,
attributes_diff,
)
)
ret['changes'] = {'attributes': {'diff': attributes_diff}}
return ret
r = __salt__['boto_sqs.set_attributes'](
name,
attrs_to_set,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(
'Failed to set queue attributes: {0}'.format(r['error']),
)
return ret
ret['comment'].append(
'Updated SQS queue attribute(s) {0}.'.format(attr_names),
)
ret['changes']['attributes'] = {'diff': attributes_diff}
return ret | python | def present(
name,
attributes=None,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the SQS queue exists.
name
Name of the SQS queue.
attributes
A dict of key/value SQS 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': {},
}
r = __salt__['boto_sqs.exists'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(r['error'])
return ret
if r['result']:
ret['comment'].append('SQS queue {0} present.'.format(name))
else:
if __opts__['test']:
ret['result'] = None
ret['comment'].append(
'SQS queue {0} is set to be created.'.format(name),
)
ret['changes'] = {'old': None, 'new': name}
return ret
r = __salt__['boto_sqs.create'](
name,
attributes=attributes,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(
'Failed to create SQS queue {0}: {1}'.format(name, r['error']),
)
return ret
ret['comment'].append('SQS queue {0} created.'.format(name))
ret['changes']['old'] = None
ret['changes']['new'] = name
# Return immediately, as the create call also set all attributes
return ret
if not attributes:
return ret
r = __salt__['boto_sqs.get_attributes'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(
'Failed to get queue attributes: {0}'.format(r['error']),
)
return ret
current_attributes = r['result']
attrs_to_set = {}
for attr, val in six.iteritems(attributes):
_val = current_attributes.get(attr, None)
if attr == 'Policy':
# Normalize by brute force
if isinstance(_val, six.string_types):
_val = salt.utils.json.loads(_val)
if isinstance(val, six.string_types):
val = salt.utils.json.loads(val)
if _val != val:
log.debug('Policies differ:\n%s\n%s', _val, val)
attrs_to_set[attr] = salt.utils.json.dumps(val, sort_keys=True)
elif six.text_type(_val) != six.text_type(val):
log.debug('Attributes differ:\n%s\n%s', _val, val)
attrs_to_set[attr] = val
attr_names = ', '.join(attrs_to_set)
if not attrs_to_set:
ret['comment'].append('Queue attributes already set correctly.')
return ret
final_attributes = current_attributes.copy()
final_attributes.update(attrs_to_set)
def _yaml_safe_dump(attrs):
'''
Safely dump YAML using a readable flow style
'''
dumper = __utils__['yaml.get_dumper']('IndentedSafeOrderedDumper')
return __utils__['yaml.dump'](
attrs,
default_flow_style=False,
Dumper=dumper)
attributes_diff = ''.join(difflib.unified_diff(
_yaml_safe_dump(current_attributes).splitlines(True),
_yaml_safe_dump(final_attributes).splitlines(True),
))
if __opts__['test']:
ret['result'] = None
ret['comment'].append(
'Attribute(s) {0} set to be updated:\n{1}'.format(
attr_names,
attributes_diff,
)
)
ret['changes'] = {'attributes': {'diff': attributes_diff}}
return ret
r = __salt__['boto_sqs.set_attributes'](
name,
attrs_to_set,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'].append(
'Failed to set queue attributes: {0}'.format(r['error']),
)
return ret
ret['comment'].append(
'Updated SQS queue attribute(s) {0}.'.format(attr_names),
)
ret['changes']['attributes'] = {'diff': attributes_diff}
return ret | [
"def",
"present",
"(",
"name",
",",
"attributes",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":... | Ensure the SQS queue exists.
name
Name of the SQS queue.
attributes
A dict of key/value SQS 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",
"SQS",
"queue",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_sqs.py#L82-L250 | train |
saltstack/salt | salt/states/boto_sqs.py | absent | def absent(
name,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the named sqs queue is deleted.
name
Name of the SQS queue.
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': {}}
r = __salt__['boto_sqs.exists'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'] = six.text_type(r['error'])
return ret
if not r['result']:
ret['comment'] = 'SQS queue {0} does not exist in {1}.'.format(
name,
region,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'SQS queue {0} is set to be removed.'.format(name)
ret['changes'] = {'old': name, 'new': None}
return ret
r = __salt__['boto_sqs.delete'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'] = six.text_type(r['error'])
return ret
ret['comment'] = 'SQS queue {0} was deleted.'.format(name)
ret['changes']['old'] = name
ret['changes']['new'] = None
return ret | python | def absent(
name,
region=None,
key=None,
keyid=None,
profile=None,
):
'''
Ensure the named sqs queue is deleted.
name
Name of the SQS queue.
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': {}}
r = __salt__['boto_sqs.exists'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'] = six.text_type(r['error'])
return ret
if not r['result']:
ret['comment'] = 'SQS queue {0} does not exist in {1}.'.format(
name,
region,
)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'SQS queue {0} is set to be removed.'.format(name)
ret['changes'] = {'old': name, 'new': None}
return ret
r = __salt__['boto_sqs.delete'](
name,
region=region,
key=key,
keyid=keyid,
profile=profile,
)
if 'error' in r:
ret['result'] = False
ret['comment'] = six.text_type(r['error'])
return ret
ret['comment'] = 'SQS queue {0} was deleted.'.format(name)
ret['changes']['old'] = name
ret['changes']['new'] = None
return ret | [
"def",
"absent",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",... | Ensure the named sqs queue is deleted.
name
Name of the SQS queue.
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",
"named",
"sqs",
"queue",
"is",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_sqs.py#L253-L321 | train |
saltstack/salt | salt/states/user.py | _group_changes | def _group_changes(cur, wanted, remove=False):
'''
Determine if the groups need to be changed
'''
old = set(cur)
new = set(wanted)
if (remove and old != new) or (not remove and not new.issubset(old)):
return True
return False | python | def _group_changes(cur, wanted, remove=False):
'''
Determine if the groups need to be changed
'''
old = set(cur)
new = set(wanted)
if (remove and old != new) or (not remove and not new.issubset(old)):
return True
return False | [
"def",
"_group_changes",
"(",
"cur",
",",
"wanted",
",",
"remove",
"=",
"False",
")",
":",
"old",
"=",
"set",
"(",
"cur",
")",
"new",
"=",
"set",
"(",
"wanted",
")",
"if",
"(",
"remove",
"and",
"old",
"!=",
"new",
")",
"or",
"(",
"not",
"remove",... | Determine if the groups need to be changed | [
"Determine",
"if",
"the",
"groups",
"need",
"to",
"be",
"changed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/user.py#L44-L52 | train |
saltstack/salt | salt/states/user.py | _changes | def _changes(name,
uid=None,
gid=None,
groups=None,
optional_groups=None,
remove_groups=True,
home=None,
createhome=True,
password=None,
enforce_password=True,
empty_password=False,
shell=None,
fullname='',
roomnumber='',
workphone='',
homephone='',
other='',
loginclass=None,
date=None,
mindays=0,
maxdays=999999,
inactdays=0,
warndays=7,
expire=None,
win_homedrive=None,
win_profile=None,
win_logonscript=None,
win_description=None,
allow_uid_change=False,
allow_gid_change=False):
'''
Return a dict of the changes required for a user if the user is present,
otherwise return False.
Updated in 2015.8.0 to include support for windows homedrive, profile,
logonscript, and description fields.
Updated in 2014.7.0 to include support for shadow attributes, all
attributes supported as integers only.
'''
if 'shadow.info' in __salt__:
lshad = __salt__['shadow.info'](name)
lusr = __salt__['user.info'](name)
if not lusr:
return False
change = {}
if groups is None:
groups = lusr['groups']
wanted_groups = sorted(set((groups or []) + (optional_groups or [])))
if uid and lusr['uid'] != uid:
change['uid'] = uid
if gid is not None and lusr['gid'] not in (gid, __salt__['file.group_to_gid'](gid)):
change['gid'] = gid
default_grp = __salt__['file.gid_to_group'](
gid if gid is not None else lusr['gid']
)
# remove the default group from the list for comparison purposes
if default_grp in lusr['groups']:
lusr['groups'].remove(default_grp)
if name in lusr['groups'] and name not in wanted_groups:
lusr['groups'].remove(name)
# remove default group from wanted_groups, as this requirement is
# already met
if default_grp in wanted_groups:
wanted_groups.remove(default_grp)
if _group_changes(lusr['groups'], wanted_groups, remove_groups):
change['groups'] = wanted_groups
if home and lusr['home'] != home:
change['home'] = home
if createhome:
newhome = home if home else lusr['home']
if newhome is not None and not os.path.isdir(newhome):
change['homeDoesNotExist'] = newhome
if shell and lusr['shell'] != shell:
change['shell'] = shell
if 'shadow.info' in __salt__ and 'shadow.default_hash' in __salt__:
if password and not empty_password:
default_hash = __salt__['shadow.default_hash']()
if lshad['passwd'] == default_hash \
or lshad['passwd'] != default_hash and enforce_password:
if lshad['passwd'] != password:
change['passwd'] = password
if empty_password and lshad['passwd'] != '':
change['empty_password'] = True
if date is not None and lshad['lstchg'] != date:
change['date'] = date
if mindays is not None and lshad['min'] != mindays:
change['mindays'] = mindays
if maxdays is not None and lshad['max'] != maxdays:
change['maxdays'] = maxdays
if inactdays is not None and lshad['inact'] != inactdays:
change['inactdays'] = inactdays
if warndays is not None and lshad['warn'] != warndays:
change['warndays'] = warndays
if expire and lshad['expire'] != expire:
change['expire'] = expire
elif 'shadow.info' in __salt__ and salt.utils.platform.is_windows():
if expire and expire is not -1 and salt.utils.dateutils.strftime(lshad['expire']) != salt.utils.dateutils.strftime(expire):
change['expire'] = expire
# GECOS fields
fullname = salt.utils.data.decode(fullname)
lusr['fullname'] = salt.utils.data.decode(lusr['fullname'])
if fullname is not None and lusr['fullname'] != fullname:
change['fullname'] = fullname
if win_homedrive and lusr['homedrive'] != win_homedrive:
change['homedrive'] = win_homedrive
if win_profile and lusr['profile'] != win_profile:
change['profile'] = win_profile
if win_logonscript and lusr['logonscript'] != win_logonscript:
change['logonscript'] = win_logonscript
if win_description and lusr['description'] != win_description:
change['description'] = win_description
# MacOS doesn't have full GECOS support, so check for the "ch" functions
# and ignore these parameters if these functions do not exist.
if 'user.chroomnumber' in __salt__ \
and roomnumber is not None:
roomnumber = salt.utils.data.decode(roomnumber)
lusr['roomnumber'] = salt.utils.data.decode(lusr['roomnumber'])
if lusr['roomnumber'] != roomnumber:
change['roomnumber'] = roomnumber
if 'user.chworkphone' in __salt__ \
and workphone is not None:
workphone = salt.utils.data.decode(workphone)
lusr['workphone'] = salt.utils.data.decode(lusr['workphone'])
if lusr['workphone'] != workphone:
change['workphone'] = workphone
if 'user.chhomephone' in __salt__ \
and homephone is not None:
homephone = salt.utils.data.decode(homephone)
lusr['homephone'] = salt.utils.data.decode(lusr['homephone'])
if lusr['homephone'] != homephone:
change['homephone'] = homephone
if 'user.chother' in __salt__ and other is not None:
other = salt.utils.data.decode(other)
lusr['other'] = salt.utils.data.decode(lusr['other'])
if lusr['other'] != other:
change['other'] = other
# OpenBSD/FreeBSD login class
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD'):
if loginclass:
if __salt__['user.get_loginclass'](name) != loginclass:
change['loginclass'] = loginclass
errors = []
if not allow_uid_change and 'uid' in change:
errors.append(
'Changing uid ({0} -> {1}) not permitted, set allow_uid_change to '
'True to force this change. Note that this will not change file '
'ownership.'.format(lusr['uid'], uid)
)
if not allow_gid_change and 'gid' in change:
errors.append(
'Changing gid ({0} -> {1}) not permitted, set allow_gid_change to '
'True to force this change. Note that this will not change file '
'ownership.'.format(lusr['gid'], gid)
)
if errors:
raise CommandExecutionError(
'Encountered error checking for needed changes',
info=errors
)
return change | python | def _changes(name,
uid=None,
gid=None,
groups=None,
optional_groups=None,
remove_groups=True,
home=None,
createhome=True,
password=None,
enforce_password=True,
empty_password=False,
shell=None,
fullname='',
roomnumber='',
workphone='',
homephone='',
other='',
loginclass=None,
date=None,
mindays=0,
maxdays=999999,
inactdays=0,
warndays=7,
expire=None,
win_homedrive=None,
win_profile=None,
win_logonscript=None,
win_description=None,
allow_uid_change=False,
allow_gid_change=False):
'''
Return a dict of the changes required for a user if the user is present,
otherwise return False.
Updated in 2015.8.0 to include support for windows homedrive, profile,
logonscript, and description fields.
Updated in 2014.7.0 to include support for shadow attributes, all
attributes supported as integers only.
'''
if 'shadow.info' in __salt__:
lshad = __salt__['shadow.info'](name)
lusr = __salt__['user.info'](name)
if not lusr:
return False
change = {}
if groups is None:
groups = lusr['groups']
wanted_groups = sorted(set((groups or []) + (optional_groups or [])))
if uid and lusr['uid'] != uid:
change['uid'] = uid
if gid is not None and lusr['gid'] not in (gid, __salt__['file.group_to_gid'](gid)):
change['gid'] = gid
default_grp = __salt__['file.gid_to_group'](
gid if gid is not None else lusr['gid']
)
# remove the default group from the list for comparison purposes
if default_grp in lusr['groups']:
lusr['groups'].remove(default_grp)
if name in lusr['groups'] and name not in wanted_groups:
lusr['groups'].remove(name)
# remove default group from wanted_groups, as this requirement is
# already met
if default_grp in wanted_groups:
wanted_groups.remove(default_grp)
if _group_changes(lusr['groups'], wanted_groups, remove_groups):
change['groups'] = wanted_groups
if home and lusr['home'] != home:
change['home'] = home
if createhome:
newhome = home if home else lusr['home']
if newhome is not None and not os.path.isdir(newhome):
change['homeDoesNotExist'] = newhome
if shell and lusr['shell'] != shell:
change['shell'] = shell
if 'shadow.info' in __salt__ and 'shadow.default_hash' in __salt__:
if password and not empty_password:
default_hash = __salt__['shadow.default_hash']()
if lshad['passwd'] == default_hash \
or lshad['passwd'] != default_hash and enforce_password:
if lshad['passwd'] != password:
change['passwd'] = password
if empty_password and lshad['passwd'] != '':
change['empty_password'] = True
if date is not None and lshad['lstchg'] != date:
change['date'] = date
if mindays is not None and lshad['min'] != mindays:
change['mindays'] = mindays
if maxdays is not None and lshad['max'] != maxdays:
change['maxdays'] = maxdays
if inactdays is not None and lshad['inact'] != inactdays:
change['inactdays'] = inactdays
if warndays is not None and lshad['warn'] != warndays:
change['warndays'] = warndays
if expire and lshad['expire'] != expire:
change['expire'] = expire
elif 'shadow.info' in __salt__ and salt.utils.platform.is_windows():
if expire and expire is not -1 and salt.utils.dateutils.strftime(lshad['expire']) != salt.utils.dateutils.strftime(expire):
change['expire'] = expire
# GECOS fields
fullname = salt.utils.data.decode(fullname)
lusr['fullname'] = salt.utils.data.decode(lusr['fullname'])
if fullname is not None and lusr['fullname'] != fullname:
change['fullname'] = fullname
if win_homedrive and lusr['homedrive'] != win_homedrive:
change['homedrive'] = win_homedrive
if win_profile and lusr['profile'] != win_profile:
change['profile'] = win_profile
if win_logonscript and lusr['logonscript'] != win_logonscript:
change['logonscript'] = win_logonscript
if win_description and lusr['description'] != win_description:
change['description'] = win_description
# MacOS doesn't have full GECOS support, so check for the "ch" functions
# and ignore these parameters if these functions do not exist.
if 'user.chroomnumber' in __salt__ \
and roomnumber is not None:
roomnumber = salt.utils.data.decode(roomnumber)
lusr['roomnumber'] = salt.utils.data.decode(lusr['roomnumber'])
if lusr['roomnumber'] != roomnumber:
change['roomnumber'] = roomnumber
if 'user.chworkphone' in __salt__ \
and workphone is not None:
workphone = salt.utils.data.decode(workphone)
lusr['workphone'] = salt.utils.data.decode(lusr['workphone'])
if lusr['workphone'] != workphone:
change['workphone'] = workphone
if 'user.chhomephone' in __salt__ \
and homephone is not None:
homephone = salt.utils.data.decode(homephone)
lusr['homephone'] = salt.utils.data.decode(lusr['homephone'])
if lusr['homephone'] != homephone:
change['homephone'] = homephone
if 'user.chother' in __salt__ and other is not None:
other = salt.utils.data.decode(other)
lusr['other'] = salt.utils.data.decode(lusr['other'])
if lusr['other'] != other:
change['other'] = other
# OpenBSD/FreeBSD login class
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD'):
if loginclass:
if __salt__['user.get_loginclass'](name) != loginclass:
change['loginclass'] = loginclass
errors = []
if not allow_uid_change and 'uid' in change:
errors.append(
'Changing uid ({0} -> {1}) not permitted, set allow_uid_change to '
'True to force this change. Note that this will not change file '
'ownership.'.format(lusr['uid'], uid)
)
if not allow_gid_change and 'gid' in change:
errors.append(
'Changing gid ({0} -> {1}) not permitted, set allow_gid_change to '
'True to force this change. Note that this will not change file '
'ownership.'.format(lusr['gid'], gid)
)
if errors:
raise CommandExecutionError(
'Encountered error checking for needed changes',
info=errors
)
return change | [
"def",
"_changes",
"(",
"name",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"optional_groups",
"=",
"None",
",",
"remove_groups",
"=",
"True",
",",
"home",
"=",
"None",
",",
"createhome",
"=",
"True",
",",
"pass... | Return a dict of the changes required for a user if the user is present,
otherwise return False.
Updated in 2015.8.0 to include support for windows homedrive, profile,
logonscript, and description fields.
Updated in 2014.7.0 to include support for shadow attributes, all
attributes supported as integers only. | [
"Return",
"a",
"dict",
"of",
"the",
"changes",
"required",
"for",
"a",
"user",
"if",
"the",
"user",
"is",
"present",
"otherwise",
"return",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/user.py#L55-L222 | train |
saltstack/salt | salt/states/user.py | present | def present(name,
uid=None,
gid=None,
usergroup=None,
groups=None,
optional_groups=None,
remove_groups=True,
home=None,
createhome=True,
password=None,
hash_password=False,
enforce_password=True,
empty_password=False,
shell=None,
unique=True,
system=False,
fullname=None,
roomnumber=None,
workphone=None,
homephone=None,
other=None,
loginclass=None,
date=None,
mindays=None,
maxdays=None,
inactdays=None,
warndays=None,
expire=None,
win_homedrive=None,
win_profile=None,
win_logonscript=None,
win_description=None,
nologinit=False,
allow_uid_change=False,
allow_gid_change=False):
'''
Ensure that the named user is present with the specified properties
name
The name of the user to manage
uid
The user id to assign. If not specified, and the user does not exist,
then the next available uid will be assigned.
gid
The id of the default group to assign to the user. Either a group name
or gid can be used. If not specified, and the user does not exist, then
the next available gid will be assigned.
allow_uid_change : False
Set to ``True`` to allow the state to update the uid.
.. versionadded:: 2018.3.1
allow_gid_change : False
Set to ``True`` to allow the state to update the gid.
.. versionadded:: 2018.3.1
usergroup
If True, a group with the same name as the user will be created. If
False, a group with the same name as the user will not be created. The
default is distribution-specific. See the USERGROUPS_ENAB section of
the login.defs(5) man page.
.. note::
Only supported on GNU/Linux distributions
.. versionadded:: Fluorine
groups
A list of groups to assign the user to, pass a list object. If a group
specified here does not exist on the minion, the state will fail.
If set to the empty list, the user will be removed from all groups
except the default group. If unset, salt will assume current groups
are still wanted (see issue #28706).
optional_groups
A list of groups to assign the user to, pass a list object. If a group
specified here does not exist on the minion, the state will silently
ignore it.
NOTE: If the same group is specified in both "groups" and
"optional_groups", then it will be assumed to be required and not optional.
remove_groups
Remove groups that the user is a member of that weren't specified in
the state, Default is ``True``.
home
The custom login directory of user. Uses default value of underlying
system if not set. Notice that this directory does not have to exist.
This also the location of the home directory to create if createhome is
set to True.
createhome : True
If set to ``False``, the home directory will not be created if it
doesn't already exist.
.. warning::
Not supported on Windows or Mac OS.
Additionally, parent directories will *not* be created. The parent
directory for ``home`` must already exist.
nologinit : False
If set to ``True``, it will not add the user to lastlog and faillog
databases.
.. note::
Not supported on Windows or Mac OS.
password
A password hash to set for the user. This field is only supported on
Linux, FreeBSD, NetBSD, OpenBSD, and Solaris. If the ``empty_password``
argument is set to ``True`` then ``password`` is ignored.
For Windows this is the plain text password.
For Linux, the hash can be generated with ``mkpasswd -m sha-256``.
.. versionchanged:: 0.16.0
BSD support added.
hash_password
Set to True to hash the clear text password. Default is ``False``.
enforce_password
Set to False to keep the password from being changed if it has already
been set and the password hash differs from what is specified in the
"password" field. This option will be ignored if "password" is not
specified, Default is ``True``.
empty_password
Set to True to enable password-less login for user, Default is ``False``.
shell
The login shell, defaults to the system default shell
unique
Require a unique UID, Default is ``True``.
system
Choose UID in the range of FIRST_SYSTEM_UID and LAST_SYSTEM_UID, Default is
``False``.
loginclass
The login class, defaults to empty
(BSD only)
User comment field (GECOS) support (currently Linux, BSD, and MacOS
only):
The below values should be specified as strings to avoid ambiguities when
the values are loaded. (Especially the phone and room number fields which
are likely to contain numeric data)
fullname
The user's full name
roomnumber
The user's room number (not supported in MacOS)
workphone
The user's work phone number (not supported in MacOS)
homephone
The user's home phone number (not supported in MacOS)
other
The user's other attribute (not supported in MacOS)
If GECOS field contains more than 4 commas, this field will have the rest of 'em
.. versionchanged:: 2014.7.0
Shadow attribute support added.
Shadow attributes support (currently Linux only):
The below values should be specified as integers.
date
Date of last change of password, represented in days since epoch
(January 1, 1970).
mindays
The minimum number of days between password changes.
maxdays
The maximum number of days between password changes.
inactdays
The number of days after a password expires before an account is
locked.
warndays
Number of days prior to maxdays to warn users.
expire
Date that account expires, represented in days since epoch (January 1,
1970).
The below parameters apply to windows only:
win_homedrive (Windows Only)
The drive letter to use for the home directory. If not specified the
home directory will be a unc path. Otherwise the home directory will be
mapped to the specified drive. Must be a letter followed by a colon.
Because of the colon, the value must be surrounded by single quotes. ie:
- win_homedrive: 'U:
.. versionchanged:: 2015.8.0
win_profile (Windows Only)
The custom profile directory of the user. Uses default value of
underlying system if not set.
.. versionchanged:: 2015.8.0
win_logonscript (Windows Only)
The full path to the logon script to run when the user logs in.
.. versionchanged:: 2015.8.0
win_description (Windows Only)
A brief description of the purpose of the users account.
.. versionchanged:: 2015.8.0
'''
# First check if a password is set. If password is set, check if
# hash_password is True, then hash it.
if password and hash_password:
log.debug('Hashing a clear text password')
# in case a password is already set, it will contain a Salt
# which should be re-used to generate the new hash, other-
# wise the Salt will be generated randomly, causing the
# hash to change each time and thereby making the
# user.present state non-idempotent.
algorithms = {
'1': 'md5',
'2a': 'blowfish',
'5': 'sha256',
'6': 'sha512',
}
try:
_, algo, shadow_salt, shadow_hash = __salt__['shadow.info'](name)['passwd'].split('$', 4)
if algo == '1':
log.warning('Using MD5 for hashing passwords is considered insecure!')
log.debug('Re-using existing shadow salt for hashing password using %s', algorithms.get(algo))
password = __salt__['shadow.gen_password'](password, crypt_salt=shadow_salt, algorithm=algorithms.get(algo))
except ValueError:
log.info('No existing shadow salt found, defaulting to a randomly generated new one')
password = __salt__['shadow.gen_password'](password)
if fullname is not None:
fullname = salt.utils.data.decode(fullname)
if roomnumber is not None:
roomnumber = salt.utils.data.decode(roomnumber)
if workphone is not None:
workphone = salt.utils.data.decode(workphone)
if homephone is not None:
homephone = salt.utils.data.decode(homephone)
if other is not None:
other = salt.utils.data.decode(other)
# createhome not supported on Windows or Mac
if __grains__['kernel'] in ('Darwin', 'Windows'):
createhome = False
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0} is present and up to date'.format(name)}
# the comma is used to separate field in GECOS, thus resulting into
# salt adding the end of fullname each time this function is called
for gecos_field in [fullname, roomnumber, workphone]:
if isinstance(gecos_field, string_types) and ',' in gecos_field:
ret['comment'] = "Unsupported char ',' in {0}".format(gecos_field)
ret['result'] = False
return ret
if groups:
missing_groups = [x for x in groups if not __salt__['group.info'](x)]
if missing_groups:
ret['comment'] = 'The following group(s) are not present: ' \
'{0}'.format(','.join(missing_groups))
ret['result'] = False
return ret
if optional_groups:
present_optgroups = [x for x in optional_groups
if __salt__['group.info'](x)]
for missing_optgroup in [x for x in optional_groups
if x not in present_optgroups]:
log.debug(
'Optional group "%s" for user "%s" is not present',
missing_optgroup, name
)
else:
present_optgroups = None
# Log a warning for all groups specified in both "groups" and
# "optional_groups" lists.
if groups and optional_groups:
for isected in set(groups).intersection(optional_groups):
log.warning(
'Group "%s" specified in both groups and optional_groups '
'for user %s', isected, name
)
# If usergroup was specified, we'll also be creating a new
# group. We should report this change without setting the gid
# variable.
if usergroup and __salt__['file.group_to_gid'](name) != '':
changes_gid = name
else:
changes_gid = gid
try:
changes = _changes(name,
uid,
changes_gid,
groups,
present_optgroups,
remove_groups,
home,
createhome,
password,
enforce_password,
empty_password,
shell,
fullname,
roomnumber,
workphone,
homephone,
other,
loginclass,
date,
mindays,
maxdays,
inactdays,
warndays,
expire,
win_homedrive,
win_profile,
win_logonscript,
win_description,
allow_uid_change,
allow_gid_change)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if changes:
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('The following user attributes are set to be '
'changed:\n')
for key, val in iteritems(changes):
if key == 'passwd':
val = 'XXX-REDACTED-XXX'
elif key == 'group' and not remove_groups:
key = 'ensure groups'
ret['comment'] += '{0}: {1}\n'.format(key, val)
return ret
# The user is present
if 'shadow.info' in __salt__:
lshad = __salt__['shadow.info'](name)
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD'):
lcpre = __salt__['user.get_loginclass'](name)
pre = __salt__['user.info'](name)
for key, val in iteritems(changes):
if key == 'passwd' and not empty_password:
__salt__['shadow.set_password'](name, password)
continue
if key == 'passwd' and empty_password:
log.warning("No password will be set when empty_password=True")
continue
if key == 'empty_password' and val:
__salt__['shadow.del_password'](name)
continue
if key == 'date':
__salt__['shadow.set_date'](name, date)
continue
# run chhome once to avoid any possible bad side-effect
if key == 'home' and 'homeDoesNotExist' not in changes:
if __grains__['kernel'] in ('Darwin', 'Windows'):
__salt__['user.chhome'](name, val)
else:
__salt__['user.chhome'](name, val, persist=False)
continue
if key == 'homeDoesNotExist':
if __grains__['kernel'] in ('Darwin', 'Windows'):
__salt__['user.chhome'](name, val)
else:
__salt__['user.chhome'](name, val, persist=True)
if not os.path.isdir(val):
__salt__['file.mkdir'](val, pre['uid'], pre['gid'], 0o755)
continue
if key == 'mindays':
__salt__['shadow.set_mindays'](name, mindays)
continue
if key == 'maxdays':
__salt__['shadow.set_maxdays'](name, maxdays)
continue
if key == 'inactdays':
__salt__['shadow.set_inactdays'](name, inactdays)
continue
if key == 'warndays':
__salt__['shadow.set_warndays'](name, warndays)
continue
if key == 'expire':
__salt__['shadow.set_expire'](name, expire)
continue
if key == 'win_homedrive':
__salt__['user.update'](name=name, homedrive=val)
continue
if key == 'win_profile':
__salt__['user.update'](name=name, profile=val)
continue
if key == 'win_logonscript':
__salt__['user.update'](name=name, logonscript=val)
continue
if key == 'win_description':
__salt__['user.update'](name=name, description=val)
continue
if key == 'groups':
__salt__['user.ch{0}'.format(key)](
name, val, not remove_groups
)
else:
__salt__['user.ch{0}'.format(key)](name, val)
post = __salt__['user.info'](name)
spost = {}
if 'shadow.info' in __salt__ and lshad['passwd'] != password:
spost = __salt__['shadow.info'](name)
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD'):
lcpost = __salt__['user.get_loginclass'](name)
# See if anything changed
for key in post:
if post[key] != pre[key]:
ret['changes'][key] = post[key]
if 'shadow.info' in __salt__:
for key in spost:
if lshad[key] != spost[key]:
if key == 'passwd':
ret['changes'][key] = 'XXX-REDACTED-XXX'
else:
ret['changes'][key] = spost[key]
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD') and lcpost != lcpre:
ret['changes']['loginclass'] = lcpost
if ret['changes']:
ret['comment'] = 'Updated user {0}'.format(name)
changes = _changes(name,
uid,
gid,
groups,
present_optgroups,
remove_groups,
home,
createhome,
password,
enforce_password,
empty_password,
shell,
fullname,
roomnumber,
workphone,
homephone,
other,
loginclass,
date,
mindays,
maxdays,
inactdays,
warndays,
expire,
win_homedrive,
win_profile,
win_logonscript,
win_description,
allow_uid_change=True,
allow_gid_change=True)
# allow_uid_change and allow_gid_change passed as True to avoid race
# conditions where a uid/gid is modified outside of Salt. If an
# unauthorized change was requested, it would have been caught the
# first time we ran _changes().
if changes:
ret['comment'] = 'These values could not be changed: {0}'.format(
changes
)
ret['result'] = False
return ret
if changes is False:
# The user is not present, make it!
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} set to be added'.format(name)
return ret
if groups and present_optgroups:
groups.extend(present_optgroups)
elif present_optgroups:
groups = present_optgroups[:]
# Setup params specific to Linux and Windows to be passed to the
# add.user function
if not salt.utils.platform.is_windows():
params = {'name': name,
'uid': uid,
'gid': gid,
'groups': groups,
'home': home,
'shell': shell,
'unique': unique,
'system': system,
'fullname': fullname,
'roomnumber': roomnumber,
'workphone': workphone,
'homephone': homephone,
'other': other,
'createhome': createhome,
'nologinit': nologinit,
'loginclass': loginclass,
'usergroup': usergroup}
else:
params = ({'name': name,
'password': password,
'fullname': fullname,
'description': win_description,
'groups': groups,
'home': home,
'homedrive': win_homedrive,
'profile': win_profile,
'logonscript': win_logonscript})
if __salt__['user.add'](**params):
ret['comment'] = 'New user {0} created'.format(name)
ret['changes'] = __salt__['user.info'](name)
if not createhome:
# pwd incorrectly reports presence of home
ret['changes']['home'] = ''
if 'shadow.info' in __salt__ \
and not salt.utils.platform.is_windows() \
and not salt.utils.platform.is_darwin():
if password and not empty_password:
__salt__['shadow.set_password'](name, password)
spost = __salt__['shadow.info'](name)
if spost['passwd'] != password:
ret['comment'] = 'User {0} created but failed to set' \
' password to' \
' {1}'.format(name, 'XXX-REDACTED-XXX')
ret['result'] = False
ret['changes']['password'] = 'XXX-REDACTED-XXX'
if empty_password and not password:
__salt__['shadow.del_password'](name)
spost = __salt__['shadow.info'](name)
if spost['passwd'] != '':
ret['comment'] = 'User {0} created but failed to ' \
'empty password'.format(name)
ret['result'] = False
ret['changes']['password'] = ''
if date is not None:
__salt__['shadow.set_date'](name, date)
spost = __salt__['shadow.info'](name)
if spost['lstchg'] != date:
ret['comment'] = 'User {0} created but failed to set' \
' last change date to' \
' {1}'.format(name, date)
ret['result'] = False
ret['changes']['date'] = date
if mindays:
__salt__['shadow.set_mindays'](name, mindays)
spost = __salt__['shadow.info'](name)
if spost['min'] != mindays:
ret['comment'] = 'User {0} created but failed to set' \
' minimum days to' \
' {1}'.format(name, mindays)
ret['result'] = False
ret['changes']['mindays'] = mindays
if maxdays:
__salt__['shadow.set_maxdays'](name, maxdays)
spost = __salt__['shadow.info'](name)
if spost['max'] != maxdays:
ret['comment'] = 'User {0} created but failed to set' \
' maximum days to' \
' {1}'.format(name, maxdays)
ret['result'] = False
ret['changes']['maxdays'] = maxdays
if inactdays:
__salt__['shadow.set_inactdays'](name, inactdays)
spost = __salt__['shadow.info'](name)
if spost['inact'] != inactdays:
ret['comment'] = 'User {0} created but failed to set' \
' inactive days to' \
' {1}'.format(name, inactdays)
ret['result'] = False
ret['changes']['inactdays'] = inactdays
if warndays:
__salt__['shadow.set_warndays'](name, warndays)
spost = __salt__['shadow.info'](name)
if spost['warn'] != warndays:
ret['comment'] = 'User {0} created but failed to set' \
' warn days to' \
' {1}'.format(name, warndays)
ret['result'] = False
ret['changes']['warndays'] = warndays
if expire:
__salt__['shadow.set_expire'](name, expire)
spost = __salt__['shadow.info'](name)
if spost['expire'] != expire:
ret['comment'] = 'User {0} created but failed to set' \
' expire days to' \
' {1}'.format(name, expire)
ret['result'] = False
ret['changes']['expire'] = expire
elif salt.utils.platform.is_windows():
if password and not empty_password:
if not __salt__['user.setpassword'](name, password):
ret['comment'] = 'User {0} created but failed to set' \
' password to' \
' {1}'.format(name, 'XXX-REDACTED-XXX')
ret['result'] = False
ret['changes']['passwd'] = 'XXX-REDACTED-XXX'
if expire:
__salt__['shadow.set_expire'](name, expire)
spost = __salt__['shadow.info'](name)
if salt.utils.dateutils.strftime(spost['expire']) != salt.utils.dateutils.strftime(expire):
ret['comment'] = 'User {0} created but failed to set' \
' expire days to' \
' {1}'.format(name, expire)
ret['result'] = False
ret['changes']['expiration_date'] = spost['expire']
elif salt.utils.platform.is_darwin() and password and not empty_password:
if not __salt__['shadow.set_password'](name, password):
ret['comment'] = 'User {0} created but failed to set' \
' password to' \
' {1}'.format(name, 'XXX-REDACTED-XXX')
ret['result'] = False
ret['changes']['passwd'] = 'XXX-REDACTED-XXX'
else:
ret['comment'] = 'Failed to create new user {0}'.format(name)
ret['result'] = False
return ret | python | def present(name,
uid=None,
gid=None,
usergroup=None,
groups=None,
optional_groups=None,
remove_groups=True,
home=None,
createhome=True,
password=None,
hash_password=False,
enforce_password=True,
empty_password=False,
shell=None,
unique=True,
system=False,
fullname=None,
roomnumber=None,
workphone=None,
homephone=None,
other=None,
loginclass=None,
date=None,
mindays=None,
maxdays=None,
inactdays=None,
warndays=None,
expire=None,
win_homedrive=None,
win_profile=None,
win_logonscript=None,
win_description=None,
nologinit=False,
allow_uid_change=False,
allow_gid_change=False):
'''
Ensure that the named user is present with the specified properties
name
The name of the user to manage
uid
The user id to assign. If not specified, and the user does not exist,
then the next available uid will be assigned.
gid
The id of the default group to assign to the user. Either a group name
or gid can be used. If not specified, and the user does not exist, then
the next available gid will be assigned.
allow_uid_change : False
Set to ``True`` to allow the state to update the uid.
.. versionadded:: 2018.3.1
allow_gid_change : False
Set to ``True`` to allow the state to update the gid.
.. versionadded:: 2018.3.1
usergroup
If True, a group with the same name as the user will be created. If
False, a group with the same name as the user will not be created. The
default is distribution-specific. See the USERGROUPS_ENAB section of
the login.defs(5) man page.
.. note::
Only supported on GNU/Linux distributions
.. versionadded:: Fluorine
groups
A list of groups to assign the user to, pass a list object. If a group
specified here does not exist on the minion, the state will fail.
If set to the empty list, the user will be removed from all groups
except the default group. If unset, salt will assume current groups
are still wanted (see issue #28706).
optional_groups
A list of groups to assign the user to, pass a list object. If a group
specified here does not exist on the minion, the state will silently
ignore it.
NOTE: If the same group is specified in both "groups" and
"optional_groups", then it will be assumed to be required and not optional.
remove_groups
Remove groups that the user is a member of that weren't specified in
the state, Default is ``True``.
home
The custom login directory of user. Uses default value of underlying
system if not set. Notice that this directory does not have to exist.
This also the location of the home directory to create if createhome is
set to True.
createhome : True
If set to ``False``, the home directory will not be created if it
doesn't already exist.
.. warning::
Not supported on Windows or Mac OS.
Additionally, parent directories will *not* be created. The parent
directory for ``home`` must already exist.
nologinit : False
If set to ``True``, it will not add the user to lastlog and faillog
databases.
.. note::
Not supported on Windows or Mac OS.
password
A password hash to set for the user. This field is only supported on
Linux, FreeBSD, NetBSD, OpenBSD, and Solaris. If the ``empty_password``
argument is set to ``True`` then ``password`` is ignored.
For Windows this is the plain text password.
For Linux, the hash can be generated with ``mkpasswd -m sha-256``.
.. versionchanged:: 0.16.0
BSD support added.
hash_password
Set to True to hash the clear text password. Default is ``False``.
enforce_password
Set to False to keep the password from being changed if it has already
been set and the password hash differs from what is specified in the
"password" field. This option will be ignored if "password" is not
specified, Default is ``True``.
empty_password
Set to True to enable password-less login for user, Default is ``False``.
shell
The login shell, defaults to the system default shell
unique
Require a unique UID, Default is ``True``.
system
Choose UID in the range of FIRST_SYSTEM_UID and LAST_SYSTEM_UID, Default is
``False``.
loginclass
The login class, defaults to empty
(BSD only)
User comment field (GECOS) support (currently Linux, BSD, and MacOS
only):
The below values should be specified as strings to avoid ambiguities when
the values are loaded. (Especially the phone and room number fields which
are likely to contain numeric data)
fullname
The user's full name
roomnumber
The user's room number (not supported in MacOS)
workphone
The user's work phone number (not supported in MacOS)
homephone
The user's home phone number (not supported in MacOS)
other
The user's other attribute (not supported in MacOS)
If GECOS field contains more than 4 commas, this field will have the rest of 'em
.. versionchanged:: 2014.7.0
Shadow attribute support added.
Shadow attributes support (currently Linux only):
The below values should be specified as integers.
date
Date of last change of password, represented in days since epoch
(January 1, 1970).
mindays
The minimum number of days between password changes.
maxdays
The maximum number of days between password changes.
inactdays
The number of days after a password expires before an account is
locked.
warndays
Number of days prior to maxdays to warn users.
expire
Date that account expires, represented in days since epoch (January 1,
1970).
The below parameters apply to windows only:
win_homedrive (Windows Only)
The drive letter to use for the home directory. If not specified the
home directory will be a unc path. Otherwise the home directory will be
mapped to the specified drive. Must be a letter followed by a colon.
Because of the colon, the value must be surrounded by single quotes. ie:
- win_homedrive: 'U:
.. versionchanged:: 2015.8.0
win_profile (Windows Only)
The custom profile directory of the user. Uses default value of
underlying system if not set.
.. versionchanged:: 2015.8.0
win_logonscript (Windows Only)
The full path to the logon script to run when the user logs in.
.. versionchanged:: 2015.8.0
win_description (Windows Only)
A brief description of the purpose of the users account.
.. versionchanged:: 2015.8.0
'''
# First check if a password is set. If password is set, check if
# hash_password is True, then hash it.
if password and hash_password:
log.debug('Hashing a clear text password')
# in case a password is already set, it will contain a Salt
# which should be re-used to generate the new hash, other-
# wise the Salt will be generated randomly, causing the
# hash to change each time and thereby making the
# user.present state non-idempotent.
algorithms = {
'1': 'md5',
'2a': 'blowfish',
'5': 'sha256',
'6': 'sha512',
}
try:
_, algo, shadow_salt, shadow_hash = __salt__['shadow.info'](name)['passwd'].split('$', 4)
if algo == '1':
log.warning('Using MD5 for hashing passwords is considered insecure!')
log.debug('Re-using existing shadow salt for hashing password using %s', algorithms.get(algo))
password = __salt__['shadow.gen_password'](password, crypt_salt=shadow_salt, algorithm=algorithms.get(algo))
except ValueError:
log.info('No existing shadow salt found, defaulting to a randomly generated new one')
password = __salt__['shadow.gen_password'](password)
if fullname is not None:
fullname = salt.utils.data.decode(fullname)
if roomnumber is not None:
roomnumber = salt.utils.data.decode(roomnumber)
if workphone is not None:
workphone = salt.utils.data.decode(workphone)
if homephone is not None:
homephone = salt.utils.data.decode(homephone)
if other is not None:
other = salt.utils.data.decode(other)
# createhome not supported on Windows or Mac
if __grains__['kernel'] in ('Darwin', 'Windows'):
createhome = False
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'User {0} is present and up to date'.format(name)}
# the comma is used to separate field in GECOS, thus resulting into
# salt adding the end of fullname each time this function is called
for gecos_field in [fullname, roomnumber, workphone]:
if isinstance(gecos_field, string_types) and ',' in gecos_field:
ret['comment'] = "Unsupported char ',' in {0}".format(gecos_field)
ret['result'] = False
return ret
if groups:
missing_groups = [x for x in groups if not __salt__['group.info'](x)]
if missing_groups:
ret['comment'] = 'The following group(s) are not present: ' \
'{0}'.format(','.join(missing_groups))
ret['result'] = False
return ret
if optional_groups:
present_optgroups = [x for x in optional_groups
if __salt__['group.info'](x)]
for missing_optgroup in [x for x in optional_groups
if x not in present_optgroups]:
log.debug(
'Optional group "%s" for user "%s" is not present',
missing_optgroup, name
)
else:
present_optgroups = None
# Log a warning for all groups specified in both "groups" and
# "optional_groups" lists.
if groups and optional_groups:
for isected in set(groups).intersection(optional_groups):
log.warning(
'Group "%s" specified in both groups and optional_groups '
'for user %s', isected, name
)
# If usergroup was specified, we'll also be creating a new
# group. We should report this change without setting the gid
# variable.
if usergroup and __salt__['file.group_to_gid'](name) != '':
changes_gid = name
else:
changes_gid = gid
try:
changes = _changes(name,
uid,
changes_gid,
groups,
present_optgroups,
remove_groups,
home,
createhome,
password,
enforce_password,
empty_password,
shell,
fullname,
roomnumber,
workphone,
homephone,
other,
loginclass,
date,
mindays,
maxdays,
inactdays,
warndays,
expire,
win_homedrive,
win_profile,
win_logonscript,
win_description,
allow_uid_change,
allow_gid_change)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = exc.strerror
return ret
if changes:
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('The following user attributes are set to be '
'changed:\n')
for key, val in iteritems(changes):
if key == 'passwd':
val = 'XXX-REDACTED-XXX'
elif key == 'group' and not remove_groups:
key = 'ensure groups'
ret['comment'] += '{0}: {1}\n'.format(key, val)
return ret
# The user is present
if 'shadow.info' in __salt__:
lshad = __salt__['shadow.info'](name)
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD'):
lcpre = __salt__['user.get_loginclass'](name)
pre = __salt__['user.info'](name)
for key, val in iteritems(changes):
if key == 'passwd' and not empty_password:
__salt__['shadow.set_password'](name, password)
continue
if key == 'passwd' and empty_password:
log.warning("No password will be set when empty_password=True")
continue
if key == 'empty_password' and val:
__salt__['shadow.del_password'](name)
continue
if key == 'date':
__salt__['shadow.set_date'](name, date)
continue
# run chhome once to avoid any possible bad side-effect
if key == 'home' and 'homeDoesNotExist' not in changes:
if __grains__['kernel'] in ('Darwin', 'Windows'):
__salt__['user.chhome'](name, val)
else:
__salt__['user.chhome'](name, val, persist=False)
continue
if key == 'homeDoesNotExist':
if __grains__['kernel'] in ('Darwin', 'Windows'):
__salt__['user.chhome'](name, val)
else:
__salt__['user.chhome'](name, val, persist=True)
if not os.path.isdir(val):
__salt__['file.mkdir'](val, pre['uid'], pre['gid'], 0o755)
continue
if key == 'mindays':
__salt__['shadow.set_mindays'](name, mindays)
continue
if key == 'maxdays':
__salt__['shadow.set_maxdays'](name, maxdays)
continue
if key == 'inactdays':
__salt__['shadow.set_inactdays'](name, inactdays)
continue
if key == 'warndays':
__salt__['shadow.set_warndays'](name, warndays)
continue
if key == 'expire':
__salt__['shadow.set_expire'](name, expire)
continue
if key == 'win_homedrive':
__salt__['user.update'](name=name, homedrive=val)
continue
if key == 'win_profile':
__salt__['user.update'](name=name, profile=val)
continue
if key == 'win_logonscript':
__salt__['user.update'](name=name, logonscript=val)
continue
if key == 'win_description':
__salt__['user.update'](name=name, description=val)
continue
if key == 'groups':
__salt__['user.ch{0}'.format(key)](
name, val, not remove_groups
)
else:
__salt__['user.ch{0}'.format(key)](name, val)
post = __salt__['user.info'](name)
spost = {}
if 'shadow.info' in __salt__ and lshad['passwd'] != password:
spost = __salt__['shadow.info'](name)
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD'):
lcpost = __salt__['user.get_loginclass'](name)
# See if anything changed
for key in post:
if post[key] != pre[key]:
ret['changes'][key] = post[key]
if 'shadow.info' in __salt__:
for key in spost:
if lshad[key] != spost[key]:
if key == 'passwd':
ret['changes'][key] = 'XXX-REDACTED-XXX'
else:
ret['changes'][key] = spost[key]
if __grains__['kernel'] in ('OpenBSD', 'FreeBSD') and lcpost != lcpre:
ret['changes']['loginclass'] = lcpost
if ret['changes']:
ret['comment'] = 'Updated user {0}'.format(name)
changes = _changes(name,
uid,
gid,
groups,
present_optgroups,
remove_groups,
home,
createhome,
password,
enforce_password,
empty_password,
shell,
fullname,
roomnumber,
workphone,
homephone,
other,
loginclass,
date,
mindays,
maxdays,
inactdays,
warndays,
expire,
win_homedrive,
win_profile,
win_logonscript,
win_description,
allow_uid_change=True,
allow_gid_change=True)
# allow_uid_change and allow_gid_change passed as True to avoid race
# conditions where a uid/gid is modified outside of Salt. If an
# unauthorized change was requested, it would have been caught the
# first time we ran _changes().
if changes:
ret['comment'] = 'These values could not be changed: {0}'.format(
changes
)
ret['result'] = False
return ret
if changes is False:
# The user is not present, make it!
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} set to be added'.format(name)
return ret
if groups and present_optgroups:
groups.extend(present_optgroups)
elif present_optgroups:
groups = present_optgroups[:]
# Setup params specific to Linux and Windows to be passed to the
# add.user function
if not salt.utils.platform.is_windows():
params = {'name': name,
'uid': uid,
'gid': gid,
'groups': groups,
'home': home,
'shell': shell,
'unique': unique,
'system': system,
'fullname': fullname,
'roomnumber': roomnumber,
'workphone': workphone,
'homephone': homephone,
'other': other,
'createhome': createhome,
'nologinit': nologinit,
'loginclass': loginclass,
'usergroup': usergroup}
else:
params = ({'name': name,
'password': password,
'fullname': fullname,
'description': win_description,
'groups': groups,
'home': home,
'homedrive': win_homedrive,
'profile': win_profile,
'logonscript': win_logonscript})
if __salt__['user.add'](**params):
ret['comment'] = 'New user {0} created'.format(name)
ret['changes'] = __salt__['user.info'](name)
if not createhome:
# pwd incorrectly reports presence of home
ret['changes']['home'] = ''
if 'shadow.info' in __salt__ \
and not salt.utils.platform.is_windows() \
and not salt.utils.platform.is_darwin():
if password and not empty_password:
__salt__['shadow.set_password'](name, password)
spost = __salt__['shadow.info'](name)
if spost['passwd'] != password:
ret['comment'] = 'User {0} created but failed to set' \
' password to' \
' {1}'.format(name, 'XXX-REDACTED-XXX')
ret['result'] = False
ret['changes']['password'] = 'XXX-REDACTED-XXX'
if empty_password and not password:
__salt__['shadow.del_password'](name)
spost = __salt__['shadow.info'](name)
if spost['passwd'] != '':
ret['comment'] = 'User {0} created but failed to ' \
'empty password'.format(name)
ret['result'] = False
ret['changes']['password'] = ''
if date is not None:
__salt__['shadow.set_date'](name, date)
spost = __salt__['shadow.info'](name)
if spost['lstchg'] != date:
ret['comment'] = 'User {0} created but failed to set' \
' last change date to' \
' {1}'.format(name, date)
ret['result'] = False
ret['changes']['date'] = date
if mindays:
__salt__['shadow.set_mindays'](name, mindays)
spost = __salt__['shadow.info'](name)
if spost['min'] != mindays:
ret['comment'] = 'User {0} created but failed to set' \
' minimum days to' \
' {1}'.format(name, mindays)
ret['result'] = False
ret['changes']['mindays'] = mindays
if maxdays:
__salt__['shadow.set_maxdays'](name, maxdays)
spost = __salt__['shadow.info'](name)
if spost['max'] != maxdays:
ret['comment'] = 'User {0} created but failed to set' \
' maximum days to' \
' {1}'.format(name, maxdays)
ret['result'] = False
ret['changes']['maxdays'] = maxdays
if inactdays:
__salt__['shadow.set_inactdays'](name, inactdays)
spost = __salt__['shadow.info'](name)
if spost['inact'] != inactdays:
ret['comment'] = 'User {0} created but failed to set' \
' inactive days to' \
' {1}'.format(name, inactdays)
ret['result'] = False
ret['changes']['inactdays'] = inactdays
if warndays:
__salt__['shadow.set_warndays'](name, warndays)
spost = __salt__['shadow.info'](name)
if spost['warn'] != warndays:
ret['comment'] = 'User {0} created but failed to set' \
' warn days to' \
' {1}'.format(name, warndays)
ret['result'] = False
ret['changes']['warndays'] = warndays
if expire:
__salt__['shadow.set_expire'](name, expire)
spost = __salt__['shadow.info'](name)
if spost['expire'] != expire:
ret['comment'] = 'User {0} created but failed to set' \
' expire days to' \
' {1}'.format(name, expire)
ret['result'] = False
ret['changes']['expire'] = expire
elif salt.utils.platform.is_windows():
if password and not empty_password:
if not __salt__['user.setpassword'](name, password):
ret['comment'] = 'User {0} created but failed to set' \
' password to' \
' {1}'.format(name, 'XXX-REDACTED-XXX')
ret['result'] = False
ret['changes']['passwd'] = 'XXX-REDACTED-XXX'
if expire:
__salt__['shadow.set_expire'](name, expire)
spost = __salt__['shadow.info'](name)
if salt.utils.dateutils.strftime(spost['expire']) != salt.utils.dateutils.strftime(expire):
ret['comment'] = 'User {0} created but failed to set' \
' expire days to' \
' {1}'.format(name, expire)
ret['result'] = False
ret['changes']['expiration_date'] = spost['expire']
elif salt.utils.platform.is_darwin() and password and not empty_password:
if not __salt__['shadow.set_password'](name, password):
ret['comment'] = 'User {0} created but failed to set' \
' password to' \
' {1}'.format(name, 'XXX-REDACTED-XXX')
ret['result'] = False
ret['changes']['passwd'] = 'XXX-REDACTED-XXX'
else:
ret['comment'] = 'Failed to create new user {0}'.format(name)
ret['result'] = False
return ret | [
"def",
"present",
"(",
"name",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"usergroup",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"optional_groups",
"=",
"None",
",",
"remove_groups",
"=",
"True",
",",
"home",
"=",
"None",
",",
"create... | Ensure that the named user is present with the specified properties
name
The name of the user to manage
uid
The user id to assign. If not specified, and the user does not exist,
then the next available uid will be assigned.
gid
The id of the default group to assign to the user. Either a group name
or gid can be used. If not specified, and the user does not exist, then
the next available gid will be assigned.
allow_uid_change : False
Set to ``True`` to allow the state to update the uid.
.. versionadded:: 2018.3.1
allow_gid_change : False
Set to ``True`` to allow the state to update the gid.
.. versionadded:: 2018.3.1
usergroup
If True, a group with the same name as the user will be created. If
False, a group with the same name as the user will not be created. The
default is distribution-specific. See the USERGROUPS_ENAB section of
the login.defs(5) man page.
.. note::
Only supported on GNU/Linux distributions
.. versionadded:: Fluorine
groups
A list of groups to assign the user to, pass a list object. If a group
specified here does not exist on the minion, the state will fail.
If set to the empty list, the user will be removed from all groups
except the default group. If unset, salt will assume current groups
are still wanted (see issue #28706).
optional_groups
A list of groups to assign the user to, pass a list object. If a group
specified here does not exist on the minion, the state will silently
ignore it.
NOTE: If the same group is specified in both "groups" and
"optional_groups", then it will be assumed to be required and not optional.
remove_groups
Remove groups that the user is a member of that weren't specified in
the state, Default is ``True``.
home
The custom login directory of user. Uses default value of underlying
system if not set. Notice that this directory does not have to exist.
This also the location of the home directory to create if createhome is
set to True.
createhome : True
If set to ``False``, the home directory will not be created if it
doesn't already exist.
.. warning::
Not supported on Windows or Mac OS.
Additionally, parent directories will *not* be created. The parent
directory for ``home`` must already exist.
nologinit : False
If set to ``True``, it will not add the user to lastlog and faillog
databases.
.. note::
Not supported on Windows or Mac OS.
password
A password hash to set for the user. This field is only supported on
Linux, FreeBSD, NetBSD, OpenBSD, and Solaris. If the ``empty_password``
argument is set to ``True`` then ``password`` is ignored.
For Windows this is the plain text password.
For Linux, the hash can be generated with ``mkpasswd -m sha-256``.
.. versionchanged:: 0.16.0
BSD support added.
hash_password
Set to True to hash the clear text password. Default is ``False``.
enforce_password
Set to False to keep the password from being changed if it has already
been set and the password hash differs from what is specified in the
"password" field. This option will be ignored if "password" is not
specified, Default is ``True``.
empty_password
Set to True to enable password-less login for user, Default is ``False``.
shell
The login shell, defaults to the system default shell
unique
Require a unique UID, Default is ``True``.
system
Choose UID in the range of FIRST_SYSTEM_UID and LAST_SYSTEM_UID, Default is
``False``.
loginclass
The login class, defaults to empty
(BSD only)
User comment field (GECOS) support (currently Linux, BSD, and MacOS
only):
The below values should be specified as strings to avoid ambiguities when
the values are loaded. (Especially the phone and room number fields which
are likely to contain numeric data)
fullname
The user's full name
roomnumber
The user's room number (not supported in MacOS)
workphone
The user's work phone number (not supported in MacOS)
homephone
The user's home phone number (not supported in MacOS)
other
The user's other attribute (not supported in MacOS)
If GECOS field contains more than 4 commas, this field will have the rest of 'em
.. versionchanged:: 2014.7.0
Shadow attribute support added.
Shadow attributes support (currently Linux only):
The below values should be specified as integers.
date
Date of last change of password, represented in days since epoch
(January 1, 1970).
mindays
The minimum number of days between password changes.
maxdays
The maximum number of days between password changes.
inactdays
The number of days after a password expires before an account is
locked.
warndays
Number of days prior to maxdays to warn users.
expire
Date that account expires, represented in days since epoch (January 1,
1970).
The below parameters apply to windows only:
win_homedrive (Windows Only)
The drive letter to use for the home directory. If not specified the
home directory will be a unc path. Otherwise the home directory will be
mapped to the specified drive. Must be a letter followed by a colon.
Because of the colon, the value must be surrounded by single quotes. ie:
- win_homedrive: 'U:
.. versionchanged:: 2015.8.0
win_profile (Windows Only)
The custom profile directory of the user. Uses default value of
underlying system if not set.
.. versionchanged:: 2015.8.0
win_logonscript (Windows Only)
The full path to the logon script to run when the user logs in.
.. versionchanged:: 2015.8.0
win_description (Windows Only)
A brief description of the purpose of the users account.
.. versionchanged:: 2015.8.0 | [
"Ensure",
"that",
"the",
"named",
"user",
"is",
"present",
"with",
"the",
"specified",
"properties"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/user.py#L225-L872 | train |
saltstack/salt | salt/states/user.py | absent | def absent(name, purge=False, force=False):
'''
Ensure that the named user is absent
name
The name of the user to remove
purge
Set purge to True to delete all of the user's files as well as the user,
Default is ``False``.
force
If the user is logged in, the absent state will fail. Set the force
option to True to remove the user even if they are logged in. Not
supported in FreeBSD and Solaris, Default is ``False``.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
lusr = __salt__['user.info'](name)
if lusr:
# The user is present, make it not present
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} set for removal'.format(name)
return ret
beforegroups = set(salt.utils.user.get_group_list(name))
ret['result'] = __salt__['user.delete'](name, purge, force)
aftergroups = set([g for g in beforegroups if __salt__['group.info'](g)])
if ret['result']:
ret['changes'] = {}
for g in beforegroups - aftergroups:
ret['changes']['{0} group'.format(g)] = 'removed'
ret['changes'][name] = 'removed'
ret['comment'] = 'Removed user {0}'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to remove user {0}'.format(name)
return ret
ret['comment'] = 'User {0} is not present'.format(name)
return ret | python | def absent(name, purge=False, force=False):
'''
Ensure that the named user is absent
name
The name of the user to remove
purge
Set purge to True to delete all of the user's files as well as the user,
Default is ``False``.
force
If the user is logged in, the absent state will fail. Set the force
option to True to remove the user even if they are logged in. Not
supported in FreeBSD and Solaris, Default is ``False``.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
lusr = __salt__['user.info'](name)
if lusr:
# The user is present, make it not present
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'User {0} set for removal'.format(name)
return ret
beforegroups = set(salt.utils.user.get_group_list(name))
ret['result'] = __salt__['user.delete'](name, purge, force)
aftergroups = set([g for g in beforegroups if __salt__['group.info'](g)])
if ret['result']:
ret['changes'] = {}
for g in beforegroups - aftergroups:
ret['changes']['{0} group'.format(g)] = 'removed'
ret['changes'][name] = 'removed'
ret['comment'] = 'Removed user {0}'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Failed to remove user {0}'.format(name)
return ret
ret['comment'] = 'User {0} is not present'.format(name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"purge",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"lusr",
"=",
... | Ensure that the named user is absent
name
The name of the user to remove
purge
Set purge to True to delete all of the user's files as well as the user,
Default is ``False``.
force
If the user is logged in, the absent state will fail. Set the force
option to True to remove the user even if they are logged in. Not
supported in FreeBSD and Solaris, Default is ``False``. | [
"Ensure",
"that",
"the",
"named",
"user",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/user.py#L875-L919 | train |
saltstack/salt | salt/utils/url.py | parse | def parse(url):
'''
Parse a salt:// URL; return the path and a possible saltenv query.
'''
if not url.startswith('salt://'):
return url, None
# urlparse will split on valid filename chars such as '?' and '&'
resource = url.split('salt://', 1)[-1]
if '?env=' in resource:
# "env" is not supported; Use "saltenv".
path, saltenv = resource.split('?env=', 1)[0], None
elif '?saltenv=' in resource:
path, saltenv = resource.split('?saltenv=', 1)
else:
path, saltenv = resource, None
if salt.utils.platform.is_windows():
path = salt.utils.path.sanitize_win_path(path)
return path, saltenv | python | def parse(url):
'''
Parse a salt:// URL; return the path and a possible saltenv query.
'''
if not url.startswith('salt://'):
return url, None
# urlparse will split on valid filename chars such as '?' and '&'
resource = url.split('salt://', 1)[-1]
if '?env=' in resource:
# "env" is not supported; Use "saltenv".
path, saltenv = resource.split('?env=', 1)[0], None
elif '?saltenv=' in resource:
path, saltenv = resource.split('?saltenv=', 1)
else:
path, saltenv = resource, None
if salt.utils.platform.is_windows():
path = salt.utils.path.sanitize_win_path(path)
return path, saltenv | [
"def",
"parse",
"(",
"url",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'salt://'",
")",
":",
"return",
"url",
",",
"None",
"# urlparse will split on valid filename chars such as '?' and '&'",
"resource",
"=",
"url",
".",
"split",
"(",
"'salt://'",
",... | Parse a salt:// URL; return the path and a possible saltenv query. | [
"Parse",
"a",
"salt",
":",
"//",
"URL",
";",
"return",
"the",
"path",
"and",
"a",
"possible",
"saltenv",
"query",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L19-L40 | train |
saltstack/salt | salt/utils/url.py | create | def create(path, saltenv=None):
'''
join `path` and `saltenv` into a 'salt://' URL.
'''
if salt.utils.platform.is_windows():
path = salt.utils.path.sanitize_win_path(path)
path = salt.utils.data.decode(path)
query = 'saltenv={0}'.format(saltenv) if saltenv else ''
url = salt.utils.data.decode(urlunparse(('file', '', path, '', query, '')))
return 'salt://{0}'.format(url[len('file:///'):]) | python | def create(path, saltenv=None):
'''
join `path` and `saltenv` into a 'salt://' URL.
'''
if salt.utils.platform.is_windows():
path = salt.utils.path.sanitize_win_path(path)
path = salt.utils.data.decode(path)
query = 'saltenv={0}'.format(saltenv) if saltenv else ''
url = salt.utils.data.decode(urlunparse(('file', '', path, '', query, '')))
return 'salt://{0}'.format(url[len('file:///'):]) | [
"def",
"create",
"(",
"path",
",",
"saltenv",
"=",
"None",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"path",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"sanitize_win_path",
"(",
"path",
")",
"path",
... | join `path` and `saltenv` into a 'salt://' URL. | [
"join",
"path",
"and",
"saltenv",
"into",
"a",
"salt",
":",
"//",
"URL",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L43-L53 | train |
saltstack/salt | salt/utils/url.py | is_escaped | def is_escaped(url):
'''
test whether `url` is escaped with `|`
'''
scheme = urlparse(url).scheme
if not scheme:
return url.startswith('|')
elif scheme == 'salt':
path, saltenv = parse(url)
if salt.utils.platform.is_windows() and '|' in url:
return path.startswith('_')
else:
return path.startswith('|')
else:
return False | python | def is_escaped(url):
'''
test whether `url` is escaped with `|`
'''
scheme = urlparse(url).scheme
if not scheme:
return url.startswith('|')
elif scheme == 'salt':
path, saltenv = parse(url)
if salt.utils.platform.is_windows() and '|' in url:
return path.startswith('_')
else:
return path.startswith('|')
else:
return False | [
"def",
"is_escaped",
"(",
"url",
")",
":",
"scheme",
"=",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"if",
"not",
"scheme",
":",
"return",
"url",
".",
"startswith",
"(",
"'|'",
")",
"elif",
"scheme",
"==",
"'salt'",
":",
"path",
",",
"saltenv",
"=",... | test whether `url` is escaped with `|` | [
"test",
"whether",
"url",
"is",
"escaped",
"with",
"|"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L56-L70 | train |
saltstack/salt | salt/utils/url.py | escape | def escape(url):
'''
add escape character `|` to `url`
'''
if salt.utils.platform.is_windows():
return url
scheme = urlparse(url).scheme
if not scheme:
if url.startswith('|'):
return url
else:
return '|{0}'.format(url)
elif scheme == 'salt':
path, saltenv = parse(url)
if path.startswith('|'):
return create(path, saltenv)
else:
return create('|{0}'.format(path), saltenv)
else:
return url | python | def escape(url):
'''
add escape character `|` to `url`
'''
if salt.utils.platform.is_windows():
return url
scheme = urlparse(url).scheme
if not scheme:
if url.startswith('|'):
return url
else:
return '|{0}'.format(url)
elif scheme == 'salt':
path, saltenv = parse(url)
if path.startswith('|'):
return create(path, saltenv)
else:
return create('|{0}'.format(path), saltenv)
else:
return url | [
"def",
"escape",
"(",
"url",
")",
":",
"if",
"salt",
".",
"utils",
".",
"platform",
".",
"is_windows",
"(",
")",
":",
"return",
"url",
"scheme",
"=",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"if",
"not",
"scheme",
":",
"if",
"url",
".",
"startsw... | add escape character `|` to `url` | [
"add",
"escape",
"character",
"|",
"to",
"url"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L73-L93 | train |
saltstack/salt | salt/utils/url.py | unescape | def unescape(url):
'''
remove escape character `|` from `url`
'''
scheme = urlparse(url).scheme
if not scheme:
return url.lstrip('|')
elif scheme == 'salt':
path, saltenv = parse(url)
if salt.utils.platform.is_windows() and '|' in url:
return create(path.lstrip('_'), saltenv)
else:
return create(path.lstrip('|'), saltenv)
else:
return url | python | def unescape(url):
'''
remove escape character `|` from `url`
'''
scheme = urlparse(url).scheme
if not scheme:
return url.lstrip('|')
elif scheme == 'salt':
path, saltenv = parse(url)
if salt.utils.platform.is_windows() and '|' in url:
return create(path.lstrip('_'), saltenv)
else:
return create(path.lstrip('|'), saltenv)
else:
return url | [
"def",
"unescape",
"(",
"url",
")",
":",
"scheme",
"=",
"urlparse",
"(",
"url",
")",
".",
"scheme",
"if",
"not",
"scheme",
":",
"return",
"url",
".",
"lstrip",
"(",
"'|'",
")",
"elif",
"scheme",
"==",
"'salt'",
":",
"path",
",",
"saltenv",
"=",
"pa... | remove escape character `|` from `url` | [
"remove",
"escape",
"character",
"|",
"from",
"url"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L96-L110 | train |
saltstack/salt | salt/utils/url.py | add_env | def add_env(url, saltenv):
'''
append `saltenv` to `url` as a query parameter to a 'salt://' url
'''
if not url.startswith('salt://'):
return url
path, senv = parse(url)
return create(path, saltenv) | python | def add_env(url, saltenv):
'''
append `saltenv` to `url` as a query parameter to a 'salt://' url
'''
if not url.startswith('salt://'):
return url
path, senv = parse(url)
return create(path, saltenv) | [
"def",
"add_env",
"(",
"url",
",",
"saltenv",
")",
":",
"if",
"not",
"url",
".",
"startswith",
"(",
"'salt://'",
")",
":",
"return",
"url",
"path",
",",
"senv",
"=",
"parse",
"(",
"url",
")",
"return",
"create",
"(",
"path",
",",
"saltenv",
")"
] | append `saltenv` to `url` as a query parameter to a 'salt://' url | [
"append",
"saltenv",
"to",
"url",
"as",
"a",
"query",
"parameter",
"to",
"a",
"salt",
":",
"//",
"url"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/url.py#L113-L121 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.