id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,600
|
test_alias_deprecation.py
|
ansible_ansible/test/integration/targets/module_utils/library/test_alias_deprecation.py
|
#!/usr/bin/python
from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule
# overridden
from ansible.module_utils.ansible_release import data
results = {"data": data}
arg_spec = dict(
foo=dict(type='str', aliases=['baz'], deprecated_aliases=[dict(name='baz', version='9.99')])
)
AnsibleModule(argument_spec=arg_spec).exit_json(**results)
| 378
|
Python
|
.py
| 10
| 35.9
| 96
| 0.760331
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,601
|
pure_json.py
|
ansible_ansible/test/integration/targets/module_utils/callback/pure_json.py
|
# (c) 2021 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
name: pure_json
type: stdout
short_description: only outputs the module results as json
"""
import json
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'pure_json'
def v2_runner_on_failed(self, result, ignore_errors=False):
self._display.display(json.dumps(result._result))
def v2_runner_on_ok(self, result):
self._display.display(json.dumps(result._result))
def v2_runner_on_skipped(self, result):
self._display.display(json.dumps(result._result))
| 796
|
Python
|
.py
| 20
| 35.3
| 92
| 0.725849
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,602
|
copy.yml
|
ansible_ansible/test/integration/targets/plugin_filtering/copy.yml
|
---
- hosts: testhost
gather_facts: False
tasks:
- copy:
content: 'Testing 1... 2... 3...'
dest: ./testing.txt
- file:
state: absent
path: ./testing.txt
| 185
|
Python
|
.py
| 10
| 14.3
| 39
| 0.56
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,603
|
_module3.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/_module3.py
|
#!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
module: _module3
short_description: Another test module
description: This is a test module that has not been deprecated.
author:
- Ansible Core Team
"""
EXAMPLES = """
- minimal:
"""
RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={},
)
module.exit_json()
if __name__ == '__main__':
main()
| 563
|
Python
|
.py
| 22
| 22.954545
| 92
| 0.700565
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,604
|
module1.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/module1.py
|
#!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
module: module1
short_description: Hello test module
description: Hello test module.
options: {}
author:
- Ansible Core Team
"""
EXAMPLES = """
- minimal:
"""
RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={},
)
module.exit_json()
if __name__ == '__main__':
main()
| 539
|
Python
|
.py
| 23
| 20.869565
| 92
| 0.693676
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,605
|
module2.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/a/b/module2.py
|
#!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
module: module2
short_description: Hello test module
description: Hello test module.
options: {}
author:
- Ansible Core Team
"""
EXAMPLES = """
- minimal:
"""
RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={},
)
module.exit_json()
if __name__ == '__main__':
main()
| 539
|
Python
|
.py
| 23
| 20.869565
| 92
| 0.693676
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,606
|
lookup1.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/lookup/lookup1.py
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
name: lookup1
author: Ansible Core Team
short_description: hello test lookup
description:
- Hello test lookup.
options: {}
"""
EXAMPLES = """
- minimal:
"""
RETURN = """
"""
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
return []
| 506
|
Python
|
.py
| 19
| 23.105263
| 92
| 0.693111
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,607
|
lookup2.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/lookup/a/b/lookup2.py
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
name: lookup2
author: Ansible Core Team
short_description: hello test lookup
description:
- Hello test lookup.
options: {}
"""
EXAMPLES = """
- minimal:
"""
RETURN = """
"""
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
return []
| 506
|
Python
|
.py
| 19
| 23.105263
| 92
| 0.693111
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,608
|
shell_no_failed.py
|
ansible_ansible/test/integration/targets/until/action_plugins/shell_no_failed.py
|
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
del tmp # tmp no longer has any effect
try:
self._task.args['_raw_params'] = self._task.args.pop('cmd')
except KeyError:
pass
shell_action = self._shared_loader_obj.action_loader.get('ansible.legacy.shell',
task=self._task,
connection=self._connection,
play_context=self._play_context,
loader=self._loader,
templar=self._templar,
shared_loader_obj=self._shared_loader_obj)
result = shell_action.run(task_vars=task_vars)
result.pop('failed', None)
return result
| 1,228
|
Python
|
.py
| 21
| 34.619048
| 107
| 0.472939
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,609
|
test_filter.py
|
ansible_ansible/test/integration/targets/plugin_namespace/filter_plugins/test_filter.py
|
from __future__ import annotations
def filter_name(a):
return __name__
class FilterModule(object):
def filters(self):
filters = {
'filter_name': filter_name,
}
return filters
| 224
|
Python
|
.py
| 9
| 18.444444
| 39
| 0.609524
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,610
|
lookup_name.py
|
ansible_ansible/test/integration/targets/plugin_namespace/lookup_plugins/lookup_name.py
|
from __future__ import annotations
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
return [__name__]
| 189
|
Python
|
.py
| 5
| 33.8
| 46
| 0.740331
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,611
|
test_test.py
|
ansible_ansible/test/integration/targets/plugin_namespace/test_plugins/test_test.py
|
from __future__ import annotations
import re
def test_name_ok(value):
# test names are prefixed with a unique hash value to prevent shadowing of other plugins
return bool(re.match(r'^ansible\.plugins\.test\.[0-9]+_test_test$', __name__))
class TestModule:
def tests(self):
return {
'test_name_ok': test_name_ok,
}
| 359
|
Python
|
.py
| 10
| 30.4
| 92
| 0.662791
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,612
|
ios_facts.py
|
ansible_ansible/test/integration/targets/gathering_facts/collections/ansible_collections/cisco/ios/plugins/modules/ios_facts.py
|
#!/usr/bin/python
from __future__ import annotations
DOCUMENTATION = """
---
module: ios_facts
short_description: supporting network facts module
description:
- supporting network facts module for gather_facts + module_defaults tests
options:
gather_subset:
description:
- When supplied, this argument restricts the facts collected
to a given subset.
- Possible values for this argument include
C(all), C(hardware), C(config), and C(interfaces).
- Specify a list of values to include a larger subset.
- Use a value with an initial C(!) to collect all facts except that subset.
required: false
default: '!config'
"""
from ansible.module_utils.basic import AnsibleModule
def main():
"""main entry point for module execution
"""
argument_spec = dict(
gather_subset=dict(default='!config')
)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
module.exit_json(ansible_facts={'gather_subset': module.params['gather_subset'], '_ansible_facts_gathered': True})
if __name__ == '__main__':
main()
| 1,143
|
Python
|
.py
| 32
| 30.71875
| 118
| 0.692029
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,613
|
file_utils.py
|
ansible_ansible/test/integration/targets/gathering_facts/library/file_utils.py
|
from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.facts.utils import (
get_file_content,
get_file_lines,
get_mount_size,
)
def main():
module = AnsibleModule(
argument_spec=dict(
test=dict(type='str', default='strip'),
touch_file=dict(type='str', default='/dev/null'),
line_sep_file=dict(type='str', default='/dev/null'),
line_sep_sep=dict(type='str', default='\n'),
)
)
test = module.params['test']
facts = {}
if test == 'strip':
etc_passwd = get_file_content('/etc/passwd')
etc_passwd_unstripped = get_file_content('/etc/passwd', strip=False)
facts['etc_passwd_newlines'] = etc_passwd.count('\n')
facts['etc_passwd_newlines_unstripped'] = etc_passwd_unstripped.count('\n')
elif test == 'default':
path = module.params['touch_file']
facts['touch_default'] = get_file_content(path, default='i am a default')
elif test == 'line_sep':
path = module.params['line_sep_file']
sep = module.params['line_sep_sep']
facts['line_sep'] = get_file_lines(path, line_sep=sep)
elif test == 'invalid_mountpoint':
facts['invalid_mountpoint'] = get_mount_size('/doesnotexist')
result = {
'changed': False,
'ansible_facts': facts,
}
module.exit_json(**result)
main()
| 1,440
|
Python
|
.py
| 38
| 30.894737
| 83
| 0.617986
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,614
|
none.py
|
ansible_ansible/test/integration/targets/gathering_facts/cache_plugins/none.py
|
# (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.plugins.cache import BaseCacheModule
DOCUMENTATION = """
cache: none
short_description: write-only cache (no cache)
description:
- No caching at all
version_added: historical
author: core team (@ansible-core)
"""
class CacheModule(BaseCacheModule):
def __init__(self, *args, **kwargs):
self.empty = {}
def get(self, key):
return self.empty.get(key)
def set(self, key, value):
return value
def keys(self):
return self.empty.keys()
def contains(self, key):
return key in self.empty
def delete(self, key):
del self.emtpy[key]
def flush(self):
self.empty = {}
def copy(self):
return self.empty.copy()
def __getstate__(self):
return self.copy()
def __setstate__(self, data):
self.empty = data
| 1,061
|
Python
|
.py
| 34
| 25.411765
| 92
| 0.643281
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,615
|
test_assertion.py
|
ansible_ansible/test/integration/targets/ansible-test-units-assertions/ansible_collections/ns/col/tests/unit/plugins/modules/test_assertion.py
|
from __future__ import annotations
def test_assertion():
assert dict(yes=True) == dict(no=False)
| 103
|
Python
|
.py
| 3
| 31.333333
| 43
| 0.72449
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,616
|
ansible_release.py
|
ansible_ansible/test/integration/targets/module_utils_ansible_release/library/ansible_release.py
|
#!/usr/bin/python
# Copyright: (c) 2021, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
---
module: ansible_release
short_description: Get ansible_release info from module_utils
description: Get ansible_release info from module_utils
author:
- Ansible Project
"""
EXAMPLES = r"""
#
"""
RETURN = r"""
#
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_release import __version__, __author__, __codename__
def main():
module = AnsibleModule(argument_spec={})
result = {
'version': __version__,
'author': __author__,
'codename': __codename__,
}
module.exit_json(**result)
if __name__ == '__main__':
main()
| 816
|
Python
|
.py
| 30
| 24.433333
| 92
| 0.685972
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,617
|
module.py
|
ansible_ansible/test/integration/targets/no_log/library/module.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2019 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec={
'state': {},
'secret': {'no_log': True},
'subopt_dict': {
'type': 'dict',
'options': {
'str_sub_opt1': {'no_log': True},
'str_sub_opt2': {},
'nested_subopt': {
'type': 'dict',
'options': {
'n_subopt1': {'no_log': True},
}
}
}
},
'subopt_list': {
'type': 'list',
'elements': 'dict',
'options': {
'subopt1': {'no_log': True},
'subopt2': {},
}
}
}
)
module.exit_json(msg='done')
if __name__ == '__main__':
main()
| 1,165
|
Python
|
.py
| 37
| 18.513514
| 92
| 0.394291
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,618
|
action_sets_no_log.py
|
ansible_ansible/test/integration/targets/no_log/action_plugins/action_sets_no_log.py
|
from __future__ import annotations
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
return dict(changed=False, failed=False, msg="action result should be masked", _ansible_no_log="yeppers") # ensure that a truthy non-bool works here
| 319
|
Python
|
.py
| 5
| 59.8
| 157
| 0.762058
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,619
|
exercise_cache.py
|
ansible_ansible/test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py
|
# Copyright (c) 2022 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
inventory: exercise_cache
short_description: run tests against the specified cache plugin
description:
- This plugin doesn't modify inventory.
- Load a cache plugin and test the inventory cache interface is dict-like.
- Most inventory cache write methods only apply to the in-memory cache.
- The 'flush' and 'set_cache' methods should be used to apply changes to the backing cache plugin.
- The inventory cache read methods prefer the in-memory cache, and fall back to reading from the cache plugin.
extends_documentation_fragment:
- inventory_cache
options:
plugin:
required: true
description: name of the plugin (exercise_cache)
cache_timeout:
ini: []
env: []
cli: []
default: 0 # never expire
"""
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
from ansible.utils.display import Display
from time import sleep
display = Display()
class InventoryModule(BaseInventoryPlugin, Cacheable):
NAME = 'exercise_cache'
test_cache_methods = [
'test_plugin_name',
'test_update_cache_if_changed',
'test_set_cache',
'test_load_whole_cache',
'test_iter',
'test_len',
'test_get_missing_key',
'test_get_expired_key',
'test_initial_get',
'test_get',
'test_items',
'test_keys',
'test_values',
'test_pop',
'test_del',
'test_set',
'test_update',
'test_flush',
]
def verify_file(self, path):
if not path.endswith(('exercise_cache.yml', 'exercise_cache.yaml',)):
return False
return super(InventoryModule, self).verify_file(path)
def parse(self, inventory, loader, path, cache=None):
super(InventoryModule, self).parse(inventory, loader, path)
self._read_config_data(path)
try:
self.exercise_test_cache()
except AnsibleError:
raise
except Exception as e:
raise AnsibleError("Failed to run cache tests: {0}".format(e)) from e
def exercise_test_cache(self):
failed = []
for test_name in self.test_cache_methods:
try:
getattr(self, test_name)()
except AssertionError:
failed.append(test_name)
finally:
self.cache.flush()
self.cache.update_cache_if_changed()
if failed:
raise AnsibleError(f"Cache tests failed: {', '.join(failed)}")
def test_equal(self, a, b):
try:
assert a == b
except AssertionError:
display.warning(f"Assertion {a} == {b} failed")
raise
def test_plugin_name(self):
self.test_equal(self.cache._plugin_name, self.get_option('cache_plugin'))
def test_update_cache_if_changed(self):
self.cache._retrieved = {}
self.cache._cache = {'foo': 'bar'}
self.cache.update_cache_if_changed()
self.test_equal(self.cache._retrieved, {'foo': 'bar'})
self.test_equal(self.cache._cache, {'foo': 'bar'})
def test_set_cache(self):
cache_key1 = 'key1'
cache1 = {'hosts': {'h1': {'foo': 'bar'}}}
cache_key2 = 'key2'
cache2 = {'hosts': {'h2': {}}}
self.cache._cache = {cache_key1: cache1, cache_key2: cache2}
self.cache.set_cache()
self.test_equal(self.cache._plugin.contains(cache_key1), True)
self.test_equal(self.cache._plugin.get(cache_key1), cache1)
self.test_equal(self.cache._plugin.contains(cache_key2), True)
self.test_equal(self.cache._plugin.get(cache_key2), cache2)
def test_load_whole_cache(self):
cache_data = {
'key1': {'hosts': {'h1': {'foo': 'bar'}}},
'key2': {'hosts': {'h2': {}}},
}
self.cache._cache = cache_data
self.cache.set_cache()
self.cache._cache = {}
self.cache.load_whole_cache()
self.test_equal(self.cache._cache, cache_data)
def test_iter(self):
cache_data = {
'key1': {'hosts': {'h1': {'foo': 'bar'}}},
'key2': {'hosts': {'h2': {}}},
}
self.cache._cache = cache_data
self.test_equal(sorted(list(self.cache)), ['key1', 'key2'])
def test_len(self):
cache_data = {
'key1': {'hosts': {'h1': {'foo': 'bar'}}},
'key2': {'hosts': {'h2': {}}},
}
self.cache._cache = cache_data
self.test_equal(len(self.cache), 2)
def test_get_missing_key(self):
# cache should behave like a dictionary
# a missing key with __getitem__ should raise a KeyError
try:
self.cache['keyerror']
except KeyError:
pass
else:
assert False
# get should return the default instead
self.test_equal(self.cache.get('missing'), None)
self.test_equal(self.cache.get('missing', 'default'), 'default')
def _setup_expired(self):
self.cache._cache = {'expired': True}
self.cache.set_cache()
# empty the in-memory info to test loading the key
# keys that expire mid-use do not cause errors
self.cache._cache = {}
self.cache._retrieved = {}
self.cache._plugin._cache = {}
self.cache._plugin.set_option('timeout', 1)
self.cache._plugin._timeout = 1
sleep(2)
def _cleanup_expired(self):
# Set cache timeout back to never
self.cache._plugin.set_option('timeout', 0)
self.cache._plugin._timeout = 0
def test_get_expired_key(self):
if not hasattr(self.cache._plugin, '_timeout'):
# DB-backed caches do not have a standard timeout interface
return
self._setup_expired()
try:
self.cache['expired']
except KeyError:
pass
else:
assert False
finally:
self._cleanup_expired()
self._setup_expired()
try:
self.test_equal(self.cache.get('expired'), None)
self.test_equal(self.cache.get('expired', 'default'), 'default')
finally:
self._cleanup_expired()
def test_initial_get(self):
# test cache behaves like a dictionary
# set the cache to test getting a key that exists
k1 = {'hosts': {'h1': {'foo': 'bar'}}}
k2 = {'hosts': {'h2': {}}}
self.cache._cache = {'key1': k1, 'key2': k2}
self.cache.set_cache()
# empty the in-memory info to test loading the key from the plugin
self.cache._cache = {}
self.cache._retrieved = {}
self.cache._plugin._cache = {}
self.test_equal(self.cache['key1'], k1)
# empty the in-memory info to test loading the key from the plugin
self.cache._cache = {}
self.cache._retrieved = {}
self.cache._plugin._cache = {}
self.test_equal(self.cache.get('key1'), k1)
def test_get(self):
# test cache behaves like a dictionary
# set the cache to test getting a key that exists
k1 = {'hosts': {'h1': {'foo': 'bar'}}}
k2 = {'hosts': {'h2': {}}}
self.cache._cache = {'key1': k1, 'key2': k2}
self.cache.set_cache()
self.test_equal(self.cache['key1'], k1)
self.test_equal(self.cache.get('key1'), k1)
def test_items(self):
self.test_equal(self.cache.items(), {}.items())
test_items = {'hosts': {'host1': {'foo': 'bar'}}}
self.cache._cache = test_items
self.test_equal(self.cache.items(), test_items.items())
def test_keys(self):
self.test_equal(self.cache.keys(), {}.keys())
test_items = {'hosts': {'host1': {'foo': 'bar'}}}
self.cache._cache = test_items
self.test_equal(self.cache.keys(), test_items.keys())
def test_values(self):
self.test_equal(list(self.cache.values()), list({}.values()))
test_items = {'hosts': {'host1': {'foo': 'bar'}}}
self.cache._cache = test_items
self.test_equal(list(self.cache.values()), list(test_items.values()))
def test_pop(self):
try:
self.cache.pop('missing')
except KeyError:
pass
else:
assert False
self.test_equal(self.cache.pop('missing', 'default'), 'default')
self.cache._cache = {'cache_key': 'cache'}
self.test_equal(self.cache.pop('cache_key'), 'cache')
# test backing plugin cache isn't modified
cache_key1 = 'key1'
cache1 = {'hosts': {'h1': {'foo': 'bar'}}}
cache_key2 = 'key2'
cache2 = {'hosts': {'h2': {}}}
self.cache._cache = {cache_key1: cache1, cache_key2: cache2}
self.cache.set_cache()
self.test_equal(self.cache.pop('key1'), cache1)
self.test_equal(self.cache._cache, {cache_key2: cache2})
self.test_equal(self.cache._plugin._cache, {cache_key1: cache1, cache_key2: cache2})
def test_del(self):
try:
del self.cache['missing']
except KeyError:
pass
else:
assert False
cache_key1 = 'key1'
cache1 = {'hosts': {'h1': {'foo': 'bar'}}}
cache_key2 = 'key2'
cache2 = {'hosts': {'h2': {}}}
self.cache._cache = {cache_key1: cache1, cache_key2: cache2}
self.cache.set_cache()
del self.cache['key1']
self.test_equal(self.cache._cache, {cache_key2: cache2})
self.test_equal(self.cache._plugin._cache, {cache_key1: cache1, cache_key2: cache2})
def test_set(self):
cache_key = 'key1'
hosts = {'hosts': {'h1': {'foo': 'bar'}}}
self.cache[cache_key] = hosts
self.test_equal(self.cache._cache, {cache_key: hosts})
self.test_equal(self.cache._plugin._cache, {})
def test_update(self):
cache_key1 = 'key1'
cache1 = {'hosts': {'h1': {'foo': 'bar'}}}
cache_key2 = 'key2'
cache2 = {'hosts': {'h2': {}}}
self.cache._cache = {cache_key1: cache1}
self.cache.update({cache_key2: cache2})
self.test_equal(self.cache._cache, {cache_key1: cache1, cache_key2: cache2})
def test_flush(self):
cache_key1 = 'key1'
cache1 = {'hosts': {'h1': {'foo': 'bar'}}}
cache_key2 = 'key2'
cache2 = {'hosts': {'h2': {}}}
self.cache._cache = {cache_key1: cache1, cache_key2: cache2}
self.cache.set_cache()
# Unlike the dict write methods, cache.flush() flushes the backing plugin
self.cache.flush()
self.test_equal(self.cache._cache, {})
self.test_equal(self.cache._plugin._cache, {})
| 10,983
|
Python
|
.py
| 273
| 31.201465
| 116
| 0.577444
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,620
|
cache_host.py
|
ansible_ansible/test/integration/targets/inventory_cache/plugins/inventory/cache_host.py
|
# Copyright (c) 2021 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
inventory: cache_host
short_description: add a host to inventory and cache it
description: add a host to inventory and cache it
extends_documentation_fragment:
- inventory_cache
options:
plugin:
required: true
description: name of the plugin (cache_host)
"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
import random
class InventoryModule(BaseInventoryPlugin, Cacheable):
NAME = 'cache_host'
def verify_file(self, path):
if not path.endswith(('cache_host.yml', 'cache_host.yaml',)):
return False
return super(InventoryModule, self).verify_file(path)
def parse(self, inventory, loader, path, cache=None):
super(InventoryModule, self).parse(inventory, loader, path)
self._read_config_data(path)
cache_key = self.get_cache_key(path)
# user has enabled cache and the cache is not being flushed
read_cache = self.get_option('cache') and cache
# user has enabled cache and the cache is being flushed
update_cache = self.get_option('cache') and not cache
host = None
if read_cache:
try:
host = self._cache[cache_key]
except KeyError:
# cache expired
update_cache = True
if host is None:
host = 'testhost{0}'.format(random.randint(0, 50))
self.inventory.add_host(host, 'all')
if update_cache:
self._cache[cache_key] = host
| 1,718
|
Python
|
.py
| 42
| 32.928571
| 92
| 0.654239
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,621
|
build.py
|
ansible_ansible/test/integration/targets/binary_modules/build.py
|
#!/usr/bin/env python
"""
Compile binary modules for this test for access from S3 at:
https://ci-files.testing.ansible.com/test/integration/roles/test_binary_modules/
This avoids a test dependency on go and keeps the binaries out of the git repository.
"""
from __future__ import annotations
import os
import pathlib
import shlex
import subprocess
def main() -> None:
library = pathlib.Path(__file__).parent / 'library'
# NOTE: The value of `NAME` must be `ansible_architecture` for the target system, plus any required extension.
builds = (
dict(GOOS='linux', GOARCH='amd64', NAME='linux_x86_64'),
dict(GOOS='linux', GOARCH='arm64', NAME='linux_aarch64'),
dict(GOOS='windows', GOARCH='amd64', NAME='win32nt_64-bit.exe'),
dict(GOOS='darwin', GOARCH='amd64', NAME='darwin_x86_64'),
dict(GOOS='darwin', GOARCH='arm64', NAME='darwin_arm64'),
dict(GOOS='freebsd', GOARCH='amd64', NAME='freebsd_amd64'),
dict(GOOS='freebsd', GOARCH='arm64', NAME='freebsd_arm64'),
)
for build in builds:
name = build.pop('NAME')
cmd = ['go', 'build', '-o', f'helloworld_{name}', 'helloworld.go']
env = os.environ.copy()
env.update(build)
print(f'==> {shlex.join(f"{k}={v}" for k, v in build.items())} {shlex.join(cmd)}')
subprocess.run(cmd, env=env, cwd=library, check=True, text=True)
if __name__ == '__main__':
main()
| 1,435
|
Python
|
.py
| 32
| 39.5625
| 114
| 0.650646
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,622
|
ansible_test_service.py
|
ansible_ansible/test/integration/targets/service_facts/files/ansible_test_service.py
|
#!/usr/bin/env python
# this is mostly based off of the code found here:
# http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
from __future__ import annotations
import os
import resource
import signal
import time
UMASK = 0
WORKDIR = "/"
MAXFD = 1024
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
def createDaemon():
try:
pid = os.fork()
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if (pid == 0):
os.setsid()
try:
pid = os.fork()
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if (pid == 0):
os.chdir(WORKDIR)
os.umask(UMASK)
else:
with open('/var/run/ansible_test_service.pid', 'w') as f:
f.write("%d\n" % pid)
os._exit(0)
else:
os._exit(0)
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = MAXFD
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # ERROR, fd wasn't open to begin with (ignored)
pass
os.open(REDIRECT_TO, os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2)
return (0)
if __name__ == "__main__":
signal.signal(signal.SIGHUP, signal.SIG_IGN)
retCode = createDaemon()
while True:
time.sleep(1000)
| 1,469
|
Python
|
.py
| 52
| 21.653846
| 78
| 0.580114
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,623
|
test_rc_1.py
|
ansible_ansible/test/integration/targets/win_exec_wrapper/action_plugins/test_rc_1.py
|
# Copyright: (c) 2023, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
import json
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
super().run(tmp, task_vars)
del tmp
exec_command = self._connection.exec_command
def patched_exec_command(*args, **kwargs):
rc, stdout, stderr = exec_command(*args, **kwargs)
new_stdout = json.dumps({
"rc": rc,
"stdout": stdout.decode(),
"stderr": stderr.decode(),
"failed": False,
"changed": False,
}).encode()
return (0, new_stdout, b"")
try:
# This is done to capture the raw rc/stdio from the module exec
self._connection.exec_command = patched_exec_command
return self._execute_module(task_vars=task_vars)
finally:
self._connection.exec_command = exec_command
| 1,101
|
Python
|
.py
| 26
| 32.192308
| 92
| 0.598122
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,624
|
test.py
|
ansible_ansible/test/integration/targets/run_modules/library/test.py
|
#!/usr/bin/python
from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule
module = AnsibleModule(argument_spec=dict())
module.exit_json(**{'tempdir': module._remote_tmp})
| 207
|
Python
|
.py
| 5
| 39.6
| 52
| 0.787879
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,625
|
get_gid_for_group.py
|
ansible_ansible/test/integration/targets/group/files/get_gid_for_group.py
|
from __future__ import annotations
import grp
import sys
def main():
group_name = None
if len(sys.argv) >= 2:
group_name = sys.argv[1]
print(grp.getgrnam(group_name).gr_gid)
if __name__ == '__main__':
main()
| 239
|
Python
|
.py
| 10
| 19.8
| 42
| 0.626126
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,626
|
get_free_gid.py
|
ansible_ansible/test/integration/targets/group/files/get_free_gid.py
|
from __future__ import annotations
import grp
def main():
gids = [g.gr_gid for g in grp.getgrall()]
# Start the gid numbering with 1
# FreeBSD doesn't support the usage of gid 0, it doesn't fail (rc=0) but instead a number in the normal
# range is picked.
i = 1
while True:
if i not in gids:
print(i)
break
i += 1
if __name__ == '__main__':
main()
| 423
|
Python
|
.py
| 15
| 22.2
| 107
| 0.586035
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,627
|
test_hello.py
|
ansible_ansible/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/tests/unit/plugins/modules/test_hello.py
|
from __future__ import annotations
from .....plugins.modules.hello import say_hello
def test_say_hello():
assert say_hello('Ansibull') == dict(message='Hello Ansibull')
| 176
|
Python
|
.py
| 4
| 41.25
| 66
| 0.739645
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,628
|
test_my_util.py
|
ansible_ansible/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/tests/unit/plugins/module_utils/test_my_util.py
|
from __future__ import annotations
from .....plugins.module_utils.my_util import hello
def test_hello():
assert hello('Ansibull') == 'Hello Ansibull'
| 157
|
Python
|
.py
| 4
| 36.5
| 51
| 0.733333
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,629
|
hello.py
|
ansible_ansible/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/hello.py
|
#!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
module: hello
short_description: Hello test module
description: Hello test module.
options:
name:
description: Name to say hello to.
type: str
author:
- Ansible Core Team
"""
EXAMPLES = """
- minimal:
"""
RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
from ..module_utils.my_util import hello
def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str'),
),
)
module.exit_json(**say_hello(module.params['name']))
def say_hello(name):
return dict(
message=hello(name),
)
if __name__ == '__main__':
main()
| 793
|
Python
|
.py
| 33
| 20.484848
| 92
| 0.67246
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,630
|
win_util_args.py
|
ansible_ansible/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r"""
---
module: win_util_args
short_description: Short description
description:
- Some test description for the module
options:
my_opt:
description:
- Test description
required: yes
type: str
extends_documentation_fragment:
- ns.col.ps_util
author:
- Ansible Test (@ansible)
"""
EXAMPLES = r"""
- win_util_args:
option1: test
my_opt: test
"""
RETURN = r"""
#
"""
| 727
|
Python
|
.py
| 32
| 19.4375
| 92
| 0.664244
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,631
|
my_util.py
|
ansible_ansible/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/module_utils/my_util.py
|
from __future__ import annotations
def hello(name):
return 'Hello %s' % name
| 83
|
Python
|
.py
| 3
| 24.666667
| 34
| 0.705128
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,632
|
ps_util.py
|
ansible_ansible/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/doc_fragments/ps_util.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2020 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
class ModuleDocFragment:
DOCUMENTATION = r"""
options:
option1:
description:
- Test description
required: yes
aliases:
- alias1
type: str
"""
| 366
|
Python
|
.py
| 15
| 21.066667
| 92
| 0.693642
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,633
|
echoaction.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/echoaction.py
|
from __future__ import annotations
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FILES = False
_VALID_ARGS = frozenset()
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(None, task_vars)
result = dict(changed=False, args_in=self._task.args)
return result
| 432
|
Python
|
.py
| 11
| 32.545455
| 63
| 0.681159
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,634
|
ios.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/ios.py
|
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.plugins.action.normal import ActionModule as ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['action_plugin'] = 'ios'
return result
| 445
|
Python
|
.py
| 9
| 44.555556
| 92
| 0.729604
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,635
|
vyos.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/vyos.py
|
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.plugins.action.normal import ActionModule as ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['action_plugin'] = 'vyos'
return result
| 446
|
Python
|
.py
| 9
| 44.666667
| 92
| 0.730233
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,636
|
eos.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/eos.py
|
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.plugins.action.normal import ActionModule as ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['action_plugin'] = 'eos'
return result
| 445
|
Python
|
.py
| 9
| 44.555556
| 92
| 0.729604
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,637
|
module.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/module.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
---
module: module
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
"""
EXAMPLES = r"""
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
action_option=dict(type=bool),
),
supports_check_mode=True
)
module.exit_json(action_option=module.params['action_option'])
if __name__ == '__main__':
main()
| 700
|
Python
|
.py
| 24
| 25.583333
| 92
| 0.689189
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,638
|
ios_facts.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ios_facts.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
---
module: ios_facts
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
"""
EXAMPLES = r"""
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
ios_facts=dict(type=bool),
),
supports_check_mode=True
)
module.exit_json(ios_facts=module.params['ios_facts'])
if __name__ == '__main__':
main()
| 691
|
Python
|
.py
| 24
| 25.208333
| 92
| 0.683409
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,639
|
echo1.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/echo1.py
|
#!/usr/bin/python
from __future__ import annotations
from ansible_collections.testns.testcoll.plugins.module_utils.echo_impl import do_echo
def main():
do_echo()
if __name__ == '__main__':
main()
| 209
|
Python
|
.py
| 7
| 27
| 86
| 0.71066
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,640
|
ping.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ping.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: ping
version_added: historical
short_description: Try to connect to host, verify a usable python and return C(pong) on success
description:
- A trivial test module, this module always returns C(pong) on successful
contact. It does not make sense in playbooks, but it is useful from
C(/usr/bin/ansible) to verify the ability to login and that a usable Python is configured.
- This is NOT ICMP ping, this is just a trivial test module that requires Python on the remote-node.
- For Windows targets, use the M(ansible.windows.win_ping) module instead.
- For Network targets, use the M(ansible.netcommon.net_ping) module instead.
options:
data:
description:
- Data to return for the C(ping) return value.
- If this parameter is set to C(crash), the module will cause an exception.
type: str
default: pong
seealso:
- module: ansible.netcommon.net_ping
- module: ansible.windows.win_ping
author:
- Ansible Core Team
- Michael DeHaan
notes:
- Supports C(check_mode).
"""
EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
- name: Example from an Ansible Playbook
ansible.builtin.ping:
- name: Induce an exception to see what happens
ansible.builtin.ping:
data: crash
"""
RETURN = """
ping:
description: Value provided with the data parameter.
returned: success
type: str
sample: pong
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(type='str', default='pong'),
),
supports_check_mode=True
)
if module.params['data'] == 'crash':
raise Exception("boom")
result = dict(
ping=module.params['data'],
)
module.exit_json(**result)
if __name__ == '__main__':
main()
| 2,169
|
Python
|
.py
| 66
| 29.257576
| 102
| 0.708194
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,641
|
metadata.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/metadata.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: metadata
version_added: 2.12
short_description: Test module with a specific name
description: Test module with a specific name
options:
data:
description: Required option to test module_defaults work
required: True
type: str
author:
- Ansible Core Team
"""
EXAMPLES = """
"""
RETURN = """
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(type='str', required=True),
),
)
module.exit_json()
if __name__ == '__main__':
main()
| 772
|
Python
|
.py
| 32
| 20.875
| 92
| 0.682692
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,642
|
eosfacts.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/eosfacts.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
---
module: eosfacts
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
"""
EXAMPLES = r"""
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
eosfacts=dict(type=bool),
),
supports_check_mode=True
)
module.exit_json(eosfacts=module.params['eosfacts'])
if __name__ == '__main__':
main()
| 687
|
Python
|
.py
| 24
| 25.041667
| 92
| 0.687596
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,643
|
vyosfacts.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/vyosfacts.py
|
# -*- coding: utf-8 -*-
# Copyright: (c) 2022, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
---
module: vyosfacts
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
"""
EXAMPLES = r"""
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
vyosfacts=dict(type=bool),
),
supports_check_mode=True
)
module.exit_json(vyosfacts=module.params['vyosfacts'])
if __name__ == '__main__':
main()
| 691
|
Python
|
.py
| 24
| 25.208333
| 92
| 0.689498
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,644
|
echo2.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/echo2.py
|
#!/usr/bin/python
from __future__ import annotations
from ansible_collections.testns.testcoll.plugins.module_utils.echo_impl import do_echo
def main():
do_echo()
if __name__ == '__main__':
main()
| 209
|
Python
|
.py
| 7
| 27
| 86
| 0.71066
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,645
|
echo_impl.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/module_utils/echo_impl.py
|
from __future__ import annotations
import json
from ansible.module_utils import basic
from ansible.module_utils.basic import _load_params, AnsibleModule
def do_echo():
p = _load_params()
d = json.loads(basic._ANSIBLE_ARGS)
d['ANSIBLE_MODULE_ARGS'] = {}
basic._ANSIBLE_ARGS = json.dumps(d).encode('utf-8')
module = AnsibleModule(argument_spec={})
module.exit_json(args_in=p)
| 401
|
Python
|
.py
| 11
| 33
| 66
| 0.718346
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,646
|
other_echoaction.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/othercoll/plugins/action/other_echoaction.py
|
from __future__ import annotations
from ansible_collections.testns.testcoll.plugins.action.echoaction import ActionModule as BaseAM
class ActionModule(BaseAM):
pass
| 172
|
Python
|
.py
| 4
| 40.25
| 96
| 0.842424
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,647
|
other_echo1.py
|
ansible_ansible/test/integration/targets/module_defaults/collections/ansible_collections/testns/othercoll/plugins/modules/other_echo1.py
|
#!/usr/bin/python
from __future__ import annotations
from ansible_collections.testns.testcoll.plugins.module_utils.echo_impl import do_echo
def main():
do_echo()
if __name__ == '__main__':
main()
| 209
|
Python
|
.py
| 7
| 27
| 86
| 0.71066
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,648
|
test_module_defaults.py
|
ansible_ansible/test/integration/targets/module_defaults/library/test_module_defaults.py
|
#!/usr/bin/python
from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
arg1=dict(type='str', default='default1'),
arg2=dict(type='str', default='default2'),
arg3=dict(type='str', default='default3'),
),
supports_check_mode=True
)
result = dict(
test_module_defaults=dict(
arg1=module.params['arg1'],
arg2=module.params['arg2'],
arg3=module.params['arg3'],
),
)
module.exit_json(**result)
if __name__ == '__main__':
main()
| 656
|
Python
|
.py
| 22
| 22.318182
| 54
| 0.580542
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,649
|
legacy_ping.py
|
ansible_ansible/test/integration/targets/module_defaults/library/legacy_ping.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: ping
version_added: historical
short_description: Try to connect to host, verify a usable python and return C(pong) on success
description:
- A trivial test module, this module always returns C(pong) on successful
contact. It does not make sense in playbooks, but it is useful from
C(/usr/bin/ansible) to verify the ability to login and that a usable Python is configured.
- This is NOT ICMP ping, this is just a trivial test module that requires Python on the remote-node.
- For Windows targets, use the M(ansible.windows.win_ping) module instead.
- For Network targets, use the M(ansible.netcommon.net_ping) module instead.
options:
data:
description:
- Data to return for the C(ping) return value.
- If this parameter is set to C(crash), the module will cause an exception.
type: str
default: pong
seealso:
- module: ansible.netcommon.net_ping
- module: ansible.windows.win_ping
author:
- Ansible Core Team
- Michael DeHaan
notes:
- Supports C(check_mode).
"""
EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
- name: Example from an Ansible Playbook
ansible.builtin.ping:
- name: Induce an exception to see what happens
ansible.builtin.ping:
data: crash
"""
RETURN = """
ping:
description: Value provided with the data parameter.
returned: success
type: str
sample: pong
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(type='str', default='pong'),
),
supports_check_mode=True
)
if module.params['data'] == 'crash':
raise Exception("boom")
result = dict(
ping=module.params['data'],
)
module.exit_json(**result)
if __name__ == '__main__':
main()
| 2,169
|
Python
|
.py
| 66
| 29.257576
| 102
| 0.708194
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,650
|
debug.py
|
ansible_ansible/test/integration/targets/module_defaults/action_plugins/debug.py
|
# Copyright 2012, Dag Wieers <dag@wieers.com>
# Copyright 2016, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
from ansible.errors import AnsibleUndefinedVariable
from ansible.module_utils.six import string_types
from ansible.module_utils.common.text.converters import to_text
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
""" Print statements during execution """
TRANSFERS_FILES = False
_VALID_ARGS = frozenset(('msg', 'var', 'verbosity'))
def run(self, tmp=None, task_vars=None):
if task_vars is None:
task_vars = dict()
if 'msg' in self._task.args and 'var' in self._task.args:
return {"failed": True, "msg": "'msg' and 'var' are incompatible options"}
result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
# get task verbosity
verbosity = int(self._task.args.get('verbosity', 0))
if verbosity <= self._display.verbosity:
if 'msg' in self._task.args:
result['msg'] = self._task.args['msg']
elif 'var' in self._task.args:
try:
results = self._templar.template(self._task.args['var'], convert_bare=True, fail_on_undefined=True)
if results == self._task.args['var']:
# if results is not str/unicode type, raise an exception
if not isinstance(results, string_types):
raise AnsibleUndefinedVariable
# If var name is same as result, try to template it
results = self._templar.template("{{" + results + "}}", convert_bare=True, fail_on_undefined=True)
except AnsibleUndefinedVariable as e:
results = u"VARIABLE IS NOT DEFINED!"
if self._display.verbosity > 0:
results += u": %s" % to_text(e)
if isinstance(self._task.args['var'], (list, dict)):
# If var is a list or dict, use the type as key to display
result[to_text(type(self._task.args['var']))] = results
else:
result[self._task.args['var']] = results
else:
result['msg'] = 'Hello world!'
# force flag to make debug output module always verbose
result['_ansible_verbose_always'] = True
else:
result['skipped_reason'] = "Verbosity threshold not met."
result['skipped'] = True
result['failed'] = False
return result
| 3,323
|
Python
|
.py
| 65
| 40.861538
| 122
| 0.619914
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,651
|
test-cli.py
|
ansible_ansible/test/integration/targets/cli/test-cli.py
|
#!/usr/bin/env python
# Copyright (c) 2019 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
import os
import pexpect
os.environ['ANSIBLE_NOCOLOR'] = '1'
out = pexpect.run(
'ansible localhost -m debug -a msg="{{ ansible_password }}" -k',
events={
'SSH password:': '{{ 1 + 2 }}\n'
}
)
assert b'{{ 1 + 2 }}' in out
| 444
|
Python
|
.py
| 14
| 28.928571
| 92
| 0.656471
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,652
|
test_k_and_K.py
|
ansible_ansible/test/integration/targets/cli/test_k_and_K.py
|
#!/usr/bin/env python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
import os
import sys
import pexpect
os.environ['ANSIBLE_NOCOLOR'] = '1'
out = pexpect.run(
'ansible -c ssh -i localhost, -u cliuser1 -e ansible_python_interpreter={0} '
'-m command -a whoami -Kkb --become-user cliuser2 localhost'.format(sys.argv[1]),
events={
'SSH password:': 'secretpassword\n',
'BECOME password': 'secretpassword\n',
},
timeout=10
)
print(out)
assert b'cliuser2' in out
| 582
|
Python
|
.py
| 18
| 28.944444
| 92
| 0.70018
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,653
|
check_pkg_resources.py
|
ansible_ansible/test/integration/targets/pkg_resources/lookup_plugins/check_pkg_resources.py
|
"""
This test case verifies that pkg_resources imports from ansible plugins are functional.
If pkg_resources is not installed this test will succeed.
If pkg_resources is installed but is unable to function, this test will fail.
One known failure case this test can detect is when ansible declares a __requires__ and then tests are run without an egg-info directory.
"""
from __future__ import annotations
# noinspection PyUnresolvedReferences
try:
from pkg_resources import Requirement # pylint: disable=unused-import
except ImportError:
Requirement = None
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
return []
| 720
|
Python
|
.py
| 16
| 42.375
| 137
| 0.792264
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,654
|
deprecated.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
name: deprecated
short_description: lookup
description: Lookup.
author:
- Ansible Core Team
"""
EXAMPLES = """#"""
RETURN = """#"""
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, **kwargs):
return []
| 413
|
Python
|
.py
| 15
| 25.2
| 92
| 0.727041
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,655
|
callback_meta.py
|
ansible_ansible/test/integration/targets/ansible/callback_plugins/callback_meta.py
|
# (c) 2020 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.plugins.callback import CallbackBase
import os
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'callback_meta'
def __init__(self, *args, **kwargs):
super(CallbackModule, self).__init__(*args, **kwargs)
self.wants_implicit_tasks = os.environ.get('CB_WANTS_IMPLICIT', False)
def v2_playbook_on_task_start(self, task, is_conditional):
if task.implicit:
self._display.display('saw implicit task')
self._display.display(task.get_name())
| 722
|
Python
|
.py
| 16
| 39.75
| 92
| 0.698571
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,656
|
bad_exec.py
|
ansible_ansible/test/integration/targets/ignore_unreachable/fake_connectors/bad_exec.py
|
from __future__ import annotations
import ansible.plugins.connection.local as ansible_local
from ansible.errors import AnsibleConnectionFailure
from ansible.utils.display import Display
display = Display()
class Connection(ansible_local.Connection):
def exec_command(self, cmd, in_data=None, sudoable=True):
display.debug('Intercepted call to exec remote command')
raise AnsibleConnectionFailure('BADLOCAL Error: this is supposed to fail')
| 464
|
Python
|
.py
| 9
| 47.888889
| 82
| 0.800443
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,657
|
bad_put_file.py
|
ansible_ansible/test/integration/targets/ignore_unreachable/fake_connectors/bad_put_file.py
|
from __future__ import annotations
import ansible.plugins.connection.local as ansible_local
from ansible.errors import AnsibleConnectionFailure
from ansible.utils.display import Display
display = Display()
class Connection(ansible_local.Connection):
def put_file(self, in_path, out_path):
display.debug('Intercepted call to send data')
raise AnsibleConnectionFailure('BADLOCAL Error: this is supposed to fail')
| 435
|
Python
|
.py
| 9
| 44.666667
| 82
| 0.796209
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,658
|
junkping.py
|
ansible_ansible/test/integration/targets/async_extra_data/library/junkping.py
|
#!/usr/bin/python
from __future__ import annotations
import json
def main():
print("junk_before_module_output")
print(json.dumps(dict(changed=False, source='user')))
print("junk_after_module_output")
if __name__ == '__main__':
main()
| 255
|
Python
|
.py
| 9
| 25
| 57
| 0.676349
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,659
|
setup.py
|
ansible_ansible/test/integration/targets/pip/files/setup.py
|
#!/usr/bin/env python
from __future__ import annotations
from setuptools import setup, find_packages
setup(
name="ansible_test_pip_chdir",
version="0",
packages=find_packages(),
entry_points={
'console_scripts': [
'ansible_test_pip_chdir = ansible_test_pip_chdir:main'
]
}
)
| 326
|
Python
|
.py
| 13
| 20.153846
| 66
| 0.651613
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,660
|
update-ignore.py
|
ansible_ansible/test/integration/targets/collection/update-ignore.py
|
#!/usr/bin/env python
"""Rewrite a sanity ignore file to expand Python versions for import ignores and write the file out with the correct Ansible version in the name."""
from __future__ import annotations
import os
import sys
from ansible import release
def main():
ansible_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(release.__file__))))
source_root = os.path.join(ansible_root, 'test', 'lib')
sys.path.insert(0, source_root)
from ansible_test._internal import constants
src_path = 'tests/sanity/ignore.txt'
if not os.path.exists(src_path):
print(f'Skipping updates on non-existent ignore file: {src_path}')
return
directory = os.path.dirname(src_path)
name, ext = os.path.splitext(os.path.basename(src_path))
major_minor = '.'.join(release.__version__.split('.')[:2])
dst_path = os.path.join(directory, f'{name}-{major_minor}{ext}')
with open(src_path) as src_file:
src_lines = src_file.read().splitlines()
dst_lines = []
for line in src_lines:
path, rule = line.split(' ')
if rule != 'import':
dst_lines.append(line)
continue
if path.startswith('plugins/module'):
python_versions = constants.SUPPORTED_PYTHON_VERSIONS
else:
python_versions = constants.CONTROLLER_PYTHON_VERSIONS
for python_version in python_versions:
dst_lines.append(f'{line}-{python_version}')
ignores = '\n'.join(dst_lines) + '\n'
with open(dst_path, 'w') as dst_file:
dst_file.write(ignores)
if __name__ == '__main__':
main()
| 1,643
|
Python
|
.py
| 38
| 36.578947
| 148
| 0.655738
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,661
|
test-vars_prompt.py
|
ansible_ansible/test/integration/targets/builtin_vars_prompt/test-vars_prompt.py
|
#!/usr/bin/env python
from __future__ import annotations
import os
import pexpect
import sys
from ansible.module_utils.six import PY2
if PY2:
log_buffer = sys.stdout
else:
log_buffer = sys.stdout.buffer
env_vars = {
'ANSIBLE_ROLES_PATH': './roles',
'ANSIBLE_NOCOLOR': 'True',
'ANSIBLE_RETRY_FILES_ENABLED': 'False',
}
def run_test(playbook, test_spec, args=None, timeout=10, env=None):
if not env:
env = os.environ.copy()
env.update(env_vars)
if not args:
args = sys.argv[1:]
vars_prompt_test = pexpect.spawn(
'ansible-playbook',
args=[playbook] + args,
timeout=timeout,
env=env,
)
vars_prompt_test.logfile = log_buffer
for item in test_spec[0]:
vars_prompt_test.expect(item[0])
if item[1]:
vars_prompt_test.send(item[1])
vars_prompt_test.expect(test_spec[1])
vars_prompt_test.expect(pexpect.EOF)
vars_prompt_test.close()
# These are the tests to run. Each test is a playbook and a test_spec.
#
# The test_spec is a list with two elements.
#
# The first element is a list of two element tuples. The first is the regexp to look
# for in the output, the second is the line to send.
#
# The last element is the last string of text to look for in the output.
#
tests = [
# Basic vars_prompt
{'playbook': 'vars_prompt-1.yml',
'test_spec': [
[('input:', 'some input\r')],
'"input": "some input"']},
# Custom prompt
{'playbook': 'vars_prompt-2.yml',
'test_spec': [
[('Enter some input:', 'some more input\r')],
'"input": "some more input"']},
# Test confirm, both correct and incorrect
{'playbook': 'vars_prompt-3.yml',
'test_spec': [
[('input:', 'confirm me\r'),
('confirm input:', 'confirm me\r')],
'"input": "confirm me"']},
{'playbook': 'vars_prompt-3.yml',
'test_spec': [
[('input:', 'confirm me\r'),
('confirm input:', 'incorrect\r'),
(r'\*\*\*\*\* VALUES ENTERED DO NOT MATCH \*\*\*\*', ''),
('input:', 'confirm me\r'),
('confirm input:', 'confirm me\r')],
'"input": "confirm me"']},
# Test private
{'playbook': 'vars_prompt-4.yml',
'test_spec': [
[('not_secret', 'this is displayed\r'),
('this is displayed', '')],
'"not_secret": "this is displayed"']},
# Test hashing
{'playbook': 'vars_prompt-5.yml',
'test_spec': [
[('password', 'Scenic-Improving-Payphone\r'),
('confirm password', 'Scenic-Improving-Payphone\r')],
r'"password": "\$6\$']},
# Test variables in prompt field
# https://github.com/ansible/ansible/issues/32723
{'playbook': 'vars_prompt-6.yml',
'test_spec': [
[('prompt from variable:', 'input\r')],
'']},
# Test play vars coming from vars_prompt
# https://github.com/ansible/ansible/issues/37984
{'playbook': 'vars_prompt-7.yml',
'test_spec': [
[('prompting for host:', 'testhost\r')],
r'testhost.*ok=1']},
# Test play unsafe toggle
{'playbook': 'unsafe.yml',
'test_spec': [
[('prompting for variable:', '{{whole}}\r')],
r'testhost.*ok=2']},
# Test unsupported keys
{'playbook': 'unsupported.yml',
'test_spec': [
[],
"Invalid vars_prompt data structure, found unsupported key 'when'"]},
]
for t in tests:
run_test(playbook=t['playbook'], test_spec=t['test_spec'])
| 3,527
|
Python
|
.py
| 106
| 27.122642
| 84
| 0.585344
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,662
|
test_test.py
|
ansible_ansible/test/integration/targets/collections_plugin_namespace/collection_root/ansible_collections/my_ns/my_col/plugins/test/test_test.py
|
from __future__ import annotations
def test_name_ok(value):
return __name__ == 'ansible_collections.my_ns.my_col.plugins.test.test_test'
class TestModule:
def tests(self):
return {
'test_name_ok': test_name_ok,
}
| 253
|
Python
|
.py
| 8
| 25.625
| 80
| 0.639004
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,663
|
lookup_name.py
|
ansible_ansible/test/integration/targets/collections_plugin_namespace/collection_root/ansible_collections/my_ns/my_col/plugins/lookup/lookup_name.py
|
from __future__ import annotations
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
return [__name__]
| 189
|
Python
|
.py
| 5
| 33.8
| 46
| 0.740331
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,664
|
lookup_no_future_boilerplate.py
|
ansible_ansible/test/integration/targets/collections_plugin_namespace/collection_root/ansible_collections/my_ns/my_col/plugins/lookup/lookup_no_future_boilerplate.py
|
# do not add future boilerplate to this plugin
# specifically, do not add absolute_import, as the purpose of this plugin is to test implicit relative imports on Python 2.x
from __future__ import annotations
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
return [__name__]
| 361
|
Python
|
.py
| 7
| 48.428571
| 124
| 0.769231
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,665
|
test_filter.py
|
ansible_ansible/test/integration/targets/collections_plugin_namespace/collection_root/ansible_collections/my_ns/my_col/plugins/filter/test_filter.py
|
from __future__ import annotations
def filter_name(a):
return __name__
class FilterModule(object):
def filters(self):
filters = {
'filter_name': filter_name,
}
return filters
| 224
|
Python
|
.py
| 9
| 18.444444
| 39
| 0.609524
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,666
|
test.py
|
ansible_ansible/test/integration/targets/old_style_cache_plugins/plugins/inventory/test.py
|
# Copyright (c) 2019 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
name: test
plugin_type: inventory
short_description: test inventory source
extends_documentation_fragment:
- inventory_cache
"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
class InventoryModule(BaseInventoryPlugin, Cacheable):
NAME = 'test'
def populate(self, hosts):
for host in list(hosts.keys()):
self.inventory.add_host(host, group='all')
for hostvar, hostval in hosts[host].items():
self.inventory.set_variable(host, hostvar, hostval)
def get_hosts(self):
return {'host1': {'one': 'two'}, 'host2': {'three': 'four'}}
def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path)
self.load_cache_plugin()
cache_key = self.get_cache_key(path)
# cache may be True or False at this point to indicate if the inventory is being refreshed
# get the user's cache option
cache_setting = self.get_option('cache')
attempt_to_read_cache = cache_setting and cache
cache_needs_update = cache_setting and not cache
# attempt to read the cache if inventory isn't being refreshed and the user has caching enabled
if attempt_to_read_cache:
try:
results = self._cache[cache_key]
except KeyError:
# This occurs if the cache_key is not in the cache or if the cache_key expired, so the cache needs to be updated
cache_needs_update = True
if cache_needs_update:
results = self.get_hosts()
# set the cache
self._cache[cache_key] = results
self.populate(results)
| 1,923
|
Python
|
.py
| 41
| 38.170732
| 128
| 0.655228
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,667
|
configurable_redis.py
|
ansible_ansible/test/integration/targets/old_style_cache_plugins/plugins/cache/configurable_redis.py
|
# (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
cache: configurable_redis
short_description: Use Redis DB for cache
description:
- This cache uses JSON formatted, per host records saved in Redis.
version_added: "1.9"
requirements:
- redis>=2.4.5 (python lib)
options:
_uri:
description:
- A colon separated string of connection information for Redis.
required: True
env:
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
ini:
- key: fact_caching_connection
section: defaults
_prefix:
description: User defined prefix to use when creating the DB entries
default: ansible_facts
env:
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
ini:
- key: fact_caching_prefix
section: defaults
_timeout:
default: 86400
description: Expiration timeout for the cache plugin data
env:
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
ini:
- key: fact_caching_timeout
section: defaults
type: integer
"""
import time
import json
from ansible.errors import AnsibleError
from ansible.parsing.ajson import AnsibleJSONEncoder, AnsibleJSONDecoder
from ansible.plugins.cache import BaseCacheModule
from ansible.utils.display import Display
try:
from redis import StrictRedis, VERSION
except ImportError:
raise AnsibleError("The 'redis' python module (version 2.4.5 or newer) is required for the redis fact cache, 'pip install redis'")
display = Display()
class CacheModule(BaseCacheModule):
"""
A caching module backed by redis.
Keys are maintained in a zset with their score being the timestamp
when they are inserted. This allows for the usage of 'zremrangebyscore'
to expire keys. This mechanism is used or a pattern matched 'scan' for
performance.
"""
def __init__(self, *args, **kwargs):
connection = []
super(CacheModule, self).__init__(*args, **kwargs)
if self.get_option('_uri'):
connection = self.get_option('_uri').split(':')
self._timeout = float(self.get_option('_timeout'))
self._prefix = self.get_option('_prefix')
self._cache = {}
self._db = StrictRedis(*connection)
self._keys_set = 'ansible_cache_keys'
def _make_key(self, key):
return self._prefix + key
def get(self, key):
if key not in self._cache:
value = self._db.get(self._make_key(key))
# guard against the key not being removed from the zset;
# this could happen in cases where the timeout value is changed
# between invocations
if value is None:
self.delete(key)
raise KeyError
self._cache[key] = json.loads(value, cls=AnsibleJSONDecoder)
return self._cache.get(key)
def set(self, key, value):
value2 = json.dumps(value, cls=AnsibleJSONEncoder, sort_keys=True, indent=4)
if self._timeout > 0: # a timeout of 0 is handled as meaning 'never expire'
self._db.setex(self._make_key(key), int(self._timeout), value2)
else:
self._db.set(self._make_key(key), value2)
if VERSION[0] == 2:
self._db.zadd(self._keys_set, time.time(), key)
else:
self._db.zadd(self._keys_set, {key: time.time()})
self._cache[key] = value
def _expire_keys(self):
if self._timeout > 0:
expiry_age = time.time() - self._timeout
self._db.zremrangebyscore(self._keys_set, 0, expiry_age)
def keys(self):
self._expire_keys()
return self._db.zrange(self._keys_set, 0, -1)
def contains(self, key):
self._expire_keys()
return (self._db.zrank(self._keys_set, key) is not None)
def delete(self, key):
if key in self._cache:
del self._cache[key]
self._db.delete(self._make_key(key))
self._db.zrem(self._keys_set, key)
def flush(self):
for key in self.keys():
self.delete(key)
def copy(self):
# TODO: there is probably a better way to do this in redis
ret = dict()
for key in self.keys():
ret[key] = self.get(key)
return ret
def __getstate__(self):
return dict()
def __setstate__(self, data):
self.__init__()
| 4,605
|
Python
|
.py
| 121
| 30
| 134
| 0.620852
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,668
|
legacy_redis.py
|
ansible_ansible/test/integration/targets/old_style_cache_plugins/plugins/cache/legacy_redis.py
|
# (c) 2014, Brian Coca, Josh Drake, et al
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
cache: redis
short_description: Use Redis DB for cache
description:
- This cache uses JSON formatted, per host records saved in Redis.
version_added: "1.9"
requirements:
- redis>=2.4.5 (python lib)
options:
_uri:
description:
- A colon separated string of connection information for Redis.
required: True
env:
- name: ANSIBLE_CACHE_PLUGIN_CONNECTION
ini:
- key: fact_caching_connection
section: defaults
_prefix:
description: User defined prefix to use when creating the DB entries
env:
- name: ANSIBLE_CACHE_PLUGIN_PREFIX
ini:
- key: fact_caching_prefix
section: defaults
_timeout:
default: 86400
description: Expiration timeout for the cache plugin data
env:
- name: ANSIBLE_CACHE_PLUGIN_TIMEOUT
ini:
- key: fact_caching_timeout
section: defaults
type: integer
"""
import time
import json
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.cache import BaseCacheModule
try:
from redis import StrictRedis, VERSION
except ImportError:
raise AnsibleError("The 'redis' python module (version 2.4.5 or newer) is required for the redis fact cache, 'pip install redis'")
class CacheModule(BaseCacheModule):
"""
A caching module backed by redis.
Keys are maintained in a zset with their score being the timestamp
when they are inserted. This allows for the usage of 'zremrangebyscore'
to expire keys. This mechanism is used or a pattern matched 'scan' for
performance.
"""
def __init__(self, *args, **kwargs):
if C.CACHE_PLUGIN_CONNECTION:
connection = C.CACHE_PLUGIN_CONNECTION.split(':')
else:
connection = []
self._timeout = float(C.CACHE_PLUGIN_TIMEOUT)
self._prefix = C.CACHE_PLUGIN_PREFIX
self._cache = {}
self._db = StrictRedis(*connection)
self._keys_set = 'ansible_cache_keys'
def _make_key(self, key):
return self._prefix + key
def get(self, key):
if key not in self._cache:
value = self._db.get(self._make_key(key))
# guard against the key not being removed from the zset;
# this could happen in cases where the timeout value is changed
# between invocations
if value is None:
self.delete(key)
raise KeyError
self._cache[key] = json.loads(value)
return self._cache.get(key)
def set(self, key, value):
value2 = json.dumps(value)
if self._timeout > 0: # a timeout of 0 is handled as meaning 'never expire'
self._db.setex(self._make_key(key), int(self._timeout), value2)
else:
self._db.set(self._make_key(key), value2)
if VERSION[0] == 2:
self._db.zadd(self._keys_set, time.time(), key)
else:
self._db.zadd(self._keys_set, {key: time.time()})
self._cache[key] = value
def _expire_keys(self):
if self._timeout > 0:
expiry_age = time.time() - self._timeout
self._db.zremrangebyscore(self._keys_set, 0, expiry_age)
def keys(self):
self._expire_keys()
return self._db.zrange(self._keys_set, 0, -1)
def contains(self, key):
self._expire_keys()
return (self._db.zrank(self._keys_set, key) is not None)
def delete(self, key):
if key in self._cache:
del self._cache[key]
self._db.delete(self._make_key(key))
self._db.zrem(self._keys_set, key)
def flush(self):
for key in self.keys():
self.delete(key)
def copy(self):
# TODO: there is probably a better way to do this in redis
ret = dict()
for key in self.keys():
ret[key] = self.get(key)
return ret
def __getstate__(self):
return dict()
def __setstate__(self, data):
self.__init__()
| 4,338
|
Python
|
.py
| 118
| 28.576271
| 134
| 0.612434
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,669
|
test_test.py
|
ansible_ansible/test/integration/targets/ansible-test-config/ansible_collections/ns/col/tests/unit/plugins/module_utils/test_test.py
|
from __future__ import annotations
from ansible_collections.ns.col.plugins.module_utils import test
def test_me():
assert test
| 134
|
Python
|
.py
| 4
| 30.75
| 64
| 0.795276
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,670
|
test.py
|
ansible_ansible/test/integration/targets/ansible-test-config/ansible_collections/ns/col/plugins/module_utils/test.py
|
from __future__ import annotations
import sys
import os
def version_to_str(value):
return '.'.join(str(v) for v in value)
controller_min_python_version = tuple(int(v) for v in os.environ['ANSIBLE_CONTROLLER_MIN_PYTHON_VERSION'].split('.'))
current_python_version = sys.version_info[:2]
if current_python_version < controller_min_python_version:
raise Exception('Current Python version %s is lower than the minimum controller Python version of %s. '
'Did the collection config get ignored?' % (version_to_str(current_python_version), version_to_str(controller_min_python_version)))
| 615
|
Python
|
.py
| 10
| 57.1
| 151
| 0.741235
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,671
|
slurp.py
|
ansible_ansible/test/integration/targets/fetch/injection/library/slurp.py
|
#!/usr/bin/python
from __future__ import annotations
DOCUMENTATION = """
module: fakeslurp
short_description: fake slurp module
description:
- this is a fake slurp module
options:
_notreal:
description: really not a real slurp
author:
- me
"""
import json
import random
bad_responses = ['../foo', '../../foo', '../../../foo', '/../../../foo', '/../foo', '//..//foo', '..//..//foo']
def main():
print(json.dumps(dict(changed=False, content='', encoding='base64', source=random.choice(bad_responses))))
if __name__ == '__main__':
main()
| 607
|
Python
|
.py
| 20
| 25.75
| 111
| 0.587219
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,672
|
ansible_test_service.py
|
ansible_ansible/test/integration/targets/service/files/ansible_test_service.py
|
#!/usr/bin/env python
# this is mostly based off of the code found here:
# http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/
from __future__ import annotations
import os
import resource
import signal
import time
UMASK = 0
WORKDIR = "/"
MAXFD = 1024
if (hasattr(os, "devnull")):
REDIRECT_TO = os.devnull
else:
REDIRECT_TO = "/dev/null"
def createDaemon():
try:
pid = os.fork()
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if (pid == 0):
os.setsid()
try:
pid = os.fork()
except OSError as e:
raise Exception("%s [%d]" % (e.strerror, e.errno))
if (pid == 0):
os.chdir(WORKDIR)
os.umask(UMASK)
else:
with open('/var/run/ansible_test_service.pid', 'w') as f:
f.write("%d\n" % pid)
os._exit(0)
else:
os._exit(0)
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = MAXFD
for fd in range(0, maxfd):
try:
os.close(fd)
except OSError: # ERROR, fd wasn't open to begin with (ignored)
pass
os.open(REDIRECT_TO, os.O_RDWR)
os.dup2(0, 1)
os.dup2(0, 2)
return (0)
if __name__ == "__main__":
signal.signal(signal.SIGHUP, signal.SIG_IGN)
retCode = createDaemon()
while True:
time.sleep(1000)
| 1,469
|
Python
|
.py
| 52
| 21.653846
| 78
| 0.580114
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,673
|
testserver.py
|
ansible_ansible/test/integration/targets/uri/files/testserver.py
|
from __future__ import annotations
import http.server
import socketserver
import sys
if __name__ == '__main__':
PORT = int(sys.argv[1])
class Handler(http.server.SimpleHTTPRequestHandler):
pass
Handler.extensions_map['.json'] = 'application/json'
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
| 353
|
Python
|
.py
| 11
| 28.181818
| 56
| 0.704142
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,674
|
test_peercert.py
|
ansible_ansible/test/integration/targets/module_utils_urls/library/test_peercert.py
|
#!/usr/bin/python
# Copyright: (c) 2020, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = r"""
---
module: test_perrcert
short_description: Test getting the peer certificate of a HTTP response
description: Test getting the peer certificate of a HTTP response.
options:
url:
description: The endpoint to get the peer cert for
required: true
type: str
author:
- Ansible Project
"""
EXAMPLES = r"""
#
"""
RETURN = r"""
#
"""
import base64
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_text
from ansible.module_utils.urls import getpeercert, Request
def get_x509_shorthand(name, value):
prefix = {
'countryName': 'C',
'stateOrProvinceName': 'ST',
'localityName': 'L',
'organizationName': 'O',
'commonName': 'CN',
'organizationalUnitName': 'OU',
}[name]
return '%s=%s' % (prefix, value)
def main():
module_args = dict(
url=dict(type='str', required=True),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True,
)
result = {
'changed': False,
'cert': None,
'raw_cert': None,
}
req = Request().get(module.params['url'])
try:
cert = getpeercert(req)
b_cert = getpeercert(req, binary_form=True)
finally:
req.close()
if cert:
processed_cert = {
'issuer': '',
'not_after': cert.get('notAfter', None),
'not_before': cert.get('notBefore', None),
'serial_number': cert.get('serialNumber', None),
'subject': '',
'version': cert.get('version', None),
}
for field in ['issuer', 'subject']:
field_values = []
for x509_part in cert.get(field, []):
field_values.append(get_x509_shorthand(x509_part[0][0], x509_part[0][1]))
processed_cert[field] = ",".join(field_values)
result['cert'] = processed_cert
if b_cert:
result['raw_cert'] = to_text(base64.b64encode(b_cert))
module.exit_json(**result)
if __name__ == '__main__':
main()
| 2,293
|
Python
|
.py
| 76
| 24.131579
| 92
| 0.612477
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,675
|
testserver.py
|
ansible_ansible/test/integration/targets/get_url/files/testserver.py
|
from __future__ import annotations
import http.server
import socketserver
import sys
if __name__ == '__main__':
PORT = int(sys.argv[1])
class Handler(http.server.SimpleHTTPRequestHandler):
pass
Handler.extensions_map['.json'] = 'application/json'
httpd = socketserver.TCPServer(("", PORT), Handler)
httpd.serve_forever()
| 353
|
Python
|
.py
| 11
| 28.181818
| 56
| 0.704142
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,676
|
do-not-check-me.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-use-compat-six/ansible_collections/ns/col/do-not-check-me.py
|
from __future__ import annotations
import six
def do_stuff():
assert six.text_type
| 90
|
Python
|
.py
| 4
| 19.75
| 34
| 0.759036
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,677
|
check-me.py
|
ansible_ansible/test/integration/targets/ansible-test-sanity-use-compat-six/ansible_collections/ns/col/plugins/modules/check-me.py
|
from __future__ import annotations
import six
def do_stuff():
assert six.text_type
| 90
|
Python
|
.py
| 4
| 19.75
| 34
| 0.759036
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,678
|
testserver.py
|
ansible_ansible/test/integration/targets/ansible-galaxy/files/testserver.py
|
from __future__ import annotations
import http.server
import socketserver
import ssl
if __name__ == '__main__':
Handler = http.server.SimpleHTTPRequestHandler
context = ssl.SSLContext()
context.load_cert_chain(certfile='./cert.pem', keyfile='./key.pem')
httpd = socketserver.TCPServer(("", 4443), Handler)
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
httpd.serve_forever()
| 422
|
Python
|
.py
| 11
| 34.909091
| 71
| 0.72549
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,679
|
convert_camelCase.py
|
ansible_ansible/test/integration/targets/dict_transformations/library/convert_camelCase.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: convert_camelCase
short_description: test converting data to camelCase
description: test converting data to camelCase
options:
data:
description: Data to modify
type: dict
required: True
capitalize_first:
description: Whether to capitalize the first character
default: False
type: bool
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(type='dict', required=True),
capitalize_first=dict(type='bool', default=False),
),
)
result = snake_dict_to_camel_dict(
module.params['data'],
module.params['capitalize_first']
)
module.exit_json(data=result)
if __name__ == '__main__':
main()
| 1,060
|
Python
|
.py
| 35
| 25.857143
| 92
| 0.698914
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,680
|
convert_snake_case.py
|
ansible_ansible/test/integration/targets/dict_transformations/library/convert_snake_case.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: convert_snake_case
short_description: test converting data to snake_case
description: test converting data to snake_case
options:
data:
description: Data to modify
type: dict
required: True
reversible:
description:
- Make the snake_case conversion in a way that can be converted back to the original value
- For example, convert IAMUser to i_a_m_user instead of iam_user
default: False
ignore_list:
description: list of top level keys that should not have their contents converted
type: list
default: []
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(type='dict', required=True),
reversible=dict(type='bool', default=False),
ignore_list=dict(type='list', default=[]),
),
)
result = camel_dict_to_snake_dict(
module.params['data'],
module.params['reversible'],
module.params['ignore_list']
)
module.exit_json(data=result)
if __name__ == '__main__':
main()
| 1,381
|
Python
|
.py
| 42
| 28.02381
| 96
| 0.688772
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,681
|
run-with-pty.py
|
ansible_ansible/test/integration/targets/fork_safe_stdio/run-with-pty.py
|
#!/usr/bin/env python
"""Run a command using a PTY."""
from __future__ import annotations
import sys
if sys.version_info < (3, 10):
import vendored_pty as pty
else:
import pty
sys.exit(1 if pty.spawn(sys.argv[1:]) else 0)
| 233
|
Python
|
.py
| 9
| 23.666667
| 45
| 0.705882
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,682
|
vendored_pty.py
|
ansible_ansible/test/integration/targets/fork_safe_stdio/vendored_pty.py
|
# Vendored copy of https://github.com/python/cpython/blob/3680ebed7f3e529d01996dd0318601f9f0d02b4b/Lib/pty.py
# PSF License (see licenses/PSF-license.txt or https://opensource.org/licenses/Python-2.0)
"""Pseudo terminal utilities."""
# Bugs: No signal handling. Doesn't set slave termios and window size.
# Only tested on Linux, FreeBSD, and macOS.
# See: W. Richard Stevens. 1992. Advanced Programming in the
# UNIX Environment. Chapter 19.
# Author: Steen Lumholt -- with additions by Guido.
from __future__ import annotations
from select import select
import os
import sys
import tty
# names imported directly for test mocking purposes
from os import close, waitpid
from tty import setraw, tcgetattr, tcsetattr
__all__ = ["openpty", "fork", "spawn"]
STDIN_FILENO = 0
STDOUT_FILENO = 1
STDERR_FILENO = 2
CHILD = 0
def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (AttributeError, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, slave_fd
def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = os.ttyname(slave_fd)
os.close(slave_fd)
return master_fd, slave_name
return _open_terminal()
def _open_terminal():
"""Open pty master and return (master_fd, tty_name)."""
for x in 'pqrstuvwxyzPQRST':
for y in '0123456789abcdef':
pty_name = '/dev/pty' + x + y
try:
fd = os.open(pty_name, os.O_RDWR)
except OSError:
continue
return (fd, '/dev/tty' + x + y)
raise OSError('out of pty devices')
def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead."""
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except ImportError:
return result
try:
ioctl(result, I_PUSH, "ptem")
ioctl(result, I_PUSH, "ldterm")
except OSError:
pass
return result
def fork():
"""fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal."""
try:
pid, fd = os.forkpty()
except (AttributeError, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
# os.forkpty() already set us session leader
pass
return pid, fd
master_fd, slave_fd = openpty()
pid = os.fork()
if pid == CHILD:
# Establish a new session.
os.setsid()
os.close(master_fd)
# Slave becomes stdin/stdout/stderr of child.
os.dup2(slave_fd, STDIN_FILENO)
os.dup2(slave_fd, STDOUT_FILENO)
os.dup2(slave_fd, STDERR_FILENO)
if slave_fd > STDERR_FILENO:
os.close(slave_fd)
# Explicitly open the tty to make it become a controlling tty.
tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
os.close(tmp_fd)
else:
os.close(slave_fd)
# Parent and child process.
return pid, master_fd
def _writen(fd, data):
"""Write all the data to a descriptor."""
while data:
n = os.write(fd, data)
data = data[n:]
def _read(fd):
"""Default read function."""
return os.read(fd, 1024)
def _copy(master_fd, master_read=_read, stdin_read=_read):
"""Parent copy loop.
Copies
pty master -> standard output (master_read)
standard input -> pty master (stdin_read)"""
fds = [master_fd, STDIN_FILENO]
while fds:
rfds, _wfds, _xfds = select(fds, [], [])
if master_fd in rfds:
# Some OSes signal EOF by returning an empty byte string,
# some throw OSErrors.
try:
data = master_read(master_fd)
except OSError:
data = b""
if not data: # Reached EOF.
return # Assume the child process has exited and is
# unreachable, so we clean up.
else:
os.write(STDOUT_FILENO, data)
if STDIN_FILENO in rfds:
data = stdin_read(STDIN_FILENO)
if not data:
fds.remove(STDIN_FILENO)
else:
_writen(master_fd, data)
def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if isinstance(argv, str):
argv = (argv,)
sys.audit('pty.spawn', argv)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tcgetattr(STDIN_FILENO)
setraw(STDIN_FILENO)
restore = True
except tty.error: # This is the same as termios.error
restore = False
try:
_copy(master_fd, master_read, stdin_read)
finally:
if restore:
tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)
close(master_fd)
return waitpid(pid, 0)[1]
| 5,448
|
Python
|
.py
| 160
| 26.65
| 109
| 0.605934
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,683
|
spewstdio.py
|
ansible_ansible/test/integration/targets/fork_safe_stdio/callback_plugins/spewstdio.py
|
from __future__ import annotations
import atexit
import os
import sys
from ansible.plugins.callback import CallbackBase
from ansible.utils.display import Display
from threading import Thread
# This callback plugin reliably triggers the deadlock from https://github.com/ansible/ansible-runner/issues/1164 when
# run on a TTY/PTY. It starts a thread in the controller that spews unprintable characters to stdout as fast as
# possible, while causing forked children to write directly to the inherited stdout immediately post-fork. If a fork
# occurs while the spew thread holds stdout's internal BufferedIOWriter lock, the lock will be orphaned in the child,
# and attempts to write to stdout there will hang forever.
# Any mechanism that ensures non-main threads do not hold locks before forking should allow this test to pass.
# ref: https://docs.python.org/3/library/io.html#multi-threading
# ref: https://github.com/python/cpython/blob/0547a981ae413248b21a6bb0cb62dda7d236fe45/Modules/_io/bufferedio.c#L268
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_NAME = 'spewstdio'
def __init__(self):
super().__init__()
self.display = Display()
if os.environ.get('SPEWSTDIO_ENABLED', '0') != '1':
self.display.warning('spewstdio test plugin loaded but disabled; set SPEWSTDIO_ENABLED=1 to enable')
return
self.display = Display()
self._keep_spewing = True
# cause the child to write directly to stdout immediately post-fork
os.register_at_fork(after_in_child=lambda: print(f"hi from forked child pid {os.getpid()}"))
# in passing cases, stop spewing when the controller is exiting to prevent fatal errors on final flush
atexit.register(self.stop_spew)
self._spew_thread = Thread(target=self.spew, daemon=True)
self._spew_thread.start()
def stop_spew(self):
self._keep_spewing = False
def spew(self):
# dump a message so we know the callback thread has started
self.display.warning("spewstdio STARTING NONPRINTING SPEW ON BACKGROUND THREAD")
while self._keep_spewing:
# dump a non-printing control character directly to stdout to avoid junking up the screen while still
# doing lots of writes and flushes.
sys.stdout.write('\x1b[K')
sys.stdout.flush()
self.display.warning("spewstdio STOPPING SPEW")
| 2,450
|
Python
|
.py
| 43
| 50.465116
| 117
| 0.727615
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,684
|
foo-py26.txt
|
ansible_ansible/test/integration/targets/template/files/foo-py26.txt
|
templated_var_loaded
{
"bool": true,
"multi_part": "1Foo",
"null_type": null,
"number": 5,
"string_num": "5"
}
| 132
|
Python
|
.py
| 8
| 12.875
| 25
| 0.552846
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,685
|
myplugin.py
|
ansible_ansible/test/integration/targets/template/role_filter/filter_plugins/myplugin.py
|
#!/usr/bin/env python
from __future__ import annotations
class FilterModule(object):
def filters(self):
return {'parse_ip': self.parse_ip}
def parse_ip(self, ip):
return ip
| 201
|
Python
|
.py
| 7
| 23.714286
| 42
| 0.668421
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,686
|
test.py
|
ansible_ansible/test/integration/targets/ansible-test-integration-targets/test.py
|
#!/usr/bin/env python
from __future__ import annotations
import subprocess
import unittest
class OptionsTest(unittest.TestCase):
options = (
'unsupported',
'disabled',
'unstable',
'destructive',
)
def test_options(self):
for option in self.options:
with self.subTest(option=option):
try:
command = ['ansible-test', 'integration', '--list-targets']
skip_all = subprocess.run([*command, f'{option}_a', f'{option}_b'], text=True, capture_output=True, check=True)
allow_all = subprocess.run([*command, f'--allow-{option}', f'{option}_a', f'{option}_b'], text=True, capture_output=True, check=True)
allow_first = subprocess.run([*command, f'{option}/{option}_a', f'{option}_b'], text=True, capture_output=True, check=True)
allow_last = subprocess.run([*command, f'{option}_a', f'{option}/{option}_b'], text=True, capture_output=True, check=True)
self.assertEqual(skip_all.stdout.splitlines(), [])
self.assertEqual(allow_all.stdout.splitlines(), [f'{option}_a', f'{option}_b'])
self.assertEqual(allow_first.stdout.splitlines(), [f'{option}_a'])
self.assertEqual(allow_last.stdout.splitlines(), [f'{option}_b'])
except subprocess.CalledProcessError as ex:
raise Exception(f'{ex}:\n>>> Standard Output:\n{ex.stdout}\n>>> Standard Error:\n{ex.stderr}') from ex
class PrefixesTest(unittest.TestCase):
def test_prefixes(self):
try:
command = ['ansible-test', 'integration', '--list-targets']
something = subprocess.run([*command, 'something/'], text=True, capture_output=True, check=True)
self.assertEqual(something.stdout.splitlines(), ['one-part_test', 'two_part_test'])
except subprocess.CalledProcessError as ex:
raise Exception(f'{ex}:\n>>> Standard Output:\n{ex.stdout}\n>>> Standard Error:\n{ex.stderr}') from ex
if __name__ == '__main__':
unittest.main()
| 2,132
|
Python
|
.py
| 36
| 47.666667
| 153
| 0.601727
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,687
|
tmpdir.py
|
ansible_ansible/test/integration/targets/become_unprivileged/action_plugins/tmpdir.py
|
from __future__ import annotations
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result.update(self._execute_module('ping', task_vars=task_vars))
result['tmpdir'] = self._connection._shell.tmpdir
return result
| 378
|
Python
|
.py
| 8
| 41.25
| 72
| 0.715847
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,688
|
async_test.py
|
ansible_ansible/test/integration/targets/async/library/async_test.py
|
from __future__ import annotations
import json
import sys
from ansible.module_utils.basic import AnsibleModule
def main():
if "--interactive" in sys.argv:
import ansible.module_utils.basic
ansible.module_utils.basic._ANSIBLE_ARGS = json.dumps(dict(
ANSIBLE_MODULE_ARGS=dict(
fail_mode="graceful"
)
))
module = AnsibleModule(
argument_spec=dict(
fail_mode=dict(type='list', default=['success'])
)
)
result = dict(changed=True)
fail_mode = module.params['fail_mode']
try:
if 'leading_junk' in fail_mode:
print("leading junk before module output")
if 'graceful' in fail_mode:
module.fail_json(msg="failed gracefully")
if 'exception' in fail_mode:
raise Exception('failing via exception')
if 'stderr' in fail_mode:
print('printed to stderr', file=sys.stderr)
module.exit_json(**result)
finally:
if 'trailing_junk' in fail_mode:
print("trailing junk after module output")
main()
| 1,117
|
Python
|
.py
| 33
| 25.484848
| 67
| 0.616464
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,689
|
test_throttle.py
|
ansible_ansible/test/integration/targets/throttle/test_throttle.py
|
#!/usr/bin/env python
from __future__ import annotations
import os
import sys
import time
# read the args from sys.argv
throttledir, inventory_hostname, max_throttle = sys.argv[1:]
# format/create additional vars
max_throttle = int(max_throttle)
throttledir = os.path.expanduser(throttledir)
throttlefile = os.path.join(throttledir, inventory_hostname)
try:
# create the file
with open(throttlefile, 'a'):
os.utime(throttlefile, None)
# count the number of files in the dir
throttlelist = os.listdir(throttledir)
print("tasks: %d/%d" % (len(throttlelist), max_throttle))
# if we have too many files, fail
if len(throttlelist) > max_throttle:
print(throttlelist)
raise ValueError("Too many concurrent tasks: %d/%d" % (len(throttlelist), max_throttle))
time.sleep(1.5)
finally:
# remove the file, then wait to make sure it's gone
os.unlink(throttlefile)
while True:
if not os.path.exists(throttlefile):
break
time.sleep(0.1)
| 1,022
|
Python
|
.py
| 30
| 29.766667
| 96
| 0.707786
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,690
|
ini_dupes.py
|
ansible_ansible/test/integration/targets/ansible-config/files/ini_dupes.py
|
#!/usr/bin/env python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
import configparser
import sys
ini_file = sys.argv[1]
c = configparser.ConfigParser(strict=True, inline_comment_prefixes=(';',))
c.read_file(open(ini_file))
| 311
|
Python
|
.py
| 8
| 37.375
| 92
| 0.762542
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,691
|
77788.py
|
ansible_ansible/test/integration/targets/templating_lookups/template_lookups/mock_lookup_plugins/77788.py
|
from __future__ import annotations
from ansible.plugins.lookup import LookupBase
class LookupModule(LookupBase):
def run(self, terms, variables, **kwargs):
return {'one': 1, 'two': 2}
| 199
|
Python
|
.py
| 5
| 35.8
| 46
| 0.722513
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,692
|
test_module.py
|
ansible_ansible/test/integration/targets/ansible-galaxy-collection/files/test_module.py
|
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: ping
version_added: historical
short_description: Try to connect to host, verify a usable python and return C(pong) on success
description:
- A trivial test module, this module always returns C(pong) on successful
contact. It does not make sense in playbooks, but it is useful from
C(/usr/bin/ansible) to verify the ability to login and that a usable Python is configured.
- This is NOT ICMP ping, this is just a trivial test module that requires Python on the remote-node.
- For Windows targets, use the M(ansible.windows.win_ping) module instead.
- For Network targets, use the M(ansible.netcommon.net_ping) module instead.
options:
data:
description:
- Data to return for the C(ping) return value.
- If this parameter is set to C(crash), the module will cause an exception.
type: str
default: pong
seealso:
- module: ansible.netcommon.net_ping
- module: ansible.windows.win_ping
author:
- Ansible Core Team
- Michael DeHaan
"""
EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
- name: Example from an Ansible Playbook
ping:
- name: Induce an exception to see what happens
ping:
data: crash
"""
RETURN = """
ping:
description: value provided with the data parameter
returned: success
type: str
sample: pong
"""
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(type='str', default='pong'),
),
supports_check_mode=True
)
if module.params['data'] == 'crash':
raise Exception("boom")
result = dict(
ping=module.params['data'],
)
module.exit_json(**result)
if __name__ == '__main__':
main()
| 2,089
|
Python
|
.py
| 63
| 29.365079
| 103
| 0.70398
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,693
|
build_bad_tar.py
|
ansible_ansible/test/integration/targets/ansible-galaxy-collection/files/build_bad_tar.py
|
#!/usr/bin/env python
# Copyright: (c) 2020, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
import hashlib
import io
import json
import os
import sys
import tarfile
from ansible.module_utils.common.file import S_IRWXU_RXG_RXO
manifest = {
'collection_info': {
'namespace': 'suspicious',
'name': 'test',
'version': '1.0.0',
'dependencies': {},
},
'file_manifest_file': {
'name': 'FILES.json',
'ftype': 'file',
'chksum_type': 'sha256',
'chksum_sha256': None,
'format': 1
},
'format': 1,
}
files = {
'files': [
{
'name': '.',
'ftype': 'dir',
'chksum_type': None,
'chksum_sha256': None,
'format': 1,
},
],
'format': 1,
}
def add_file(tar_file, filename, b_content, update_files=True):
tar_info = tarfile.TarInfo(filename)
tar_info.size = len(b_content)
tar_info.mode = S_IRWXU_RXG_RXO
tar_file.addfile(tarinfo=tar_info, fileobj=io.BytesIO(b_content))
if update_files:
sha256 = hashlib.sha256()
sha256.update(b_content)
files['files'].append({
'name': filename,
'ftype': 'file',
'chksum_type': 'sha256',
'chksum_sha256': sha256.hexdigest(),
'format': 1
})
collection_tar = os.path.join(sys.argv[1], 'suspicious-test-1.0.0.tar.gz')
with tarfile.open(collection_tar, mode='w:gz') as tar_file:
add_file(tar_file, '../../outside.sh', b"#!/usr/bin/env bash\necho \"you got pwned\"")
b_files = json.dumps(files).encode('utf-8')
b_files_hash = hashlib.sha256()
b_files_hash.update(b_files)
manifest['file_manifest_file']['chksum_sha256'] = b_files_hash.hexdigest()
add_file(tar_file, 'FILES.json', b_files)
add_file(tar_file, 'MANIFEST.json', json.dumps(manifest).encode('utf-8'))
b_manifest = json.dumps(manifest).encode('utf-8')
for name, b in [('MANIFEST.json', b_manifest), ('FILES.json', b_files)]:
b_io = io.BytesIO(b)
tar_info = tarfile.TarInfo(name)
tar_info.size = len(b)
tar_info.mode = 0o0644
tar_file.addfile(tarinfo=tar_info, fileobj=b_io)
| 2,320
|
Python
|
.py
| 70
| 26.685714
| 92
| 0.597048
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,694
|
reset_pulp.py
|
ansible_ansible/test/integration/targets/ansible-galaxy-collection/library/reset_pulp.py
|
#!/usr/bin/python
# Copyright: (c) 2020, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
---
module: reset_pulp
short_description: Resets pulp back to the initial state
description:
- See short_description
options:
pulp_api:
description:
- The Pulp API endpoint.
required: yes
type: str
galaxy_ng_server:
description:
- The Galaxy NG API endpoint.
required: yes
type: str
url_username:
description:
- The username to use when authenticating against Pulp.
required: yes
type: str
url_password:
description:
- The password to use when authenticating against Pulp.
required: yes
type: str
repositories:
description:
- A list of pulp repositories to create.
- Galaxy NG expects a repository that matches C(GALAXY_API_DEFAULT_DISTRIBUTION_BASE_PATH) in
C(/etc/pulp/settings.py) or the default of C(published).
required: yes
type: list
elements: str
namespaces:
description:
- A list of namespaces to create for Galaxy NG.
required: yes
type: list
elements: str
author:
- Jordan Borean (@jborean93)
"""
EXAMPLES = """
- name: reset pulp content
reset_pulp:
pulp_api: http://galaxy:24817
galaxy_ng_server: http://galaxy/api/galaxy/
url_username: username
url_password: password
repository: published
namespaces:
- namespace1
- namespace2
"""
RETURN = """
#
"""
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.urls import fetch_url
from ansible.module_utils.common.text.converters import to_text
def invoke_api(module, url, method='GET', data=None, status_codes=None):
status_codes = status_codes or [200]
headers = {}
if data:
headers['Content-Type'] = 'application/json'
data = json.dumps(data)
resp, info = fetch_url(module, url, method=method, data=data, headers=headers)
if info['status'] not in status_codes:
info['url'] = url
module.fail_json(**info)
data = to_text(resp.read())
if data:
return json.loads(data)
def delete_galaxy_namespace(namespace, module):
""" Deletes the galaxy ng namespace specified. """
ns_uri = '%sv3/namespaces/%s/' % (module.params['galaxy_ng_server'], namespace)
invoke_api(module, ns_uri, method='DELETE', status_codes=[204])
def delete_pulp_distribution(distribution, module):
""" Deletes the pulp distribution at the URI specified. """
task_info = invoke_api(module, distribution, method='DELETE', status_codes=[202])
wait_pulp_task(task_info['task'], module)
def delete_pulp_orphans(module):
""" Deletes any orphaned pulp objects. """
orphan_uri = module.params['galaxy_ng_server'] + 'pulp/api/v3/orphans/'
task_info = invoke_api(module, orphan_uri, method='DELETE', status_codes=[202])
wait_pulp_task(task_info['task'], module)
def delete_pulp_repository(repository, module):
""" Deletes the pulp repository at the URI specified. """
task_info = invoke_api(module, repository, method='DELETE', status_codes=[202])
wait_pulp_task(task_info['task'], module)
def get_galaxy_namespaces(module):
""" Gets a list of galaxy namespaces. """
# No pagination has been implemented, shouldn't need unless we ever exceed 100 namespaces.
namespace_uri = module.params['galaxy_ng_server'] + 'v3/namespaces/?limit=100&offset=0'
ns_info = invoke_api(module, namespace_uri)
return [n['name'] for n in ns_info['data']]
def get_pulp_distributions(module, distribution):
""" Gets a list of all the pulp distributions. """
distro_uri = module.params['galaxy_ng_server'] + 'pulp/api/v3/distributions/ansible/ansible/'
distro_info = invoke_api(module, distro_uri + '?name=' + distribution)
return [module.params['pulp_api'] + r['pulp_href'] for r in distro_info['results']]
def get_pulp_repositories(module, repository):
""" Gets a list of all the pulp repositories. """
repo_uri = module.params['galaxy_ng_server'] + 'pulp/api/v3/repositories/ansible/ansible/'
repo_info = invoke_api(module, repo_uri + '?name=' + repository)
return [module.params['pulp_api'] + r['pulp_href'] for r in repo_info['results']]
def get_repo_collections(repository, module):
collections_uri = module.params['galaxy_ng_server'] + 'v3/plugin/ansible/content/' + repository + '/collections/index/'
# status code 500 isn't really expected, an unhandled exception is causing this instead of a 404
# See https://issues.redhat.com/browse/AAH-2329
info = invoke_api(module, collections_uri + '?limit=100&offset=0', status_codes=[200, 500])
if not info:
return []
return [module.params['pulp_api'] + c['href'] for c in info['data']]
def delete_repo_collection(collection, module):
task_info = invoke_api(module, collection, method='DELETE', status_codes=[202])
wait_pulp_task(task_info['task'], module)
def new_galaxy_namespace(name, module):
""" Creates a new namespace in Galaxy NG. """
ns_uri = module.params['galaxy_ng_server'] + 'v3/namespaces/ '
data = {'name': name, 'groups': []}
ns_info = invoke_api(module, ns_uri, method='POST', data=data, status_codes=[201])
return ns_info['id']
def new_pulp_repository(name, module):
""" Creates a new pulp repository. """
repo_uri = module.params['galaxy_ng_server'] + 'pulp/api/v3/repositories/ansible/ansible/'
# retain_repo_versions to work around https://issues.redhat.com/browse/AAH-2332
data = {'name': name, 'retain_repo_versions': '1024'}
repo_info = invoke_api(module, repo_uri, method='POST', data=data, status_codes=[201])
return repo_info['pulp_href']
def new_pulp_distribution(name, base_path, repository, module):
""" Creates a new pulp distribution for a repository. """
distro_uri = module.params['galaxy_ng_server'] + 'pulp/api/v3/distributions/ansible/ansible/'
data = {'name': name, 'base_path': base_path, 'repository': repository}
task_info = invoke_api(module, distro_uri, method='POST', data=data, status_codes=[202])
task_info = wait_pulp_task(task_info['task'], module)
return module.params['pulp_api'] + task_info['created_resources'][0]
def wait_pulp_task(task, module):
""" Waits for a pulp import task to finish. """
while True:
task_info = invoke_api(module, module.params['pulp_api'] + task)
if task_info['finished_at'] is not None:
break
return task_info
def main():
module_args = dict(
pulp_api=dict(type='str', required=True),
galaxy_ng_server=dict(type='str', required=True),
url_username=dict(type='str', required=True),
url_password=dict(type='str', required=True, no_log=True),
repositories=dict(type='list', elements='str', required=True),
namespaces=dict(type='list', elements='str', required=True),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=False
)
module.params['force_basic_auth'] = True
# It may be due to the process of cleaning up orphans, but we cannot delete the namespace
# while a collection still exists, so this is just a new safety to nuke all collections
# first
for repository in module.params['repositories']:
[delete_repo_collection(c, module) for c in get_repo_collections(repository, module)]
for repository in module.params['repositories']:
[delete_pulp_distribution(d, module) for d in get_pulp_distributions(module, repository)]
[delete_pulp_repository(r, module) for r in get_pulp_repositories(module, repository)]
delete_pulp_orphans(module)
[delete_galaxy_namespace(n, module) for n in get_galaxy_namespaces(module)]
for repository in module.params['repositories']:
repo_href = new_pulp_repository(repository, module)
new_pulp_distribution(repository, repository, repo_href, module)
[new_galaxy_namespace(n, module) for n in module.params['namespaces']]
module.exit_json(changed=True)
if __name__ == '__main__':
main()
| 8,200
|
Python
|
.py
| 182
| 40.214286
| 123
| 0.695494
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,695
|
setup_collections.py
|
ansible_ansible/test/integration/targets/ansible-galaxy-collection/library/setup_collections.py
|
#!/usr/bin/python
# Copyright: (c) 2020, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
---
module: setup_collections
short_description: Set up test collections based on the input
description:
- Builds and publishes a whole bunch of collections used for testing in bulk.
options:
server:
description:
- The Galaxy server to upload the collections to.
required: yes
type: str
token:
description:
- The token used to authenticate with the Galaxy server.
required: yes
type: str
collections:
description:
- A list of collection details to use for the build.
required: yes
type: list
elements: dict
options:
namespace:
description:
- The namespace of the collection.
required: yes
type: str
name:
description:
- The name of the collection.
required: yes
type: str
version:
description:
- The version of the collection.
type: str
default: '1.0.0'
dependencies:
description:
- The dependencies of the collection.
type: dict
default: '{}'
author:
- Jordan Borean (@jborean93)
"""
EXAMPLES = """
- name: Build test collections
setup_collections:
path: ~/ansible/collections/ansible_collections
collections:
- namespace: namespace1
name: name1
version: 0.0.1
- namespace: namespace1
name: name1
version: 0.0.2
"""
RETURN = """
#
"""
import datetime
import os
import subprocess
import tarfile
import tempfile
import yaml
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_bytes
from functools import partial
from multiprocessing import dummy as threading
from multiprocessing import TimeoutError
COLLECTIONS_BUILD_AND_PUBLISH_TIMEOUT = 180
def publish_collection(module, collection):
namespace = collection['namespace']
name = collection['name']
version = collection['version']
dependencies = collection['dependencies']
use_symlink = collection['use_symlink']
result = {}
collection_dir = os.path.join(module.tmpdir, "%s-%s-%s" % (namespace, name, version))
b_collection_dir = to_bytes(collection_dir, errors='surrogate_or_strict')
os.mkdir(b_collection_dir)
os.mkdir(os.path.join(b_collection_dir, b'meta'))
with open(os.path.join(b_collection_dir, b'README.md'), mode='wb') as fd:
fd.write(b"Collection readme")
galaxy_meta = {
'namespace': namespace,
'name': name,
'version': version,
'readme': 'README.md',
'authors': ['Collection author <name@email.com'],
'dependencies': dependencies,
'license': ['GPL-3.0-or-later'],
'repository': 'https://ansible.com/',
}
with open(os.path.join(b_collection_dir, b'galaxy.yml'), mode='wb') as fd:
fd.write(to_bytes(yaml.safe_dump(galaxy_meta), errors='surrogate_or_strict'))
with open(os.path.join(b_collection_dir, b'meta/runtime.yml'), mode='wb') as fd:
fd.write(b'requires_ansible: ">=1.0.0"')
with tempfile.NamedTemporaryFile(mode='wb') as temp_fd:
temp_fd.write(b"data")
if use_symlink:
os.mkdir(os.path.join(b_collection_dir, b'docs'))
os.mkdir(os.path.join(b_collection_dir, b'plugins'))
b_target_file = b'RE\xc3\x85DM\xc3\x88.md'
with open(os.path.join(b_collection_dir, b_target_file), mode='wb') as fd:
fd.write(b'data')
os.symlink(b_target_file, os.path.join(b_collection_dir, b_target_file + b'-link'))
os.symlink(temp_fd.name, os.path.join(b_collection_dir, b_target_file + b'-outside-link'))
os.symlink(os.path.join(b'..', b_target_file), os.path.join(b_collection_dir, b'docs', b_target_file))
os.symlink(os.path.join(b_collection_dir, b_target_file),
os.path.join(b_collection_dir, b'plugins', b_target_file))
os.symlink(b'docs', os.path.join(b_collection_dir, b'docs-link'))
release_filename = '%s-%s-%s.tar.gz' % (namespace, name, version)
collection_path = os.path.join(collection_dir, release_filename)
rc, stdout, stderr = module.run_command(['ansible-galaxy', 'collection', 'build'], cwd=collection_dir)
result['build'] = {
'rc': rc,
'stdout': stdout,
'stderr': stderr,
}
if module.params['signature_dir'] is not None:
# To test user-provided signatures, we need to sign the MANIFEST.json before publishing
# Extract the tarfile to sign the MANIFEST.json
with tarfile.open(collection_path, mode='r') as collection_tar:
# deprecated: description='extractall fallback without filter' python_version='3.11'
# Replace 'tar_filter' with 'data_filter' and 'filter=tar' with 'filter=data' once Python 3.12 is minimum requirement.
if hasattr(tarfile, 'tar_filter'):
collection_tar.extractall(path=os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version)), filter='tar')
else:
collection_tar.extractall(path=os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version)))
manifest_path = os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version), 'MANIFEST.json')
signature_path = os.path.join(module.params['signature_dir'], '%s-%s-%s-MANIFEST.json.asc' % (namespace, name, version))
sign_manifest(signature_path, manifest_path, module, result)
# Create the tarfile containing the signed MANIFEST.json
with tarfile.open(collection_path, "w:gz") as tar:
tar.add(os.path.join(collection_dir, '%s-%s-%s' % (namespace, name, version)), arcname=os.path.sep)
publish_args = ['ansible-galaxy', 'collection', 'publish', collection_path, '--server', module.params['server']]
if module.params['token']:
publish_args.extend(['--token', module.params['token']])
rc, stdout, stderr = module.run_command(publish_args)
result['publish'] = {
'rc': rc,
'stdout': stdout,
'stderr': stderr,
}
return result
def sign_manifest(signature_path, manifest_path, module, collection_setup_result):
collection_setup_result['gpg_detach_sign'] = {'signature_path': signature_path}
status_fd_read, status_fd_write = os.pipe()
gpg_cmd = [
"gpg",
"--batch",
"--pinentry-mode",
"loopback",
"--yes",
"--homedir",
module.params['signature_dir'],
"--detach-sign",
"--armor",
"--output",
signature_path,
manifest_path,
]
try:
p = subprocess.Popen(
gpg_cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
pass_fds=(status_fd_write,),
encoding='utf8',
)
except (FileNotFoundError, subprocess.SubprocessError) as err:
collection_setup_result['gpg_detach_sign']['error'] = "Failed during GnuPG verification with command '{gpg_cmd}': {err}".format(
gpg_cmd=gpg_cmd, err=err
)
else:
stdout, stderr = p.communicate()
collection_setup_result['gpg_detach_sign']['stdout'] = stdout
if stderr:
error = "Failed during GnuPG verification with command '{gpg_cmd}':\n{stderr}".format(gpg_cmd=gpg_cmd, stderr=stderr)
collection_setup_result['gpg_detach_sign']['error'] = error
finally:
os.close(status_fd_write)
def run_module():
module_args = dict(
server=dict(type='str', required=True),
token=dict(type='str'),
collections=dict(
type='list',
elements='dict',
required=True,
options=dict(
namespace=dict(type='str', required=True),
name=dict(type='str', required=True),
version=dict(type='str', default='1.0.0'),
dependencies=dict(type='dict', default={}),
use_symlink=dict(type='bool', default=False),
),
),
signature_dir=dict(type='path', default=None),
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=False
)
start = datetime.datetime.now()
result = dict(changed=True, results=[], start=str(start))
pool = threading.Pool(4)
publish_func = partial(publish_collection, module)
try:
result['results'] = pool.map_async(
publish_func, module.params['collections'],
).get(timeout=COLLECTIONS_BUILD_AND_PUBLISH_TIMEOUT)
except TimeoutError as timeout_err:
module.fail_json(
'Timed out waiting for collections to be provisioned.',
)
failed = bool(sum(
r['build']['rc'] + r['publish']['rc'] for r in result['results']
))
end = datetime.datetime.now()
delta = end - start
module.exit_json(failed=failed, end=str(end), delta=str(delta), **result)
def main():
run_module()
if __name__ == '__main__':
main()
| 9,457
|
Python
|
.py
| 240
| 31.708333
| 136
| 0.625041
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,696
|
missing_required_lib.py
|
ansible_ansible/test/integration/targets/missing_required_lib/library/missing_required_lib.py
|
#!/usr/bin/python
# Copyright: (c) 2020, Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
try:
import ansible_missing_lib # pylint: disable=unused-import
HAS_LIB = True
except ImportError as e:
HAS_LIB = False
def main():
module = AnsibleModule({
'url': {'type': 'bool'},
'reason': {'type': 'bool'},
})
kwargs = {}
if module.params['url']:
kwargs['url'] = 'https://github.com/ansible/ansible'
if module.params['reason']:
kwargs['reason'] = 'for fun'
if not HAS_LIB:
module.fail_json(
msg=missing_required_lib(
'ansible_missing_lib',
**kwargs
),
)
if __name__ == '__main__':
main()
| 915
|
Python
|
.py
| 29
| 25.344828
| 92
| 0.602958
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,697
|
remote_is_local.py
|
ansible_ansible/test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
DOCUMENTATION = """
name: remote_is_local
short_description: remote is local
description:
- remote_is_local
author: ansible (@core)
version_added: historical
extends_documentation_fragment:
- connection_pipelining
notes:
- The remote user is ignored, the user with which the ansible CLI was executed is used instead.
"""
from ansible.plugins.connection.local import Connection as LocalConnection
class Connection(LocalConnection):
_remote_is_local = True
| 646
|
Python
|
.py
| 17
| 33.294118
| 103
| 0.736334
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,698
|
venv-pythons.py
|
ansible_ansible/test/integration/targets/ansible-test/venv-pythons.py
|
#!/usr/bin/env python
"""Return target Python options for use with ansible-test."""
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
import sys
from ansible import release
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--only-versions', action='store_true')
options = parser.parse_args()
ansible_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(release.__file__))))
source_root = os.path.join(ansible_root, 'test', 'lib')
sys.path.insert(0, source_root)
from ansible_test._internal import constants
args = []
for python_version in constants.SUPPORTED_PYTHON_VERSIONS:
executable = shutil.which(f'python{python_version}')
if executable:
if python_version.startswith('2.'):
cmd = [executable, '-m', 'virtualenv', '--version']
else:
cmd = [executable, '-m', 'venv', '--help']
process = subprocess.run(cmd, capture_output=True, check=False)
print(f'{executable} - {"fail" if process.returncode else "pass"}', file=sys.stderr)
if not process.returncode:
if options.only_versions:
args.append(python_version)
continue
args.extend(['--target-python', f'venv/{python_version}'])
print(' '.join(args))
if __name__ == '__main__':
main()
| 1,456
|
Python
|
.py
| 35
| 33.685714
| 103
| 0.632217
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|
13,699
|
ansible-var-precedence-check.py
|
ansible_ansible/test/integration/targets/var_precedence/ansible-var-precedence-check.py
|
#!/usr/bin/env python
# A tool to check the order of precedence for ansible variables
# https://github.com/ansible/ansible/blob/devel/test/integration/test_var_precedence.yml
from __future__ import annotations
import json
import os
import sys
import shutil
import stat
import subprocess
import tempfile
import yaml
from optparse import OptionParser
from jinja2 import Environment
ENV = Environment()
TESTDIR = tempfile.mkdtemp()
def run_command(args, cwd=None):
p = subprocess.Popen(
args,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=True,
cwd=cwd,
)
(so, se) = p.communicate()
return (p.returncode, so, se)
def clean_test_dir():
if os.path.isdir(TESTDIR):
shutil.rmtree(TESTDIR)
os.makedirs(TESTDIR)
class Role(object):
def __init__(self, name):
self.name = name
self.load = True
self.dependencies = []
self.defaults = False
self.vars = False
self.tasks = []
self.params = dict()
def write_role(self):
fpath = os.path.join(TESTDIR, 'roles', self.name)
if not os.path.isdir(fpath):
os.makedirs(fpath)
if self.defaults:
# roles/x/defaults/main.yml
fpath = os.path.join(TESTDIR, 'roles', self.name, 'defaults')
if not os.path.isdir(fpath):
os.makedirs(fpath)
fname = os.path.join(fpath, 'main.yml')
with open(fname, 'w') as f:
f.write('findme: %s\n' % self.name)
if self.vars:
# roles/x/vars/main.yml
fpath = os.path.join(TESTDIR, 'roles', self.name, 'vars')
if not os.path.isdir(fpath):
os.makedirs(fpath)
fname = os.path.join(fpath, 'main.yml')
with open(fname, 'w') as f:
f.write('findme: %s\n' % self.name)
if self.dependencies:
fpath = os.path.join(TESTDIR, 'roles', self.name, 'meta')
if not os.path.isdir(fpath):
os.makedirs(fpath)
fname = os.path.join(fpath, 'main.yml')
with open(fname, 'w') as f:
f.write('dependencies:\n')
for dep in self.dependencies:
f.write('- { role: %s }\n' % dep)
class DynamicInventory(object):
BASESCRIPT = '''#!/usr/bin/python
import json
data = """{{ data }}"""
data = json.loads(data)
print(json.dumps(data, indent=2, sort_keys=True))
'''
BASEINV = {
'_meta': {
'hostvars': {
'testhost': {}
}
}
}
def __init__(self, features):
self.ENV = Environment()
self.features = features
self.fpath = None
self.inventory = self.BASEINV.copy()
self.build()
def build(self):
xhost = 'testhost'
if 'script_host' in self.features:
self.inventory['_meta']['hostvars'][xhost]['findme'] = 'script_host'
else:
self.inventory['_meta']['hostvars'][xhost] = {}
if 'script_child' in self.features:
self.inventory['child'] = {
'hosts': [xhost],
'vars': {'findme': 'script_child'}
}
if 'script_parent' in self.features:
self.inventory['parent'] = {
'vars': {'findme': 'script_parent'}
}
if 'script_child' in self.features:
self.inventory['parent']['children'] = ['child']
else:
self.inventory['parent']['hosts'] = [xhost]
if 'script_all' in self.features:
self.inventory['all'] = {
'hosts': [xhost],
'vars': {
'findme': 'script_all'
},
}
else:
self.inventory['all'] = {
'hosts': [xhost],
}
def write_script(self):
fdir = os.path.join(TESTDIR, 'inventory')
if not os.path.isdir(fdir):
os.makedirs(fdir)
fpath = os.path.join(fdir, 'hosts')
# fpath = os.path.join(TESTDIR, 'inventory')
self.fpath = fpath
data = json.dumps(self.inventory)
t = self.ENV.from_string(self.BASESCRIPT)
fdata = t.render(data=data)
with open(fpath, 'w') as f:
f.write(fdata + '\n')
st = os.stat(fpath)
os.chmod(fpath, st.st_mode | stat.S_IEXEC)
class VarTestMaker(object):
def __init__(self, features, dynamic_inventory=False):
clean_test_dir()
self.dynamic_inventory = dynamic_inventory
self.di = None
self.features = features[:]
self.inventory = ''
self.playvars = dict()
self.varsfiles = []
self.playbook = dict(hosts='testhost', gather_facts=False)
self.tasks = []
self.roles = []
self.ansible_command = None
self.stdout = None
def write_playbook(self):
fname = os.path.join(TESTDIR, 'site.yml')
pb_copy = self.playbook.copy()
if self.playvars:
pb_copy['vars'] = self.playvars
if self.varsfiles:
pb_copy['vars_files'] = self.varsfiles
if self.roles:
pb_copy['roles'] = []
for role in self.roles:
role.write_role()
role_def = dict(role=role.name)
role_def.update(role.params)
pb_copy['roles'].append(role_def)
if self.tasks:
pb_copy['tasks'] = self.tasks
with open(fname, 'w') as f:
pb_yaml = yaml.dump([pb_copy], f, default_flow_style=False, indent=2)
def build(self):
if self.dynamic_inventory:
# python based inventory file
self.di = DynamicInventory(self.features)
self.di.write_script()
else:
# ini based inventory file
if 'ini_host' in self.features:
self.inventory += 'testhost findme=ini_host\n'
else:
self.inventory += 'testhost\n'
self.inventory += '\n'
if 'ini_child' in self.features:
self.inventory += '[child]\n'
self.inventory += 'testhost\n'
self.inventory += '\n'
self.inventory += '[child:vars]\n'
self.inventory += 'findme=ini_child\n'
self.inventory += '\n'
if 'ini_parent' in self.features:
if 'ini_child' in self.features:
self.inventory += '[parent:children]\n'
self.inventory += 'child\n'
else:
self.inventory += '[parent]\n'
self.inventory += 'testhost\n'
self.inventory += '\n'
self.inventory += '[parent:vars]\n'
self.inventory += 'findme=ini_parent\n'
self.inventory += '\n'
if 'ini_all' in self.features:
self.inventory += '[all:vars]\n'
self.inventory += 'findme=ini_all\n'
self.inventory += '\n'
# default to a single file called inventory
invfile = os.path.join(TESTDIR, 'inventory', 'hosts')
ipath = os.path.join(TESTDIR, 'inventory')
if not os.path.isdir(ipath):
os.makedirs(ipath)
with open(invfile, 'w') as f:
f.write(self.inventory)
hpath = os.path.join(TESTDIR, 'inventory', 'host_vars')
if not os.path.isdir(hpath):
os.makedirs(hpath)
gpath = os.path.join(TESTDIR, 'inventory', 'group_vars')
if not os.path.isdir(gpath):
os.makedirs(gpath)
if 'ini_host_vars_file' in self.features:
hfile = os.path.join(hpath, 'testhost')
with open(hfile, 'w') as f:
f.write('findme: ini_host_vars_file\n')
if 'ini_group_vars_file_all' in self.features:
hfile = os.path.join(gpath, 'all')
with open(hfile, 'w') as f:
f.write('findme: ini_group_vars_file_all\n')
if 'ini_group_vars_file_child' in self.features:
hfile = os.path.join(gpath, 'child')
with open(hfile, 'w') as f:
f.write('findme: ini_group_vars_file_child\n')
if 'ini_group_vars_file_parent' in self.features:
hfile = os.path.join(gpath, 'parent')
with open(hfile, 'w') as f:
f.write('findme: ini_group_vars_file_parent\n')
if 'pb_host_vars_file' in self.features:
os.makedirs(os.path.join(TESTDIR, 'host_vars'))
fname = os.path.join(TESTDIR, 'host_vars', 'testhost')
with open(fname, 'w') as f:
f.write('findme: pb_host_vars_file\n')
if 'pb_group_vars_file_parent' in self.features:
if not os.path.isdir(os.path.join(TESTDIR, 'group_vars')):
os.makedirs(os.path.join(TESTDIR, 'group_vars'))
fname = os.path.join(TESTDIR, 'group_vars', 'parent')
with open(fname, 'w') as f:
f.write('findme: pb_group_vars_file_parent\n')
if 'pb_group_vars_file_child' in self.features:
if not os.path.isdir(os.path.join(TESTDIR, 'group_vars')):
os.makedirs(os.path.join(TESTDIR, 'group_vars'))
fname = os.path.join(TESTDIR, 'group_vars', 'child')
with open(fname, 'w') as f:
f.write('findme: pb_group_vars_file_child\n')
if 'pb_group_vars_file_all' in self.features:
if not os.path.isdir(os.path.join(TESTDIR, 'group_vars')):
os.makedirs(os.path.join(TESTDIR, 'group_vars'))
fname = os.path.join(TESTDIR, 'group_vars', 'all')
with open(fname, 'w') as f:
f.write('findme: pb_group_vars_file_all\n')
if 'play_var' in self.features:
self.playvars['findme'] = 'play_var'
if 'set_fact' in self.features:
self.tasks.append(dict(set_fact='findme="set_fact"'))
if 'vars_file' in self.features:
self.varsfiles.append('varsfile.yml')
fname = os.path.join(TESTDIR, 'varsfile.yml')
with open(fname, 'w') as f:
f.write('findme: vars_file\n')
if 'include_vars' in self.features:
self.tasks.append(dict(include_vars='included_vars.yml'))
fname = os.path.join(TESTDIR, 'included_vars.yml')
with open(fname, 'w') as f:
f.write('findme: include_vars\n')
if 'role_var' in self.features:
role = Role('role_var')
role.vars = True
role.load = True
self.roles.append(role)
if 'role_parent_default' in self.features:
role = Role('role_default')
role.load = False
role.defaults = True
self.roles.append(role)
role = Role('role_parent_default')
role.dependencies.append('role_default')
role.defaults = True
role.load = True
if 'role_params' in self.features:
role.params = dict(findme='role_params')
self.roles.append(role)
elif 'role_default' in self.features:
role = Role('role_default')
role.defaults = True
role.load = True
if 'role_params' in self.features:
role.params = dict(findme='role_params')
self.roles.append(role)
debug_task = dict(debug='var=findme')
test_task = {'assert': dict(that=['findme == "%s"' % self.features[0]])}
if 'task_vars' in self.features:
test_task['vars'] = dict(findme="task_vars")
if 'registered_vars' in self.features:
test_task['register'] = 'findme'
if 'block_vars' in self.features:
block_wrapper = [
debug_task,
{
'block': [test_task],
'vars': dict(findme="block_vars"),
}
]
else:
block_wrapper = [debug_task, test_task]
if 'include_params' in self.features:
self.tasks.append(dict(name='including tasks', include_tasks='included_tasks.yml', vars=dict(findme='include_params')))
else:
self.tasks.append(dict(include_tasks='included_tasks.yml'))
fname = os.path.join(TESTDIR, 'included_tasks.yml')
with open(fname, 'w') as f:
f.write(yaml.dump(block_wrapper))
self.write_playbook()
def run(self):
"""
if self.dynamic_inventory:
cmd = 'ansible-playbook -c local -i inventory/hosts site.yml'
else:
cmd = 'ansible-playbook -c local -i inventory site.yml'
"""
cmd = 'ansible-playbook -c local -i inventory site.yml'
if 'extra_vars' in self.features:
cmd += ' --extra-vars="findme=extra_vars"'
cmd = cmd + ' -vvvvv'
self.ansible_command = cmd
(rc, so, se) = run_command(cmd, cwd=TESTDIR)
self.stdout = so
if rc != 0:
raise Exception("playbook failed (rc=%s), stdout: '%s' stderr: '%s'" % (rc, so, se))
def show_tree(self):
print('## TREE')
cmd = 'tree %s' % TESTDIR
(rc, so, se) = run_command(cmd)
lines = so.split('\n')
lines = lines[:-3]
print('\n'.join(lines))
def show_content(self):
print('## CONTENT')
cmd = 'find %s -type f | xargs tail -n +1' % TESTDIR
(rc, so, se) = run_command(cmd)
print(so)
def show_stdout(self):
print('## COMMAND')
print(self.ansible_command)
print('## STDOUT')
print(self.stdout)
def main():
features = [
'extra_vars',
'include_params',
# 'role_params', # FIXME: we don't yet validate tasks within a role
'set_fact',
# 'registered_vars', # FIXME: hard to simulate
'include_vars',
# 'role_dep_params',
'task_vars',
'block_vars',
'role_var',
'vars_file',
'play_var',
# 'host_facts', # FIXME: hard to simulate
'pb_host_vars_file',
'ini_host_vars_file',
'ini_host',
'pb_group_vars_file_child',
# 'ini_group_vars_file_child', #FIXME: this contradicts documented precedence pb group vars files should override inventory ones
'pb_group_vars_file_parent',
'ini_group_vars_file_parent',
'pb_group_vars_file_all',
'ini_group_vars_file_all',
'ini_child',
'ini_parent',
'ini_all',
'role_parent_default',
'role_default',
]
parser = OptionParser()
parser.add_option('-f', '--feature', action='append')
parser.add_option('--use_dynamic_inventory', action='store_true')
parser.add_option('--show_tree', action='store_true')
parser.add_option('--show_content', action='store_true')
parser.add_option('--show_stdout', action='store_true')
parser.add_option('--copy_testcases_to_local_dir', action='store_true')
(options, args) = parser.parse_args()
if options.feature:
for f in options.feature:
if f not in features:
print('%s is not a valid feature' % f)
sys.exit(1)
features = list(options.feature)
fdesc = {
'ini_host': 'host var inside the ini',
'script_host': 'host var inside the script _meta',
'ini_child': 'child group var inside the ini',
'script_child': 'child group var inside the script',
'ini_parent': 'parent group var inside the ini',
'script_parent': 'parent group var inside the script',
'ini_all': 'all group var inside the ini',
'script_all': 'all group var inside the script',
'ini_host_vars_file': 'var in inventory/host_vars/host',
'ini_group_vars_file_parent': 'var in inventory/group_vars/parent',
'ini_group_vars_file_child': 'var in inventory/group_vars/child',
'ini_group_vars_file_all': 'var in inventory/group_vars/all',
'pb_group_vars_file_parent': 'var in playbook/group_vars/parent',
'pb_group_vars_file_child': 'var in playbook/group_vars/child',
'pb_group_vars_file_all': 'var in playbook/group_vars/all',
'pb_host_vars_file': 'var in playbook/host_vars/host',
'play_var': 'var set in playbook header',
'role_parent_default': 'var in roles/role_parent/defaults/main.yml',
'role_default': 'var in roles/role/defaults/main.yml',
'role_var': 'var in ???',
'include_vars': 'var in included file',
'set_fact': 'var made by set_fact',
'vars_file': 'var in file added by vars_file',
'block_vars': 'vars defined on the block',
'task_vars': 'vars defined on the task',
'extra_vars': 'var passed via the cli'
}
dinv = options.use_dynamic_inventory
if dinv:
# some features are specific to ini, so swap those
for (idx, x) in enumerate(features):
if x.startswith('ini_') and 'vars_file' not in x:
features[idx] = x.replace('ini_', 'script_')
dinv = options.use_dynamic_inventory
index = 1
while features:
VTM = VarTestMaker(features, dynamic_inventory=dinv)
VTM.build()
if options.show_tree or options.show_content or options.show_stdout:
print('')
if options.show_tree:
VTM.show_tree()
if options.show_content:
VTM.show_content()
try:
print("CHECKING: %s (%s)" % (features[0], fdesc.get(features[0], '')))
res = VTM.run()
if options.show_stdout:
VTM.show_stdout()
features.pop(0)
if options.copy_testcases_to_local_dir:
topdir = 'testcases'
if index == 1 and os.path.isdir(topdir):
shutil.rmtree(topdir)
if not os.path.isdir(topdir):
os.makedirs(topdir)
thisindex = str(index)
if len(thisindex) == 1:
thisindex = '0' + thisindex
thisdir = os.path.join(topdir, '%s.%s' % (thisindex, res))
shutil.copytree(TESTDIR, thisdir)
except Exception as e:
print("ERROR !!!")
print(e)
print('feature: %s failed' % features[0])
sys.exit(1)
finally:
shutil.rmtree(TESTDIR)
index += 1
if __name__ == "__main__":
main()
| 18,705
|
Python
|
.py
| 461
| 29.629067
| 136
| 0.546716
|
ansible/ansible
| 62,258
| 23,791
| 861
|
GPL-3.0
|
9/5/2024, 5:11:58 PM (Europe/Amsterdam)
|