summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatt Clay <matt@mystile.com>2024-10-09 23:22:35 +0200
committerGitHub <noreply@github.com>2024-10-09 23:22:35 +0200
commita0495fc31497798a7a833ba7406a9729e1528dd8 (patch)
treec9ebc8e92d18e20bbb5f44d0184d00166b63b4df
parentansible-test - Work around pylint issue on 3.11 (#84094) (diff)
downloadansible-a0495fc31497798a7a833ba7406a9729e1528dd8.tar.xz
ansible-a0495fc31497798a7a833ba7406a9729e1528dd8.zip
Update triple single quotes to triple double quotes (#84099)
* Update triple single quotes to triple double quotes This change was fully automated. The updated Python files have been verified to tokenize the same as the originals, except for the expected change in quoting of strings, which were verified through literal_eval. * Manual conversion of docstring quotes
-rwxr-xr-xhacking/backport/backport_of_line_adder.py28
-rw-r--r--lib/ansible/cli/__init__.py12
-rwxr-xr-xlib/ansible/cli/adhoc.py10
-rwxr-xr-xlib/ansible/cli/config.py28
-rwxr-xr-xlib/ansible/cli/console.py6
-rwxr-xr-xlib/ansible/cli/doc.py20
-rwxr-xr-xlib/ansible/cli/galaxy.py8
-rwxr-xr-xlib/ansible/cli/inventory.py2
-rwxr-xr-xlib/ansible/cli/playbook.py4
-rwxr-xr-xlib/ansible/cli/pull.py8
-rw-r--r--lib/ansible/cli/scripts/ansible_connection_cli_stub.py4
-rwxr-xr-xlib/ansible/cli/vault.py18
-rw-r--r--lib/ansible/compat/__init__.py4
-rw-r--r--lib/ansible/config/manager.py26
-rw-r--r--lib/ansible/constants.py6
-rw-r--r--lib/ansible/errors/__init__.py66
-rw-r--r--lib/ansible/executor/module_common.py16
-rw-r--r--lib/ansible/executor/play_iterator.py8
-rw-r--r--lib/ansible/executor/playbook_executor.py16
-rw-r--r--lib/ansible/executor/process/worker.py20
-rw-r--r--lib/ansible/executor/stats.py10
-rw-r--r--lib/ansible/executor/task_executor.py44
-rw-r--r--lib/ansible/executor/task_queue_manager.py12
-rw-r--r--lib/ansible/executor/task_result.py8
-rw-r--r--lib/ansible/galaxy/__init__.py4
-rw-r--r--lib/ansible/galaxy/token.py6
-rw-r--r--lib/ansible/inventory/data.py12
-rw-r--r--lib/ansible/inventory/group.py6
-rw-r--r--lib/ansible/inventory/host.py2
-rw-r--r--lib/ansible/inventory/manager.py30
-rw-r--r--lib/ansible/module_utils/basic.py66
-rw-r--r--lib/ansible/module_utils/common/_utils.py4
-rw-r--r--lib/ansible/module_utils/common/dict_transformations.py4
-rw-r--r--lib/ansible/module_utils/common/file.py4
-rw-r--r--lib/ansible/module_utils/common/json.py4
-rw-r--r--lib/ansible/module_utils/common/locale.py4
-rw-r--r--lib/ansible/module_utils/common/process.py4
-rw-r--r--lib/ansible/module_utils/common/respawn.py4
-rw-r--r--lib/ansible/module_utils/common/sys_info.py16
-rw-r--r--lib/ansible/module_utils/common/text/converters.py4
-rw-r--r--lib/ansible/module_utils/distro/__init__.py4
-rw-r--r--lib/ansible/module_utils/facts/ansible_collector.py6
-rw-r--r--lib/ansible/module_utils/facts/collector.py24
-rw-r--r--lib/ansible/module_utils/facts/compat.py8
-rw-r--r--lib/ansible/module_utils/facts/hardware/freebsd.py4
-rw-r--r--lib/ansible/module_utils/facts/hardware/linux.py8
-rw-r--r--lib/ansible/module_utils/facts/namespace.py2
-rw-r--r--lib/ansible/module_utils/facts/other/ohai.py2
-rw-r--r--lib/ansible/module_utils/facts/system/distribution.py2
-rw-r--r--lib/ansible/module_utils/facts/utils.py6
-rw-r--r--lib/ansible/module_utils/json_utils.py4
-rw-r--r--lib/ansible/module_utils/service.py28
-rw-r--r--lib/ansible/module_utils/splitter.py14
-rw-r--r--lib/ansible/module_utils/urls.py36
-rw-r--r--lib/ansible/modules/add_host.py8
-rw-r--r--lib/ansible/modules/apt.py14
-rw-r--r--lib/ansible/modules/apt_key.py12
-rw-r--r--lib/ansible/modules/apt_repository.py28
-rw-r--r--lib/ansible/modules/assemble.py12
-rw-r--r--lib/ansible/modules/assert.py8
-rw-r--r--lib/ansible/modules/async_status.py12
-rw-r--r--lib/ansible/modules/async_wrapper.py4
-rw-r--r--lib/ansible/modules/blockinfile.py8
-rw-r--r--lib/ansible/modules/command.py12
-rw-r--r--lib/ansible/modules/copy.py20
-rw-r--r--lib/ansible/modules/cron.py10
-rw-r--r--lib/ansible/modules/deb822_repository.py12
-rw-r--r--lib/ansible/modules/debconf.py10
-rw-r--r--lib/ansible/modules/debug.py8
-rw-r--r--lib/ansible/modules/dnf.py8
-rw-r--r--lib/ansible/modules/dpkg_selections.py8
-rw-r--r--lib/ansible/modules/expect.py8
-rw-r--r--lib/ansible/modules/fail.py8
-rw-r--r--lib/ansible/modules/fetch.py8
-rw-r--r--lib/ansible/modules/file.py14
-rw-r--r--lib/ansible/modules/find.py18
-rw-r--r--lib/ansible/modules/gather_facts.py4
-rw-r--r--lib/ansible/modules/get_url.py12
-rw-r--r--lib/ansible/modules/getent.py12
-rw-r--r--lib/ansible/modules/git.py44
-rw-r--r--lib/ansible/modules/group.py12
-rw-r--r--lib/ansible/modules/group_by.py8
-rw-r--r--lib/ansible/modules/hostname.py8
-rw-r--r--lib/ansible/modules/import_playbook.py12
-rw-r--r--lib/ansible/modules/import_role.py12
-rw-r--r--lib/ansible/modules/import_tasks.py12
-rw-r--r--lib/ansible/modules/include_role.py12
-rw-r--r--lib/ansible/modules/include_tasks.py12
-rw-r--r--lib/ansible/modules/include_vars.py12
-rw-r--r--lib/ansible/modules/iptables.py8
-rw-r--r--lib/ansible/modules/known_hosts.py20
-rw-r--r--lib/ansible/modules/lineinfile.py10
-rw-r--r--lib/ansible/modules/meta.py8
-rw-r--r--lib/ansible/modules/package.py8
-rw-r--r--lib/ansible/modules/package_facts.py12
-rw-r--r--lib/ansible/modules/pause.py12
-rw-r--r--lib/ansible/modules/ping.py12
-rw-r--r--lib/ansible/modules/pip.py16
-rw-r--r--lib/ansible/modules/raw.py8
-rw-r--r--lib/ansible/modules/reboot.py12
-rw-r--r--lib/ansible/modules/replace.py10
-rw-r--r--lib/ansible/modules/rpm_key.py10
-rw-r--r--lib/ansible/modules/script.py8
-rw-r--r--lib/ansible/modules/service.py10
-rw-r--r--lib/ansible/modules/service_facts.py12
-rw-r--r--lib/ansible/modules/set_fact.py8
-rw-r--r--lib/ansible/modules/set_stats.py8
-rw-r--r--lib/ansible/modules/setup.py4
-rw-r--r--lib/ansible/modules/shell.py12
-rw-r--r--lib/ansible/modules/slurp.py12
-rw-r--r--lib/ansible/modules/stat.py12
-rw-r--r--lib/ansible/modules/subversion.py30
-rw-r--r--lib/ansible/modules/systemd_service.py12
-rw-r--r--lib/ansible/modules/sysvinit.py12
-rw-r--r--lib/ansible/modules/tempfile.py8
-rw-r--r--lib/ansible/modules/template.py12
-rw-r--r--lib/ansible/modules/unarchive.py18
-rw-r--r--lib/ansible/modules/uri.py16
-rw-r--r--lib/ansible/modules/user.py42
-rw-r--r--lib/ansible/modules/validate_argument_spec.py12
-rw-r--r--lib/ansible/modules/wait_for.py12
-rw-r--r--lib/ansible/modules/wait_for_connection.py12
-rw-r--r--lib/ansible/modules/yum_repository.py12
-rw-r--r--lib/ansible/parsing/dataloader.py38
-rw-r--r--lib/ansible/parsing/mod_args.py20
-rw-r--r--lib/ansible/parsing/plugin_docs.py8
-rw-r--r--lib/ansible/parsing/quoting.py2
-rw-r--r--lib/ansible/parsing/splitter.py24
-rw-r--r--lib/ansible/parsing/utils/addresses.py44
-rw-r--r--lib/ansible/parsing/utils/jsonify.py2
-rw-r--r--lib/ansible/parsing/utils/yaml.py10
-rw-r--r--lib/ansible/parsing/vault/__init__.py26
-rw-r--r--lib/ansible/parsing/yaml/dumper.py4
-rw-r--r--lib/ansible/parsing/yaml/objects.py16
-rw-r--r--lib/ansible/playbook/base.py56
-rw-r--r--lib/ansible/playbook/block.py32
-rw-r--r--lib/ansible/playbook/conditional.py8
-rw-r--r--lib/ansible/playbook/handler.py2
-rw-r--r--lib/ansible/playbook/helpers.py8
-rw-r--r--lib/ansible/playbook/loop_control.py4
-rw-r--r--lib/ansible/playbook/play.py38
-rw-r--r--lib/ansible/playbook/play_context.py16
-rw-r--r--lib/ansible/playbook/playbook_include.py12
-rw-r--r--lib/ansible/playbook/role/__init__.py30
-rw-r--r--lib/ansible/playbook/role/definition.py12
-rw-r--r--lib/ansible/playbook/role/metadata.py12
-rw-r--r--lib/ansible/playbook/role_include.py2
-rw-r--r--lib/ansible/playbook/taggable.py2
-rw-r--r--lib/ansible/playbook/task.py44
-rw-r--r--lib/ansible/playbook/task_include.py8
-rw-r--r--lib/ansible/plugins/__init__.py4
-rw-r--r--lib/ansible/plugins/action/__init__.py82
-rw-r--r--lib/ansible/plugins/action/add_host.py2
-rw-r--r--lib/ansible/plugins/action/assemble.py2
-rw-r--r--lib/ansible/plugins/action/assert.py2
-rw-r--r--lib/ansible/plugins/action/copy.py4
-rw-r--r--lib/ansible/plugins/action/debug.py2
-rw-r--r--lib/ansible/plugins/action/fail.py2
-rw-r--r--lib/ansible/plugins/action/fetch.py2
-rw-r--r--lib/ansible/plugins/action/group_by.py2
-rw-r--r--lib/ansible/plugins/action/package.py2
-rw-r--r--lib/ansible/plugins/action/pause.py4
-rw-r--r--lib/ansible/plugins/action/script.py2
-rw-r--r--lib/ansible/plugins/action/service.py2
-rw-r--r--lib/ansible/plugins/action/template.py2
-rw-r--r--lib/ansible/plugins/action/unarchive.py2
-rw-r--r--lib/ansible/plugins/action/validate_argument_spec.py10
-rw-r--r--lib/ansible/plugins/action/wait_for_connection.py2
-rw-r--r--lib/ansible/plugins/become/__init__.py6
-rw-r--r--lib/ansible/plugins/become/su.py2
-rw-r--r--lib/ansible/plugins/cache/jsonfile.py4
-rw-r--r--lib/ansible/plugins/cache/memory.py4
-rw-r--r--lib/ansible/plugins/callback/__init__.py14
-rw-r--r--lib/ansible/plugins/callback/default.py8
-rw-r--r--lib/ansible/plugins/callback/junit.py4
-rw-r--r--lib/ansible/plugins/callback/minimal.py10
-rw-r--r--lib/ansible/plugins/callback/oneline.py8
-rw-r--r--lib/ansible/plugins/callback/tree.py12
-rw-r--r--lib/ansible/plugins/connection/__init__.py20
-rw-r--r--lib/ansible/plugins/connection/local.py16
-rw-r--r--lib/ansible/plugins/connection/paramiko_ssh.py18
-rw-r--r--lib/ansible/plugins/connection/psrp.py12
-rw-r--r--lib/ansible/plugins/connection/ssh.py36
-rw-r--r--lib/ansible/plugins/connection/winrm.py14
-rw-r--r--lib/ansible/plugins/doc_fragments/action_common_attributes.py28
-rw-r--r--lib/ansible/plugins/doc_fragments/action_core.py12
-rw-r--r--lib/ansible/plugins/doc_fragments/backup.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/constructed.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/decrypt.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/default_callback.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/files.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/inventory_cache.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/result_format_callback.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/return_common.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/template_common.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/url.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/url_windows.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/validate.py4
-rw-r--r--lib/ansible/plugins/doc_fragments/vars_plugin_staging.py4
-rw-r--r--lib/ansible/plugins/filter/core.py42
-rw-r--r--lib/ansible/plugins/filter/encryption.py2
-rw-r--r--lib/ansible/plugins/filter/mathstuff.py6
-rw-r--r--lib/ansible/plugins/filter/urls.py2
-rw-r--r--lib/ansible/plugins/filter/urlsplit.py14
-rw-r--r--lib/ansible/plugins/inventory/__init__.py38
-rw-r--r--lib/ansible/plugins/inventory/advanced_host_list.py10
-rw-r--r--lib/ansible/plugins/inventory/auto.py8
-rw-r--r--lib/ansible/plugins/inventory/constructed.py16
-rw-r--r--lib/ansible/plugins/inventory/generator.py10
-rw-r--r--lib/ansible/plugins/inventory/host_list.py10
-rw-r--r--lib/ansible/plugins/inventory/ini.py44
-rw-r--r--lib/ansible/plugins/inventory/script.py4
-rw-r--r--lib/ansible/plugins/inventory/toml.py10
-rw-r--r--lib/ansible/plugins/inventory/yaml.py14
-rw-r--r--lib/ansible/plugins/loader.py40
-rw-r--r--lib/ansible/plugins/lookup/__init__.py4
-rw-r--r--lib/ansible/plugins/lookup/ini.py2
-rw-r--r--lib/ansible/plugins/lookup/password.py8
-rw-r--r--lib/ansible/plugins/shell/__init__.py4
-rw-r--r--lib/ansible/plugins/shell/cmd.py4
-rw-r--r--lib/ansible/plugins/shell/powershell.py6
-rw-r--r--lib/ansible/plugins/shell/sh.py4
-rw-r--r--lib/ansible/plugins/strategy/__init__.py30
-rw-r--r--lib/ansible/plugins/strategy/debug.py4
-rw-r--r--lib/ansible/plugins/strategy/free.py8
-rw-r--r--lib/ansible/plugins/strategy/host_pinned.py4
-rw-r--r--lib/ansible/plugins/strategy/linear.py12
-rw-r--r--lib/ansible/plugins/terminal/__init__.py8
-rw-r--r--lib/ansible/plugins/test/core.py30
-rw-r--r--lib/ansible/plugins/test/files.py2
-rw-r--r--lib/ansible/plugins/test/mathstuff.py6
-rw-r--r--lib/ansible/plugins/test/uri.py6
-rw-r--r--lib/ansible/plugins/vars/host_group_vars.py6
-rw-r--r--lib/ansible/template/__init__.py50
-rw-r--r--lib/ansible/template/template.py4
-rw-r--r--lib/ansible/utils/display.py6
-rw-r--r--lib/ansible/utils/encrypt.py4
-rw-r--r--lib/ansible/utils/fqcn.py4
-rw-r--r--lib/ansible/utils/hashing.py4
-rw-r--r--lib/ansible/utils/helpers.py4
-rw-r--r--lib/ansible/utils/lock.py4
-rw-r--r--lib/ansible/utils/path.py8
-rw-r--r--lib/ansible/utils/plugin_docs.py2
-rw-r--r--lib/ansible/utils/version.py4
-rw-r--r--lib/ansible/vars/clean.py8
-rw-r--r--lib/ansible/vars/hostvars.py10
-rw-r--r--lib/ansible/vars/manager.py54
-rw-r--r--lib/ansible/vars/reserved.py4
-rw-r--r--test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py4
-rw-r--r--test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py4
-rw-r--r--test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py12
-rw-r--r--test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/filter_subdir/in_subdir.py2
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/grouped.py2
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/database/database_type/subdir_module.py12
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py12
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/test/test_test.py2
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/deprecation.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/module.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/plugin.py4
-rw-r--r--test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/version_added.py4
-rw-r--r--test/integration/targets/ansible-doc/filter_plugins/other.py2
-rw-r--r--test/integration/targets/ansible-doc/library/double_doc.py4
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_missing_description.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_no_metadata.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_no_status.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_non_iterable_status.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_removed_precedence.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_removed_status.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_returns.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_returns_broken.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_suboptions.py12
-rw-r--r--test/integration/targets/ansible-doc/library/test_docs_yaml_anchors.py12
-rw-r--r--test/integration/targets/ansible-doc/lookup_plugins/_deprecated_with_docs.py12
-rw-r--r--test/integration/targets/ansible-galaxy-collection/files/test_module.py12
-rw-r--r--test/integration/targets/ansible-galaxy-collection/library/reset_pulp.py12
-rw-r--r--test/integration/targets/ansible-galaxy-collection/library/setup_collections.py12
-rw-r--r--test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/doc_fragments/ps_util.py4
-rw-r--r--test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/hello.py10
-rw-r--r--test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.py12
-rw-r--r--test/integration/targets/ansible-test-integration/ansible_collections/ns/col/plugins/modules/hello.py10
-rw-r--r--test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/_module3.py10
-rw-r--r--test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/a/b/module2.py10
-rw-r--r--test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/module1.py10
-rw-r--r--test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor1.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor2.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/_not_deprecated.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_1.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_2.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_3.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_4.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_5.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_6.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_7.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/import_order.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_extra_key.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_incorrect_context.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_yaml_syntax.py12
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/no_callable.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/option_name_casing.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/semantic_markup.py10
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/valid_argument_spec_context.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/wrong_aliases.py8
-rw-r--r--test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/ps_only/plugins/modules/validate.py12
-rw-r--r--test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/bad.py10
-rw-r--r--test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/world.py10
-rw-r--r--test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/modules/bad.py10
-rw-r--r--test/integration/targets/ansible-test-units/ansible_collections/ns/col/plugins/modules/hello.py10
-rw-r--r--test/integration/targets/callback_results/callback_plugins/track_connections.py4
-rw-r--r--test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/callback/usercallback.py4
-rw-r--r--test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/doc_fragments/frag.py8
-rw-r--r--test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule.py4
-rw-r--r--test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule_bad_docfrags.py4
-rw-r--r--test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/vars/custom_vars.py4
-rw-r--r--test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/action/action1.py2
-rw-r--r--test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/modules/action1.py12
-rw-r--r--test/integration/targets/collections/collections/ansible_collections/me/mycoll2/plugins/modules/module1.py12
-rw-r--r--test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/cache/custom_jsonfile.py4
-rw-r--r--test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/inventory/statichost.py6
-rw-r--r--test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/vars/custom_adj_vars.py4
-rw-r--r--test/integration/targets/collections/custom_vars_plugins/v1_vars_plugin.py4
-rw-r--r--test/integration/targets/collections/custom_vars_plugins/v2_vars_plugin.py4
-rw-r--r--test/integration/targets/collections/test_task_resolved_plugin/callback_plugins/display_resolved_action.py4
-rw-r--r--test/integration/targets/collections/test_task_resolved_plugin/collections/ansible_collections/test_ns/test_coll/plugins/modules/collection_module.py4
-rw-r--r--test/integration/targets/collections/test_task_resolved_plugin/library/legacy_module.py4
-rw-r--r--test/integration/targets/collections/testcoll2/plugins/modules/testmodule2.py12
-rw-r--r--test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py4
-rw-r--r--test/integration/targets/delegate_to/connection_plugins/fakelocal.py16
-rw-r--r--test/integration/targets/deprecations/cache_plugins/notjsonfile.py4
-rw-r--r--test/integration/targets/deprecations/library/removeoption.py12
-rw-r--r--test/integration/targets/deprecations/library/willremove.py12
-rw-r--r--test/integration/targets/dict_transformations/library/convert_camelCase.py4
-rw-r--r--test/integration/targets/dict_transformations/library/convert_snake_case.py4
-rw-r--r--test/integration/targets/gathering_facts/cache_plugins/none.py4
-rw-r--r--test/integration/targets/inventory/inventory_plugins/constructed_with_hostvars.py4
-rw-r--r--test/integration/targets/inventory_cache/plugins/inventory/cache_host.py4
-rw-r--r--test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py4
-rw-r--r--test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py4
-rw-r--r--test/integration/targets/module_defaults/action_plugins/debug.py2
-rw-r--r--test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/eosfacts.py8
-rw-r--r--test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ios_facts.py8
-rw-r--r--test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/metadata.py12
-rw-r--r--test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/module.py8
-rw-r--r--test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ping.py12
-rw-r--r--test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/vyosfacts.py8
-rw-r--r--test/integration/targets/module_defaults/library/legacy_ping.py12
-rw-r--r--test/integration/targets/module_precedence/lib_with_extension/ping.py8
-rw-r--r--test/integration/targets/module_precedence/multiple_roles/bar/library/ping.py8
-rw-r--r--test/integration/targets/module_precedence/multiple_roles/foo/library/ping.py8
-rw-r--r--test/integration/targets/module_precedence/roles_with_extension/foo/library/ping.py8
-rw-r--r--test/integration/targets/module_utils/callback/pure_json.py4
-rw-r--r--test/integration/targets/module_utils_ansible_release/library/ansible_release.py12
-rw-r--r--test/integration/targets/module_utils_urls/library/test_peercert.py12
-rw-r--r--test/integration/targets/old_style_cache_plugins/plugins/cache/configurable_redis.py4
-rw-r--r--test/integration/targets/old_style_cache_plugins/plugins/cache/legacy_redis.py4
-rw-r--r--test/integration/targets/old_style_cache_plugins/plugins/inventory/test.py4
-rw-r--r--test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py4
-rw-r--r--test/integration/targets/plugin_config_for_inventory/test_inventory.py8
-rw-r--r--test/integration/targets/plugin_loader/file_collision/roles/r1/filter_plugins/custom.py2
-rw-r--r--test/integration/targets/plugin_loader/file_collision/roles/r2/filter_plugins/custom.py2
-rw-r--r--test/integration/targets/plugin_loader/override/filter_plugins/core.py2
-rw-r--r--test/integration/targets/prepare_http_tests/library/httptester_kinit.py12
-rw-r--r--test/integration/targets/rel_plugin_loading/subdir/inventory_plugins/notyaml.py14
-rw-r--r--test/integration/targets/shell/connection_plugins/test_connection_default.py6
-rw-r--r--test/integration/targets/shell/connection_plugins/test_connection_override.py6
-rwxr-xr-xtest/integration/targets/var_precedence/ansible-var-precedence-check.py4
-rw-r--r--test/integration/targets/windows-minimal/library/win_ping.py12
-rw-r--r--test/support/integration/plugins/modules/pkgng.py8
-rw-r--r--test/support/windows-integration/collections/ansible_collections/ansible/windows/plugins/modules/win_uri.py12
-rw-r--r--test/support/windows-integration/plugins/action/win_copy.py4
-rw-r--r--test/support/windows-integration/plugins/modules/win_acl.py8
-rw-r--r--test/support/windows-integration/plugins/modules/win_certificate_store.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_command.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_copy.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_file.py8
-rw-r--r--test/support/windows-integration/plugins/modules/win_get_url.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_lineinfile.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_ping.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_reboot.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_regedit.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_shell.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_stat.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_user.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_user_right.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_wait_for.py12
-rw-r--r--test/support/windows-integration/plugins/modules/win_whoami.py12
-rw-r--r--test/units/cli/test_galaxy.py90
-rw-r--r--test/units/errors/test_errors.py4
-rw-r--r--test/units/executor/module_common/test_modify_module.py4
-rw-r--r--test/units/executor/test_playbook_executor.py20
-rw-r--r--test/units/galaxy/test_api.py2
-rw-r--r--test/units/galaxy/test_collection.py4
-rw-r--r--test/units/inventory/test_group.py4
-rw-r--r--test/units/mock/vault_helper.py6
-rw-r--r--test/units/module_utils/basic/test_set_cwd.py10
-rw-r--r--test/units/module_utils/common/test_dict_transformations.py4
-rw-r--r--test/units/module_utils/common/validation/test_check_type_float.py2
-rw-r--r--test/units/module_utils/facts/network/test_generic_bsd.py8
-rw-r--r--test/units/module_utils/facts/other/test_facter.py4
-rw-r--r--test/units/module_utils/facts/other/test_ohai.py4
-rw-r--r--test/units/module_utils/facts/system/test_lsb.py12
-rw-r--r--test/units/module_utils/urls/test_gzip.py8
-rw-r--r--test/units/parsing/test_dataloader.py2
-rw-r--r--test/units/parsing/vault/test_vault.py24
-rw-r--r--test/units/plugins/action/test_action.py8
-rw-r--r--test/units/plugins/callback/test_callback.py36
-rw-r--r--test/units/plugins/connection/test_connection.py12
-rw-r--r--test/units/plugins/test_plugins.py8
-rw-r--r--test/units/template/test_templar.py2
-rw-r--r--test/units/utils/display/test_logger.py4
-rw-r--r--test/units/vars/test_variable_manager.py4
416 files changed, 2236 insertions, 2236 deletions
diff --git a/hacking/backport/backport_of_line_adder.py b/hacking/backport/backport_of_line_adder.py
index 9856b9f0e0..70d03efd2c 100755
--- a/hacking/backport/backport_of_line_adder.py
+++ b/hacking/backport/backport_of_line_adder.py
@@ -32,14 +32,14 @@ TICKET_NUMBER = re.compile(r'(?:^|\s)#(\d+)')
def normalize_pr_url(pr, allow_non_ansible_ansible=False, only_number=False):
- '''
+ """
Given a PullRequest, or a string containing a PR number, PR URL,
or internal PR URL (e.g. ansible-collections/community.general#1234),
return either a full github URL to the PR (if only_number is False),
or an int containing the PR number (if only_number is True).
Throws if it can't parse the input.
- '''
+ """
if isinstance(pr, PullRequest):
return pr.html_url
@@ -71,10 +71,10 @@ def normalize_pr_url(pr, allow_non_ansible_ansible=False, only_number=False):
def url_to_org_repo(url):
- '''
+ """
Given a full Github PR URL, extract the user/org and repo name.
Return them in the form: "user/repo"
- '''
+ """
match = PULL_HTTP_URL_RE.match(url)
if not match:
return ''
@@ -82,7 +82,7 @@ def url_to_org_repo(url):
def generate_new_body(pr, source_pr):
- '''
+ """
Given the new PR (the backport) and the originating (source) PR,
construct the new body for the backport PR.
@@ -93,7 +93,7 @@ def generate_new_body(pr, source_pr):
This function does not side-effect, it simply returns the new body as a
string.
- '''
+ """
backport_text = '\nBackport of {0}\n'.format(source_pr)
body_lines = pr.body.split('\n')
new_body_lines = []
@@ -115,10 +115,10 @@ def generate_new_body(pr, source_pr):
def get_prs_for_commit(g, commit):
- '''
+ """
Given a commit hash, attempt to find the hash in any repo in the
ansible orgs, and then use it to determine what, if any, PR it appeared in.
- '''
+ """
commits = g.search_commits(
'hash:{0} org:ansible org:ansible-collections is:public'.format(commit)
@@ -132,7 +132,7 @@ def get_prs_for_commit(g, commit):
def search_backport(pr, g, ansible_ansible):
- '''
+ """
Do magic. This is basically the "brain" of 'auto'.
It will search the PR (the newest PR - the backport) and try to find where
it originated.
@@ -148,7 +148,7 @@ def search_backport(pr, g, ansible_ansible):
It will take all of the above, and return a list of "possibilities",
which is a list of PullRequest objects.
- '''
+ """
possibilities = []
@@ -198,20 +198,20 @@ def search_backport(pr, g, ansible_ansible):
def prompt_add():
- '''
+ """
Prompt the user and return whether or not they agree.
- '''
+ """
res = input('Shall I add the reference? [Y/n]: ')
return res.lower() in ('', 'y', 'yes')
def commit_edit(new_pr, pr):
- '''
+ """
Given the new PR (the backport), and the "possibility" that we have decided
on, prompt the user and then add the reference to the body of the new PR.
This method does the actual "destructive" work of editing the PR body.
- '''
+ """
print('I think this PR might have come from:')
print(pr.title)
print('-' * 50)
diff --git a/lib/ansible/cli/__init__.py b/lib/ansible/cli/__init__.py
index 8b12aec17f..81323c451d 100644
--- a/lib/ansible/cli/__init__.py
+++ b/lib/ansible/cli/__init__.py
@@ -116,7 +116,7 @@ except ImportError:
class CLI(ABC):
- ''' code behind bin/ansible* programs '''
+ """ code behind bin/ansible* programs """
PAGER = C.config.get_config_value('PAGER')
@@ -317,7 +317,7 @@ class CLI(ABC):
@staticmethod
def ask_passwords():
- ''' prompt for connection and become passwords if needed '''
+ """ prompt for connection and become passwords if needed """
op = context.CLIARGS
sshpass = None
@@ -347,7 +347,7 @@ class CLI(ABC):
return (sshpass, becomepass)
def validate_conflicts(self, op, runas_opts=False, fork_opts=False):
- ''' check for conflicting options '''
+ """ check for conflicting options """
if fork_opts:
if op.forks < 1:
@@ -459,7 +459,7 @@ class CLI(ABC):
@staticmethod
def version_info(gitinfo=False):
- ''' return full ansible version info '''
+ """ return full ansible version info """
if gitinfo:
# expensive call, user with care
ansible_version_string = opt_help.version()
@@ -485,7 +485,7 @@ class CLI(ABC):
@staticmethod
def pager(text):
- ''' find reasonable way to display text '''
+ """ find reasonable way to display text """
# this is a much simpler form of what is in pydoc.py
if not sys.stdout.isatty():
display.display(text, screen_only=True)
@@ -504,7 +504,7 @@ class CLI(ABC):
@staticmethod
def pager_pipe(text):
- ''' pipe text through a pager '''
+ """ pipe text through a pager """
if 'less' in CLI.PAGER:
os.environ['LESS'] = CLI.LESS_OPTS
try:
diff --git a/lib/ansible/cli/adhoc.py b/lib/ansible/cli/adhoc.py
index efe99b9910..830e5823cf 100755
--- a/lib/ansible/cli/adhoc.py
+++ b/lib/ansible/cli/adhoc.py
@@ -24,14 +24,14 @@ display = Display()
class AdHocCLI(CLI):
- ''' is an extra-simple tool/framework/API for doing 'remote things'.
+ """ is an extra-simple tool/framework/API for doing 'remote things'.
this command allows you to define and run a single task 'playbook' against a set of hosts
- '''
+ """
name = 'ansible'
def init_parser(self):
- ''' create an options parser for bin/ansible '''
+ """ create an options parser for bin/ansible """
super(AdHocCLI, self).init_parser(usage='%prog <host-pattern> [options]',
desc="Define and run a single task 'playbook' against a set of hosts",
epilog="Some actions do not make sense in Ad-Hoc (include, meta, etc)")
@@ -60,7 +60,7 @@ class AdHocCLI(CLI):
self.parser.add_argument('args', metavar='pattern', help='host pattern')
def post_process_args(self, options):
- '''Post process and validate options for bin/ansible '''
+ """Post process and validate options for bin/ansible """
options = super(AdHocCLI, self).post_process_args(options)
@@ -98,7 +98,7 @@ class AdHocCLI(CLI):
tasks=[mytask])
def run(self):
- ''' create and execute the single task playbook '''
+ """ create and execute the single task playbook """
super(AdHocCLI, self).run()
diff --git a/lib/ansible/cli/config.py b/lib/ansible/cli/config.py
index da9231af74..cd801212fc 100755
--- a/lib/ansible/cli/config.py
+++ b/lib/ansible/cli/config.py
@@ -47,14 +47,14 @@ def yaml_short(data):
def get_constants():
- ''' helper method to ensure we can template based on existing constants '''
+ """ helper method to ensure we can template based on existing constants """
if not hasattr(get_constants, 'cvars'):
get_constants.cvars = {k: getattr(C, k) for k in dir(C) if not k.startswith('__')}
return get_constants.cvars
def _ansible_env_vars(varname):
- ''' return true or false depending if variable name is possibly a 'configurable' ansible env variable '''
+ """ return true or false depending if variable name is possibly a 'configurable' ansible env variable """
return all(
[
varname.startswith("ANSIBLE_"),
@@ -188,9 +188,9 @@ class ConfigCLI(CLI):
context.CLIARGS['func']()
def execute_update(self):
- '''
+ """
Updates a single setting in the specified ansible.cfg
- '''
+ """
raise AnsibleError("Option not implemented yet")
# pylint: disable=unreachable
@@ -212,9 +212,9 @@ class ConfigCLI(CLI):
])
def execute_view(self):
- '''
+ """
Displays the current config file
- '''
+ """
try:
with open(self.config_file, 'rb') as f:
self.pager(to_text(f.read(), errors='surrogate_or_strict'))
@@ -222,9 +222,9 @@ class ConfigCLI(CLI):
raise AnsibleError("Failed to open config file: %s" % to_native(e))
def execute_edit(self):
- '''
+ """
Opens ansible.cfg in the default EDITOR
- '''
+ """
raise AnsibleError("Option not implemented yet")
# pylint: disable=unreachable
@@ -266,9 +266,9 @@ class ConfigCLI(CLI):
return entries
def _list_entries_from_args(self):
- '''
+ """
build a dict with the list requested configs
- '''
+ """
config_entries = {}
if context.CLIARGS['type'] in ('base', 'all'):
@@ -294,9 +294,9 @@ class ConfigCLI(CLI):
return config_entries
def execute_list(self):
- '''
+ """
list and output available configs
- '''
+ """
config_entries = self._list_entries_from_args()
if context.CLIARGS['format'] == 'yaml':
@@ -599,9 +599,9 @@ class ConfigCLI(CLI):
return output
def execute_dump(self):
- '''
+ """
Shows the current settings, merges ansible.cfg if specified
- '''
+ """
output = []
if context.CLIARGS['type'] in ('base', 'all'):
# deal with base
diff --git a/lib/ansible/cli/console.py b/lib/ansible/cli/console.py
index 60f9cdd84a..6f355938aa 100755
--- a/lib/ansible/cli/console.py
+++ b/lib/ansible/cli/console.py
@@ -35,7 +35,7 @@ display = Display()
class ConsoleCLI(CLI, cmd.Cmd):
- '''
+ """
A REPL that allows for running ad-hoc tasks against a chosen inventory
from a nice shell with built-in tab completion (based on dominis'
``ansible-shell``).
@@ -62,7 +62,7 @@ class ConsoleCLI(CLI, cmd.Cmd):
- ``help [command/module]``: display documentation for
the command or module
- ``exit``: exit ``ansible-console``
- '''
+ """
name = 'ansible-console'
modules = [] # type: list[str] | None
@@ -579,7 +579,7 @@ class ConsoleCLI(CLI, cmd.Cmd):
self.cmdloop()
def __getattr__(self, name):
- ''' handle not found to populate dynamically a module function if module matching name exists '''
+ """ handle not found to populate dynamically a module function if module matching name exists """
attr = None
if name.startswith('do_'):
diff --git a/lib/ansible/cli/doc.py b/lib/ansible/cli/doc.py
index a6a73b50b7..af13782990 100755
--- a/lib/ansible/cli/doc.py
+++ b/lib/ansible/cli/doc.py
@@ -409,7 +409,7 @@ def _doclink(url):
def _format(string, *args):
- ''' add ascii formatting or delimiters '''
+ """ add ascii formatting or delimiters """
for style in args:
@@ -433,10 +433,10 @@ def _format(string, *args):
class DocCLI(CLI, RoleMixin):
- ''' displays information on modules installed in Ansible libraries.
+ """ displays information on modules installed in Ansible libraries.
It displays a terse listing of plugins and their short descriptions,
provides a printout of their DOCUMENTATION strings,
- and it can create a short "snippet" which can be pasted into a playbook. '''
+ and it can create a short "snippet" which can be pasted into a playbook. """
name = 'ansible-doc'
@@ -850,14 +850,14 @@ class DocCLI(CLI, RoleMixin):
return plugin_docs
def _get_roles_path(self):
- '''
+ """
Add any 'roles' subdir in playbook dir to the roles search path.
And as a last resort, add the playbook dir itself. Order being:
- 'roles' subdir of playbook dir
- DEFAULT_ROLES_PATH (default in cliargs)
- playbook dir (basedir)
NOTE: This matches logic in RoleDefinition._load_role_path() method.
- '''
+ """
roles_path = context.CLIARGS['roles_path']
if context.CLIARGS['basedir'] is not None:
subdir = os.path.join(context.CLIARGS['basedir'], "roles")
@@ -868,7 +868,7 @@ class DocCLI(CLI, RoleMixin):
@staticmethod
def _prep_loader(plugin_type):
- ''' return a plugint type specific loader '''
+ """ return a plugint type specific loader """
loader = getattr(plugin_loader, '%s_loader' % plugin_type)
# add to plugin paths from command line
@@ -1058,7 +1058,7 @@ class DocCLI(CLI, RoleMixin):
@staticmethod
def format_snippet(plugin, plugin_type, doc):
- ''' return heavily commented plugin use to insert into play '''
+ """ return heavily commented plugin use to insert into play """
if plugin_type == 'inventory' and doc.get('options', {}).get('plugin'):
# these do not take a yaml config that we can write a snippet for
raise ValueError('The {0} inventory plugin does not take YAML type config source'
@@ -1140,7 +1140,7 @@ class DocCLI(CLI, RoleMixin):
@staticmethod
def print_paths(finder):
- ''' Returns a string suitable for printing of the search path '''
+ """ Returns a string suitable for printing of the search path """
# Uses a list to get the order right
ret = []
@@ -1280,7 +1280,7 @@ class DocCLI(CLI, RoleMixin):
DocCLI.add_fields(text, subdata, limit, opt_indent + ' ', return_values, opt_indent)
def get_role_man_text(self, role, role_json):
- '''Generate text for the supplied role suitable for display.
+ """Generate text for the supplied role suitable for display.
This is similar to get_man_text(), but roles are different enough that we have
a separate method for formatting their display.
@@ -1289,7 +1289,7 @@ class DocCLI(CLI, RoleMixin):
:param role_json: The JSON for the given role as returned from _create_role_doc().
:returns: A array of text suitable for displaying to screen.
- '''
+ """
text = []
opt_indent = " "
pad = display.columns * 0.20
diff --git a/lib/ansible/cli/galaxy.py b/lib/ansible/cli/galaxy.py
index 17c923209d..5e2bef6f15 100755
--- a/lib/ansible/cli/galaxy.py
+++ b/lib/ansible/cli/galaxy.py
@@ -177,11 +177,11 @@ class RoleDistributionServer:
class GalaxyCLI(CLI):
- '''Command to manage Ansible roles and collections.
+ """Command to manage Ansible roles and collections.
None of the CLI tools are designed to run concurrently with themselves.
Use an external scheduler and/or locking to ensure there are no clashing operations.
- '''
+ """
name = 'ansible-galaxy'
@@ -212,7 +212,7 @@ class GalaxyCLI(CLI):
super(GalaxyCLI, self).__init__(args)
def init_parser(self):
- ''' create an options parser for bin/ansible '''
+ """ create an options parser for bin/ansible """
super(GalaxyCLI, self).init_parser(
desc="Perform various Role and Collection related operations.",
@@ -1721,7 +1721,7 @@ class GalaxyCLI(CLI):
publish_collection(collection_path, self.api, wait, timeout)
def execute_search(self):
- ''' searches for roles on the Ansible Galaxy server'''
+ """ searches for roles on the Ansible Galaxy server"""
page_size = 1000
search = None
diff --git a/lib/ansible/cli/inventory.py b/lib/ansible/cli/inventory.py
index 6a4ee9241f..5d99d24ed6 100755
--- a/lib/ansible/cli/inventory.py
+++ b/lib/ansible/cli/inventory.py
@@ -26,7 +26,7 @@ display = Display()
class InventoryCLI(CLI):
- ''' used to display or dump the configured inventory as Ansible sees it '''
+ """ used to display or dump the configured inventory as Ansible sees it """
name = 'ansible-inventory'
diff --git a/lib/ansible/cli/playbook.py b/lib/ansible/cli/playbook.py
index 1a3542de1c..9e0e19d3c5 100755
--- a/lib/ansible/cli/playbook.py
+++ b/lib/ansible/cli/playbook.py
@@ -29,8 +29,8 @@ display = Display()
class PlaybookCLI(CLI):
- ''' the tool to run *Ansible playbooks*, which are a configuration and multinode deployment system.
- See the project home page (https://docs.ansible.com) for more information. '''
+ """ the tool to run *Ansible playbooks*, which are a configuration and multinode deployment system.
+ See the project home page (https://docs.ansible.com) for more information. """
name = 'ansible-playbook'
diff --git a/lib/ansible/cli/pull.py b/lib/ansible/cli/pull.py
index eb8436636e..212d63872e 100755
--- a/lib/ansible/cli/pull.py
+++ b/lib/ansible/cli/pull.py
@@ -33,7 +33,7 @@ display = Display()
class PullCLI(CLI):
- ''' Used to pull a remote copy of ansible on each managed node,
+ """ Used to pull a remote copy of ansible on each managed node,
each set to run via cron and update playbook source via a source repository.
This inverts the default *push* architecture of ansible into a *pull* architecture,
which has near-limitless scaling potential.
@@ -45,7 +45,7 @@ class PullCLI(CLI):
This is useful both for extreme scale-out as well as periodic remediation.
Usage of the 'fetch' module to retrieve logs from ansible-pull runs would be an
excellent way to gather and analyze remote logs from ansible-pull.
- '''
+ """
name = 'ansible-pull'
@@ -76,7 +76,7 @@ class PullCLI(CLI):
return inv_opts
def init_parser(self):
- ''' create an options parser for bin/ansible '''
+ """ create an options parser for bin/ansible """
super(PullCLI, self).init_parser(
usage='%prog -U <repository> [options] [<playbook.yml>]',
@@ -157,7 +157,7 @@ class PullCLI(CLI):
return options
def run(self):
- ''' use Runner lib to do SSH things '''
+ """ use Runner lib to do SSH things """
super(PullCLI, self).run()
diff --git a/lib/ansible/cli/scripts/ansible_connection_cli_stub.py b/lib/ansible/cli/scripts/ansible_connection_cli_stub.py
index 701dcdaa19..0c8baa9871 100644
--- a/lib/ansible/cli/scripts/ansible_connection_cli_stub.py
+++ b/lib/ansible/cli/scripts/ansible_connection_cli_stub.py
@@ -57,10 +57,10 @@ def file_lock(lock_path):
class ConnectionProcess(object):
- '''
+ """
The connection process wraps around a Connection object that manages
the connection to a remote device that persists over the playbook
- '''
+ """
def __init__(self, fd, play_context, socket_path, original_path, task_uuid=None, ansible_playbook_pid=None):
self.play_context = play_context
self.socket_path = socket_path
diff --git a/lib/ansible/cli/vault.py b/lib/ansible/cli/vault.py
index 86902a695f..8b6dc88a3d 100755
--- a/lib/ansible/cli/vault.py
+++ b/lib/ansible/cli/vault.py
@@ -25,7 +25,7 @@ display = Display()
class VaultCLI(CLI):
- ''' can encrypt any structured data file used by Ansible.
+ """ can encrypt any structured data file used by Ansible.
This can include *group_vars/* or *host_vars/* inventory variables,
variables loaded by *include_vars* or *vars_files*, or variable files
passed on the ansible-playbook command line with *-e @file.yml* or *-e @file.json*.
@@ -33,7 +33,7 @@ class VaultCLI(CLI):
Because Ansible tasks, handlers, and other objects are data, these can also be encrypted with vault.
If you'd like to not expose what variables you are using, you can keep an individual task file entirely encrypted.
- '''
+ """
name = 'ansible-vault'
@@ -252,7 +252,7 @@ class VaultCLI(CLI):
os.umask(old_umask)
def execute_encrypt(self):
- ''' encrypt the supplied file using the provided vault secret '''
+ """ encrypt the supplied file using the provided vault secret """
if not context.CLIARGS['args'] and sys.stdin.isatty():
display.display("Reading plaintext input from stdin", stderr=True)
@@ -286,7 +286,7 @@ class VaultCLI(CLI):
return yaml_ciphertext
def execute_encrypt_string(self):
- ''' encrypt the supplied string using the provided vault secret '''
+ """ encrypt the supplied string using the provided vault secret """
b_plaintext = None
# Holds tuples (the_text, the_source_of_the_string, the variable name if its provided).
@@ -431,7 +431,7 @@ class VaultCLI(CLI):
return output
def execute_decrypt(self):
- ''' decrypt the supplied file using the provided vault secret '''
+ """ decrypt the supplied file using the provided vault secret """
if not context.CLIARGS['args'] and sys.stdin.isatty():
display.display("Reading ciphertext input from stdin", stderr=True)
@@ -443,7 +443,7 @@ class VaultCLI(CLI):
display.display("Decryption successful", stderr=True)
def execute_create(self):
- ''' create and open a file in an editor that will be encrypted with the provided vault secret when closed'''
+ """ create and open a file in an editor that will be encrypted with the provided vault secret when closed"""
if len(context.CLIARGS['args']) != 1:
raise AnsibleOptionsError("ansible-vault create can take only one filename argument")
@@ -455,12 +455,12 @@ class VaultCLI(CLI):
raise AnsibleOptionsError("not a tty, editor cannot be opened")
def execute_edit(self):
- ''' open and decrypt an existing vaulted file in an editor, that will be encrypted again when closed'''
+ """ open and decrypt an existing vaulted file in an editor, that will be encrypted again when closed"""
for f in context.CLIARGS['args']:
self.editor.edit_file(f)
def execute_view(self):
- ''' open, decrypt and view an existing vaulted file using a pager using the supplied vault secret '''
+ """ open, decrypt and view an existing vaulted file using a pager using the supplied vault secret """
for f in context.CLIARGS['args']:
# Note: vault should return byte strings because it could encrypt
@@ -472,7 +472,7 @@ class VaultCLI(CLI):
self.pager(to_text(plaintext))
def execute_rekey(self):
- ''' re-encrypt a vaulted file with a new secret, the previous secret is required '''
+ """ re-encrypt a vaulted file with a new secret, the previous secret is required """
for f in context.CLIARGS['args']:
# FIXME: plumb in vault_id, use the default new_vault_secret for now
self.editor.rekey_file(f, self.new_encrypt_secret,
diff --git a/lib/ansible/compat/__init__.py b/lib/ansible/compat/__init__.py
index 9977603e9d..3f39dd4c6a 100644
--- a/lib/ansible/compat/__init__.py
+++ b/lib/ansible/compat/__init__.py
@@ -15,9 +15,9 @@
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
Compat library for ansible. This contains compatibility definitions for older python
When we need to import a module differently depending on python version, do it
here. Then in the code we can simply import from compat in order to get what we want.
-'''
+"""
from __future__ import annotations
diff --git a/lib/ansible/config/manager.py b/lib/ansible/config/manager.py
index 4bbd9cbf9d..f71613bca6 100644
--- a/lib/ansible/config/manager.py
+++ b/lib/ansible/config/manager.py
@@ -53,7 +53,7 @@ GALAXY_SERVER_ADDITIONAL = {
def _get_entry(plugin_type, plugin_name, config):
- ''' construct entry for requested config '''
+ """ construct entry for requested config """
entry = ''
if plugin_type:
entry += 'plugin_type: %s ' % plugin_type
@@ -65,7 +65,7 @@ def _get_entry(plugin_type, plugin_name, config):
# FIXME: see if we can unify in module_utils with similar function used by argspec
def ensure_type(value, value_type, origin=None, origin_ftype=None):
- ''' return a configuration variable with casting
+ """ return a configuration variable with casting
:arg value: The value to ensure correct typing of
:kwarg value_type: The type of the value. This can be any of the following strings:
:boolean: sets the value to a True or False value
@@ -88,7 +88,7 @@ def ensure_type(value, value_type, origin=None, origin_ftype=None):
tildes's in the value.
:str: Sets the value to string types.
:string: Same as 'str'
- '''
+ """
errmsg = ''
basedir = None
@@ -190,7 +190,7 @@ def ensure_type(value, value_type, origin=None, origin_ftype=None):
# FIXME: see if this can live in utils/path
def resolve_path(path, basedir=None):
- ''' resolve relative or 'variable' paths '''
+ """ resolve relative or 'variable' paths """
if '{{CWD}}' in path: # allow users to force CWD using 'magic' {{CWD}}
path = path.replace('{{CWD}}', os.getcwd())
@@ -215,7 +215,7 @@ def get_config_type(cfile):
# FIXME: can move to module_utils for use for ini plugins also?
def get_ini_config_value(p, entry):
- ''' returns the value of last ini entry found '''
+ """ returns the value of last ini entry found """
value = None
if p is not None:
try:
@@ -226,7 +226,7 @@ def get_ini_config_value(p, entry):
def find_ini_config_file(warnings=None):
- ''' Load INI Config File order(first found is used): ENV, CWD, HOME, /etc/ansible '''
+ """ Load INI Config File order(first found is used): ENV, CWD, HOME, /etc/ansible """
# FIXME: eventually deprecate ini configs
if warnings is None:
@@ -289,7 +289,7 @@ def find_ini_config_file(warnings=None):
def _add_base_defs_deprecations(base_defs):
- '''Add deprecation source 'ansible.builtin' to deprecations in base.yml'''
+ """Add deprecation source 'ansible.builtin' to deprecations in base.yml"""
def process(entry):
if 'deprecated' in entry:
entry['deprecated']['collection_name'] = 'ansible.builtin'
@@ -388,7 +388,7 @@ class ConfigManager(object):
"Missing base YAML definition file (bad install?): %s" % to_native(yml_file))
def _parse_config_file(self, cfile=None):
- ''' return flat configuration settings from file(s) '''
+ """ return flat configuration settings from file(s) """
# TODO: take list of files with merge/nomerge
if cfile is None:
@@ -415,7 +415,7 @@ class ConfigManager(object):
raise AnsibleOptionsError("Unsupported configuration file type: %s" % to_native(ftype))
def _find_yaml_config_files(self):
- ''' Load YAML Config Files in order, check merge flags, keep origin of settings'''
+ """ Load YAML Config Files in order, check merge flags, keep origin of settings"""
pass
def get_plugin_options(self, plugin_type, name, keys=None, variables=None, direct=None):
@@ -467,7 +467,7 @@ class ConfigManager(object):
return has
def get_configuration_definitions(self, plugin_type=None, name=None, ignore_private=False):
- ''' just list the possible settings, either base or for specific plugins or plugin '''
+ """ just list the possible settings, either base or for specific plugins or plugin """
ret = {}
if plugin_type is None:
@@ -484,7 +484,7 @@ class ConfigManager(object):
return ret
def _loop_entries(self, container, entry_list):
- ''' repeat code for value entry assignment '''
+ """ repeat code for value entry assignment """
value = None
origin = None
@@ -510,7 +510,7 @@ class ConfigManager(object):
return value, origin
def get_config_value(self, config, cfile=None, plugin_type=None, plugin_name=None, keys=None, variables=None, direct=None):
- ''' wrapper '''
+ """ wrapper """
try:
value, _drop = self.get_config_value_and_origin(config, cfile=cfile, plugin_type=plugin_type, plugin_name=plugin_name,
@@ -522,7 +522,7 @@ class ConfigManager(object):
return value
def get_config_value_and_origin(self, config, cfile=None, plugin_type=None, plugin_name=None, keys=None, variables=None, direct=None):
- ''' Given a config key figure out the actual value and report on the origin of the settings '''
+ """ Given a config key figure out the actual value and report on the origin of the settings """
if cfile is None:
# use default config
cfile = self._config_file
diff --git a/lib/ansible/constants.py b/lib/ansible/constants.py
index 34f91db54e..af60053a3d 100644
--- a/lib/ansible/constants.py
+++ b/lib/ansible/constants.py
@@ -21,7 +21,7 @@ config = ConfigManager()
def _warning(msg):
- ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
+ """ display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write """
try:
from ansible.utils.display import Display
Display().warning(msg)
@@ -31,7 +31,7 @@ def _warning(msg):
def _deprecated(msg, version):
- ''' display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write '''
+ """ display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write """
try:
from ansible.utils.display import Display
Display().deprecated(msg, version=version)
@@ -63,7 +63,7 @@ def handle_config_noise(display=None):
def set_constant(name, value, export=vars()):
- ''' sets constants and returns resolved options dict '''
+ """ sets constants and returns resolved options dict """
export[name] = value
diff --git a/lib/ansible/errors/__init__.py b/lib/ansible/errors/__init__.py
index 78853757f8..31ee4bdf1d 100644
--- a/lib/ansible/errors/__init__.py
+++ b/lib/ansible/errors/__init__.py
@@ -36,7 +36,7 @@ from ansible.module_utils.common.text.converters import to_native, to_text
class AnsibleError(Exception):
- '''
+ """
This is the base class for all errors raised from Ansible code,
and can be instantiated with two optional parameters beyond the
error message to control whether detailed information is displayed
@@ -48,7 +48,7 @@ class AnsibleError(Exception):
Where "obj" is some subclass of ansible.parsing.yaml.objects.AnsibleBaseYAMLObject,
which should be returned by the DataLoader() class.
- '''
+ """
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None):
super(AnsibleError, self).__init__(message)
@@ -92,11 +92,11 @@ class AnsibleError(Exception):
return self.message
def _get_error_lines_from_file(self, file_name, line_number):
- '''
+ """
Returns the line in the file which corresponds to the reported error
location, as well as the line preceding it (if the error did not
occur on the first line), to provide context to the error.
- '''
+ """
target_line = ''
prev_line = ''
@@ -125,7 +125,7 @@ class AnsibleError(Exception):
return (target_line, prev_line)
def _get_extended_error(self):
- '''
+ """
Given an object reporting the location of the exception in a file, return
detailed information regarding it including:
@@ -134,7 +134,7 @@ class AnsibleError(Exception):
If this error was created with show_content=False, the reporting of content
is suppressed, as the file contents may be sensitive (ie. vault data).
- '''
+ """
error_message = ''
@@ -214,85 +214,85 @@ class AnsibleError(Exception):
class AnsiblePromptInterrupt(AnsibleError):
- '''User interrupt'''
+ """User interrupt"""
class AnsiblePromptNoninteractive(AnsibleError):
- '''Unable to get user input'''
+ """Unable to get user input"""
class AnsibleAssertionError(AnsibleError, AssertionError):
- '''Invalid assertion'''
+ """Invalid assertion"""
pass
class AnsibleOptionsError(AnsibleError):
- ''' bad or incomplete options passed '''
+ """ bad or incomplete options passed """
pass
class AnsibleRequiredOptionError(AnsibleOptionsError):
- ''' bad or incomplete options passed '''
+ """ bad or incomplete options passed """
pass
class AnsibleParserError(AnsibleError):
- ''' something was detected early that is wrong about a playbook or data file '''
+ """ something was detected early that is wrong about a playbook or data file """
pass
class AnsibleInternalError(AnsibleError):
- ''' internal safeguards tripped, something happened in the code that should never happen '''
+ """ internal safeguards tripped, something happened in the code that should never happen """
pass
class AnsibleRuntimeError(AnsibleError):
- ''' ansible had a problem while running a playbook '''
+ """ ansible had a problem while running a playbook """
pass
class AnsibleModuleError(AnsibleRuntimeError):
- ''' a module failed somehow '''
+ """ a module failed somehow """
pass
class AnsibleConnectionFailure(AnsibleRuntimeError):
- ''' the transport / connection_plugin had a fatal error '''
+ """ the transport / connection_plugin had a fatal error """
pass
class AnsibleAuthenticationFailure(AnsibleConnectionFailure):
- '''invalid username/password/key'''
+ """invalid username/password/key"""
pass
class AnsibleCallbackError(AnsibleRuntimeError):
- ''' a callback failure '''
+ """ a callback failure """
pass
class AnsibleTemplateError(AnsibleRuntimeError):
- '''A template related error'''
+ """A template related error"""
pass
class AnsibleFilterError(AnsibleTemplateError):
- ''' a templating failure '''
+ """ a templating failure """
pass
class AnsibleLookupError(AnsibleTemplateError):
- ''' a lookup failure '''
+ """ a lookup failure """
pass
class AnsibleUndefinedVariable(AnsibleTemplateError):
- ''' a templating failure '''
+ """ a templating failure """
pass
class AnsibleFileNotFound(AnsibleRuntimeError):
- ''' a file missing failure '''
+ """ a file missing failure """
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, paths=None, file_name=None):
@@ -322,7 +322,7 @@ class AnsibleFileNotFound(AnsibleRuntimeError):
# DO NOT USE as they will probably be removed soon.
# We will port the action modules in our tree to use a context manager instead.
class AnsibleAction(AnsibleRuntimeError):
- ''' Base Exception for Action plugin flow control '''
+ """ Base Exception for Action plugin flow control """
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, result=None):
@@ -335,7 +335,7 @@ class AnsibleAction(AnsibleRuntimeError):
class AnsibleActionSkip(AnsibleAction):
- ''' an action runtime skip'''
+ """ an action runtime skip"""
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, result=None):
super(AnsibleActionSkip, self).__init__(message=message, obj=obj, show_content=show_content,
@@ -344,7 +344,7 @@ class AnsibleActionSkip(AnsibleAction):
class AnsibleActionFail(AnsibleAction):
- ''' an action runtime failure'''
+ """ an action runtime failure"""
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=False, orig_exc=None, result=None):
super(AnsibleActionFail, self).__init__(message=message, obj=obj, show_content=show_content,
suppress_extended_error=suppress_extended_error, orig_exc=orig_exc, result=result)
@@ -352,37 +352,37 @@ class AnsibleActionFail(AnsibleAction):
class _AnsibleActionDone(AnsibleAction):
- ''' an action runtime early exit'''
+ """ an action runtime early exit"""
pass
class AnsiblePluginError(AnsibleError):
- ''' base class for Ansible plugin-related errors that do not need AnsibleError contextual data '''
+ """ base class for Ansible plugin-related errors that do not need AnsibleError contextual data """
def __init__(self, message=None, plugin_load_context=None):
super(AnsiblePluginError, self).__init__(message)
self.plugin_load_context = plugin_load_context
class AnsiblePluginRemovedError(AnsiblePluginError):
- ''' a requested plugin has been removed '''
+ """ a requested plugin has been removed """
pass
class AnsiblePluginCircularRedirect(AnsiblePluginError):
- '''a cycle was detected in plugin redirection'''
+ """a cycle was detected in plugin redirection"""
pass
class AnsibleCollectionUnsupportedVersionError(AnsiblePluginError):
- '''a collection is not supported by this version of Ansible'''
+ """a collection is not supported by this version of Ansible"""
pass
class AnsibleFilterTypeError(AnsibleTemplateError, TypeError):
- ''' a Jinja filter templating failure due to bad type'''
+ """ a Jinja filter templating failure due to bad type"""
pass
class AnsiblePluginNotFound(AnsiblePluginError):
- ''' Indicates we did not find an Ansible plugin '''
+ """ Indicates we did not find an Ansible plugin """
pass
diff --git a/lib/ansible/executor/module_common.py b/lib/ansible/executor/module_common.py
index 717a39833c..d4c2eab600 100644
--- a/lib/ansible/executor/module_common.py
+++ b/lib/ansible/executor/module_common.py
@@ -74,7 +74,7 @@ _MODULE_UTILS_PATH = os.path.join(os.path.dirname(__file__), '..', 'module_utils
# ******************************************************************************
-ANSIBALLZ_TEMPLATE = u'''%(shebang)s
+ANSIBALLZ_TEMPLATE = u"""%(shebang)s
%(coding)s
_ANSIBALLZ_WRAPPER = True # For test-module.py script to tell this is a ANSIBALLZ_WRAPPER
# This code is part of Ansible, but is an independent component.
@@ -333,9 +333,9 @@ def _ansiballz_main():
if __name__ == '__main__':
_ansiballz_main()
-'''
+"""
-ANSIBALLZ_COVERAGE_TEMPLATE = '''
+ANSIBALLZ_COVERAGE_TEMPLATE = """
os.environ['COVERAGE_FILE'] = %(coverage_output)r + '=python-%%s=coverage' %% '.'.join(str(v) for v in sys.version_info[:2])
import atexit
@@ -355,9 +355,9 @@ ANSIBALLZ_COVERAGE_TEMPLATE = '''
atexit.register(atexit_coverage)
cov.start()
-'''
+"""
-ANSIBALLZ_COVERAGE_CHECK_TEMPLATE = '''
+ANSIBALLZ_COVERAGE_CHECK_TEMPLATE = """
try:
if PY3:
import importlib.util
@@ -369,9 +369,9 @@ ANSIBALLZ_COVERAGE_CHECK_TEMPLATE = '''
except ImportError:
print('{"msg": "Could not find `coverage` module.", "failed": true}')
sys.exit(1)
-'''
+"""
-ANSIBALLZ_RLIMIT_TEMPLATE = '''
+ANSIBALLZ_RLIMIT_TEMPLATE = """
import resource
existing_soft, existing_hard = resource.getrlimit(resource.RLIMIT_NOFILE)
@@ -385,7 +385,7 @@ ANSIBALLZ_RLIMIT_TEMPLATE = '''
except ValueError:
# some platforms (eg macOS) lie about their hard limit
pass
-'''
+"""
def _strip_comments(source):
diff --git a/lib/ansible/executor/play_iterator.py b/lib/ansible/executor/play_iterator.py
index 1ef7451095..e512b64b84 100644
--- a/lib/ansible/executor/play_iterator.py
+++ b/lib/ansible/executor/play_iterator.py
@@ -563,9 +563,9 @@ class PlayIterator:
self._clear_state_errors(state.always_child_state)
def get_active_state(self, state):
- '''
+ """
Finds the active state, recursively if necessary when there are child states.
- '''
+ """
if state.run_state == IteratingStates.TASKS and state.tasks_child_state is not None:
return self.get_active_state(state.tasks_child_state)
elif state.run_state == IteratingStates.RESCUE and state.rescue_child_state is not None:
@@ -575,10 +575,10 @@ class PlayIterator:
return state
def is_any_block_rescuing(self, state):
- '''
+ """
Given the current HostState state, determines if the current block, or any child blocks,
are in rescue mode.
- '''
+ """
if state.run_state == IteratingStates.TASKS and state.get_current_block().rescue:
return True
if state.tasks_child_state is not None:
diff --git a/lib/ansible/executor/playbook_executor.py b/lib/ansible/executor/playbook_executor.py
index f439967838..468c4bdc70 100644
--- a/lib/ansible/executor/playbook_executor.py
+++ b/lib/ansible/executor/playbook_executor.py
@@ -40,10 +40,10 @@ display = Display()
class PlaybookExecutor:
- '''
+ """
This is the primary class for executing playbooks, and thus the
basis for bin/ansible-playbook operation.
- '''
+ """
def __init__(self, playbooks, inventory, variable_manager, loader, passwords):
self._playbooks = playbooks
@@ -74,10 +74,10 @@ class PlaybookExecutor:
set_default_transport()
def run(self):
- '''
+ """
Run the given playbook, based on the settings in the play which
may limit the runs to serialized groups, etc.
- '''
+ """
result = 0
entrylist = []
@@ -267,10 +267,10 @@ class PlaybookExecutor:
return result
def _get_serialized_batches(self, play):
- '''
+ """
Returns a list of hosts, subdivided into batches based on
the serial size specified in the play.
- '''
+ """
# make sure we have a unique list of hosts
all_hosts = self._inventory.get_hosts(play.hosts, order=play.order)
@@ -313,11 +313,11 @@ class PlaybookExecutor:
return serialized_batches
def _generate_retry_inventory(self, retry_path, replay_hosts):
- '''
+ """
Called when a playbook run fails. It generates an inventory which allows
re-running on ONLY the failed hosts. This may duplicate some variable
information in group_vars/host_vars but that is ok, and expected.
- '''
+ """
try:
makedirs_safe(os.path.dirname(retry_path))
with open(retry_path, 'w') as fd:
diff --git a/lib/ansible/executor/process/worker.py b/lib/ansible/executor/process/worker.py
index 6c26aed164..f5e7b979f4 100644
--- a/lib/ansible/executor/process/worker.py
+++ b/lib/ansible/executor/process/worker.py
@@ -47,11 +47,11 @@ class WorkerQueue(Queue):
class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defined]
- '''
+ """
The worker thread class, which uses TaskExecutor to run tasks
read from a job queue and pushes results into a results queue
for reading later.
- '''
+ """
def __init__(self, final_q, task_vars, host, task, play_context, loader, variable_manager, shared_loader_obj, worker_id):
@@ -91,13 +91,13 @@ class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defin
self._new_stdin = open(os.devnull)
def start(self):
- '''
+ """
multiprocessing.Process replaces the worker's stdin with a new file
but we wish to preserve it if it is connected to a terminal.
Therefore dup a copy prior to calling the real start(),
ensuring the descriptor is preserved somewhere in the new child, and
make sure it is closed in the parent when start() completes.
- '''
+ """
self._save_stdin()
# FUTURE: this lock can be removed once a more generalized pre-fork thread pause is in place
@@ -108,12 +108,12 @@ class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defin
self._new_stdin.close()
def _hard_exit(self, e):
- '''
+ """
There is no safe exception to return to higher level code that does not
risk an innocent try/except finding itself executing in the wrong
process. All code executing above WorkerProcess.run() on the stack
conceptually belongs to another program.
- '''
+ """
try:
display.debug(u"WORKER HARD EXIT: %s" % to_text(e))
@@ -126,7 +126,7 @@ class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defin
os._exit(1)
def run(self):
- '''
+ """
Wrap _run() to ensure no possibility an errant exception can cause
control to return to the StrategyBase task loop, or any other code
higher in the stack.
@@ -134,7 +134,7 @@ class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defin
As multiprocessing in Python 2.x provides no protection, it is possible
a try/except added in far-away code can cause a crashed child process
to suddenly assume the role and prior state of its parent.
- '''
+ """
try:
return self._run()
except BaseException as e:
@@ -155,11 +155,11 @@ class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defin
sys.stdout = sys.stderr = open(os.devnull, 'w')
def _run(self):
- '''
+ """
Called when the process is started. Pushes the result onto the
results queue. We also remove the host from the blocked hosts list, to
signify that they are ready for their next task.
- '''
+ """
# import cProfile, pstats, StringIO
# pr = cProfile.Profile()
diff --git a/lib/ansible/executor/stats.py b/lib/ansible/executor/stats.py
index a7cc713b27..acedf10759 100644
--- a/lib/ansible/executor/stats.py
+++ b/lib/ansible/executor/stats.py
@@ -23,7 +23,7 @@ from ansible.utils.vars import merge_hash
class AggregateStats:
- ''' holds stats about per-host activity during playbook runs '''
+ """ holds stats about per-host activity during playbook runs """
def __init__(self):
@@ -40,7 +40,7 @@ class AggregateStats:
self.custom = {}
def increment(self, what, host):
- ''' helper function to bump a statistic '''
+ """ helper function to bump a statistic """
self.processed[host] = 1
prev = (getattr(self, what)).get(host, 0)
@@ -57,7 +57,7 @@ class AggregateStats:
_what[host] = 0
def summarize(self, host):
- ''' return information about a particular host '''
+ """ return information about a particular host """
return dict(
ok=self.ok.get(host, 0),
@@ -70,7 +70,7 @@ class AggregateStats:
)
def set_custom_stats(self, which, what, host=None):
- ''' allow setting of a custom stat'''
+ """ allow setting of a custom stat"""
if host is None:
host = '_run'
@@ -80,7 +80,7 @@ class AggregateStats:
self.custom[host][which] = what
def update_custom_stats(self, which, what, host=None):
- ''' allow aggregation of a custom stat'''
+ """ allow aggregation of a custom stat"""
if host is None:
host = '_run'
diff --git a/lib/ansible/executor/task_executor.py b/lib/ansible/executor/task_executor.py
index 932a33cfec..ebef9cbfd1 100644
--- a/lib/ansible/executor/task_executor.py
+++ b/lib/ansible/executor/task_executor.py
@@ -61,10 +61,10 @@ def task_timeout(signum, frame):
def remove_omit(task_args, omit_token):
- '''
+ """
Remove args with a value equal to the ``omit_token`` recursively
to align with now having suboptions in the argument_spec
- '''
+ """
if not isinstance(task_args, dict):
return task_args
@@ -85,12 +85,12 @@ def remove_omit(task_args, omit_token):
class TaskExecutor:
- '''
+ """
This is the main worker class for the executor pipeline, which
handles loading an action plugin to actually dispatch the task to
a given host. This class roughly corresponds to the old Runner()
class.
- '''
+ """
def __init__(self, host, task, job_vars, play_context, new_stdin, loader, shared_loader_obj, final_q, variable_manager):
self._host = host
@@ -108,12 +108,12 @@ class TaskExecutor:
self._task.squash()
def run(self):
- '''
+ """
The main executor entrypoint, where we determine if the specified
task requires looping and either runs the task with self._run_loop()
or self._execute(). After that, the returned results are parsed and
returned as a dict.
- '''
+ """
display.debug("in run() - task %s" % self._task._uuid)
@@ -218,10 +218,10 @@ class TaskExecutor:
display.debug(u"error closing connection: %s" % to_text(e))
def _get_loop_items(self):
- '''
+ """
Loads a lookup plugin to handle the with_* portion of a task (if specified),
and returns the items result.
- '''
+ """
# get search path for this task to pass to lookup plugins
self._job_vars['ansible_search_path'] = self._task.get_search_path()
@@ -266,11 +266,11 @@ class TaskExecutor:
return items
def _run_loop(self, items):
- '''
+ """
Runs the task with the loop items specified and collates the result
into an array named 'results' which is inserted into the final result
along with the item for which the loop ran.
- '''
+ """
task_vars = self._job_vars
templar = Templar(loader=self._loader, variables=task_vars)
@@ -452,11 +452,11 @@ class TaskExecutor:
variables.update(delegated_vars)
def _execute(self, variables=None):
- '''
+ """
The primary workhorse of the executor system, this runs the task
on the specified host (which may be the delegated_to host) and handles
the retry/until and block rescue/always execution
- '''
+ """
if variables is None:
variables = self._job_vars
@@ -858,9 +858,9 @@ class TaskExecutor:
return result
def _poll_async_result(self, result, templar, task_vars=None):
- '''
+ """
Polls for the specified JID to be complete
- '''
+ """
if task_vars is None:
task_vars = self._job_vars
@@ -976,10 +976,10 @@ class TaskExecutor:
return become
def _get_connection(self, cvars, templar, current_connection):
- '''
+ """
Reads the connection property for the host, and returns the
correct connection object from the list of connection plugins
- '''
+ """
self._play_context.connection = current_connection
@@ -1134,15 +1134,15 @@ class TaskExecutor:
return varnames
def _get_action_handler(self, templar):
- '''
+ """
Returns the correct action plugin to handle the requestion task action
- '''
+ """
return self._get_action_handler_with_module_context(templar)[0]
def _get_action_handler_with_module_context(self, templar):
- '''
+ """
Returns the correct action plugin to handle the requestion task action and the module context
- '''
+ """
module_collection, separator, module_name = self._task.action.rpartition(".")
module_prefix = module_name.split('_')[0]
if module_collection:
@@ -1216,9 +1216,9 @@ CLI_STUB_NAME = 'ansible_connection_cli_stub.py'
def start_connection(play_context, options, task_uuid):
- '''
+ """
Starts the persistent connection
- '''
+ """
env = os.environ.copy()
env.update({
diff --git a/lib/ansible/executor/task_queue_manager.py b/lib/ansible/executor/task_queue_manager.py
index 3b9e251da8..75f8a69861 100644
--- a/lib/ansible/executor/task_queue_manager.py
+++ b/lib/ansible/executor/task_queue_manager.py
@@ -112,7 +112,7 @@ class AnsibleEndPlay(Exception):
class TaskQueueManager:
- '''
+ """
This class handles the multiprocessing requirements of Ansible by
creating a pool of worker forks, a result handler fork, and a
manager object with shared datastructures/queues for coordinating
@@ -120,7 +120,7 @@ class TaskQueueManager:
The queue manager is responsible for loading the play strategy plugin,
which dispatches the Play's tasks to hosts.
- '''
+ """
RUN_OK = 0
RUN_ERROR = 1
@@ -176,11 +176,11 @@ class TaskQueueManager:
self._workers.append(None)
def load_callbacks(self):
- '''
+ """
Loads all available callbacks, with the exception of those which
utilize the CALLBACK_TYPE option. When CALLBACK_TYPE is set to 'stdout',
only one such callback plugin will be loaded.
- '''
+ """
if self._callbacks_loaded:
return
@@ -269,13 +269,13 @@ class TaskQueueManager:
self._callbacks_loaded = True
def run(self, play):
- '''
+ """
Iterates over the roles/tasks in a play, using the given (or default)
strategy for queueing tasks. The default is the linear strategy, which
operates like classic Ansible by keeping all hosts in lock-step with
a given task (meaning no hosts move on to the next task until all hosts
are done with the current task).
- '''
+ """
if not self._callbacks_loaded:
self.load_callbacks()
diff --git a/lib/ansible/executor/task_result.py b/lib/ansible/executor/task_result.py
index 821189367d..06e9af72e3 100644
--- a/lib/ansible/executor/task_result.py
+++ b/lib/ansible/executor/task_result.py
@@ -22,11 +22,11 @@ CLEAN_EXCEPTIONS = (
class TaskResult:
- '''
+ """
This class is responsible for interpreting the resulting data
from an executed task, and provides helper methods for determining
the result of a given task.
- '''
+ """
def __init__(self, host, task, return_data, task_fields=None):
self._host = host
@@ -93,7 +93,7 @@ class TaskResult:
return ret
def _check_key(self, key):
- '''get a specific key from the result or its items'''
+ """get a specific key from the result or its items"""
if isinstance(self._result, dict) and key in self._result:
return self._result.get(key, False)
@@ -106,7 +106,7 @@ class TaskResult:
def clean_copy(self):
- ''' returns 'clean' taskresult object '''
+ """ returns 'clean' taskresult object """
# FIXME: clean task_fields, _task and _host copies
result = TaskResult(self._host, self._task, {}, self._task_fields)
diff --git a/lib/ansible/galaxy/__init__.py b/lib/ansible/galaxy/__init__.py
index cc961c5dd1..7b6fa569f4 100644
--- a/lib/ansible/galaxy/__init__.py
+++ b/lib/ansible/galaxy/__init__.py
@@ -18,7 +18,7 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
########################################################################
-''' This manages remote shared Ansible objects, mainly roles'''
+""" This manages remote shared Ansible objects, mainly roles"""
from __future__ import annotations
@@ -40,7 +40,7 @@ def get_collections_galaxy_meta_info():
class Galaxy(object):
- ''' Keeps global galaxy info '''
+ """ Keeps global galaxy info """
def __init__(self):
# TODO: eventually remove this as it contains a mismash of properties that aren't really global
diff --git a/lib/ansible/galaxy/token.py b/lib/ansible/galaxy/token.py
index eb06a34181..9b82ad6c62 100644
--- a/lib/ansible/galaxy/token.py
+++ b/lib/ansible/galaxy/token.py
@@ -40,10 +40,10 @@ display = Display()
class KeycloakToken(object):
- '''A token granted by a Keycloak server.
+ """A token granted by a Keycloak server.
Like sso.redhat.com as used by cloud.redhat.com
- ie Automation Hub'''
+ ie Automation Hub"""
token_type = 'Bearer'
@@ -105,7 +105,7 @@ class KeycloakToken(object):
class GalaxyToken(object):
- ''' Class to storing and retrieving local galaxy token '''
+ """ Class to storing and retrieving local galaxy token """
token_type = 'Token'
diff --git a/lib/ansible/inventory/data.py b/lib/ansible/inventory/data.py
index 7282d6fb75..691ad5bed4 100644
--- a/lib/ansible/inventory/data.py
+++ b/lib/ansible/inventory/data.py
@@ -101,7 +101,7 @@ class InventoryData(object):
return new_host
def reconcile_inventory(self):
- ''' Ensure inventory basic rules, run after updates '''
+ """ Ensure inventory basic rules, run after updates """
display.debug('Reconcile groups and hosts in inventory.')
self.current_source = None
@@ -145,7 +145,7 @@ class InventoryData(object):
self._groups_dict_cache = {}
def get_host(self, hostname):
- ''' fetch host object using name deal with implicit localhost '''
+ """ fetch host object using name deal with implicit localhost """
matching_host = self.hosts.get(hostname, None)
@@ -157,7 +157,7 @@ class InventoryData(object):
return matching_host
def add_group(self, group):
- ''' adds a group to inventory if not there already, returns named actually used '''
+ """ adds a group to inventory if not there already, returns named actually used """
if group:
if not isinstance(group, string_types):
@@ -188,7 +188,7 @@ class InventoryData(object):
h.remove_group(group)
def add_host(self, host, group=None, port=None):
- ''' adds a host to inventory and possibly a group if not there already '''
+ """ adds a host to inventory and possibly a group if not there already """
if host:
if not isinstance(host, string_types):
@@ -242,7 +242,7 @@ class InventoryData(object):
g.remove_host(host)
def set_variable(self, entity, varname, value):
- ''' sets a variable for an inventory object '''
+ """ sets a variable for an inventory object """
if entity in self.groups:
inv_object = self.groups[entity]
@@ -255,7 +255,7 @@ class InventoryData(object):
display.debug('set %s for %s' % (varname, entity))
def add_child(self, group, child):
- ''' Add host or group to group '''
+ """ Add host or group to group """
added = False
if group in self.groups:
g = self.groups[group]
diff --git a/lib/ansible/inventory/group.py b/lib/ansible/inventory/group.py
index 73c913ac9e..335f60127c 100644
--- a/lib/ansible/inventory/group.py
+++ b/lib/ansible/inventory/group.py
@@ -59,7 +59,7 @@ class InventoryObjectType(Enum):
class Group:
- ''' a group of ansible hosts '''
+ """ a group of ansible hosts """
base_type = InventoryObjectType.GROUP
# __slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts_cache' ]
@@ -120,7 +120,7 @@ class Group:
self.parent_groups.append(g)
def _walk_relationship(self, rel, include_self=False, preserve_ordering=False):
- '''
+ """
Given `rel` that is an iterable property of Group,
consitituting a directed acyclic graph among all groups,
Returns a set of all groups in full tree
@@ -132,7 +132,7 @@ class Group:
| / are directed upward
F
Called on F, returns set of (A, B, C, D, E)
- '''
+ """
seen = set([])
unprocessed = set(getattr(self, rel))
if include_self:
diff --git a/lib/ansible/inventory/host.py b/lib/ansible/inventory/host.py
index b7aea10e72..fafa952092 100644
--- a/lib/ansible/inventory/host.py
+++ b/lib/ansible/inventory/host.py
@@ -28,7 +28,7 @@ __all__ = ['Host']
class Host:
- ''' a single ansible host '''
+ """ a single ansible host """
base_type = InventoryObjectType.HOST
# __slots__ = [ 'name', 'vars', 'groups' ]
diff --git a/lib/ansible/inventory/manager.py b/lib/ansible/inventory/manager.py
index 96df1f4647..ba6397f178 100644
--- a/lib/ansible/inventory/manager.py
+++ b/lib/ansible/inventory/manager.py
@@ -50,7 +50,7 @@ IGNORED_EXTS = [b'%s$' % to_bytes(re.escape(x)) for x in C.INVENTORY_IGNORE_EXTS
IGNORED = re.compile(b'|'.join(IGNORED_ALWAYS + IGNORED_PATTERNS + IGNORED_EXTS))
PATTERN_WITH_SUBSCRIPT = re.compile(
- r'''^
+ r"""^
(.+) # A pattern expression ending with...
\[(?: # A [subscript] expression comprising:
(-?[0-9]+)| # A single positive or negative number
@@ -58,12 +58,12 @@ PATTERN_WITH_SUBSCRIPT = re.compile(
([0-9]*)
)\]
$
- ''', re.X
+ """, re.X
)
def order_patterns(patterns):
- ''' takes a list of patterns and reorders them by modifier to apply them consistently '''
+ """ takes a list of patterns and reorders them by modifier to apply them consistently """
# FIXME: this goes away if we apply patterns incrementally or by groups
pattern_regular = []
@@ -125,19 +125,19 @@ def split_host_pattern(pattern):
# This mishandles IPv6 addresses, and is retained only for backwards
# compatibility.
patterns = re.findall(
- to_text(r'''(?: # We want to match something comprising:
+ to_text(r"""(?: # We want to match something comprising:
[^\s:\[\]] # (anything other than whitespace or ':[]'
| # ...or...
\[[^\]]*\] # a single complete bracketed expression)
)+ # occurring once or more
- '''), pattern, re.X
+ """), pattern, re.X
)
return [p.strip() for p in patterns if p.strip()]
class InventoryManager(object):
- ''' Creates and manages inventory '''
+ """ Creates and manages inventory """
def __init__(self, loader, sources=None, parse=True, cache=True):
@@ -197,7 +197,7 @@ class InventoryManager(object):
return self._inventory.get_host(hostname)
def _fetch_inventory_plugins(self):
- ''' sets up loaded inventory plugins for usage '''
+ """ sets up loaded inventory plugins for usage """
display.vvvv('setting up inventory plugins')
@@ -215,7 +215,7 @@ class InventoryManager(object):
return plugins
def parse_sources(self, cache=False):
- ''' iterate over inventory sources and parse each one to populate it'''
+ """ iterate over inventory sources and parse each one to populate it"""
parsed = False
# allow for multiple inventory parsing
@@ -243,7 +243,7 @@ class InventoryManager(object):
host.vars = combine_vars(host.vars, get_vars_from_inventory_sources(self._loader, self._sources, [host], 'inventory'))
def parse_source(self, source, cache=False):
- ''' Generate or update inventory for the source provided '''
+ """ Generate or update inventory for the source provided """
parsed = False
failures = []
@@ -335,12 +335,12 @@ class InventoryManager(object):
return parsed
def clear_caches(self):
- ''' clear all caches '''
+ """ clear all caches """
self._hosts_patterns_cache = {}
self._pattern_cache = {}
def refresh_inventory(self):
- ''' recalculate inventory '''
+ """ recalculate inventory """
self.clear_caches()
self._inventory = InventoryData()
@@ -657,9 +657,9 @@ class InventoryManager(object):
self._pattern_cache = {}
def add_dynamic_host(self, host_info, result_item):
- '''
+ """
Helper function to add a new host to inventory based on a task result.
- '''
+ """
changed = False
if not result_item.get('refresh'):
@@ -697,10 +697,10 @@ class InventoryManager(object):
result_item['changed'] = changed
def add_dynamic_group(self, host, result_item):
- '''
+ """
Helper function to add a group (if it does not exist), and to assign the
specified host to that group.
- '''
+ """
changed = False
diff --git a/lib/ansible/module_utils/basic.py b/lib/ansible/module_utils/basic.py
index 19dbb1d154..7156360fb0 100644
--- a/lib/ansible/module_utils/basic.py
+++ b/lib/ansible/module_utils/basic.py
@@ -199,14 +199,14 @@ PERMS_RE = re.compile(r'^[rwxXstugo]*$')
#
def get_platform():
- '''
+ """
**Deprecated** Use :py:func:`platform.system` directly.
:returns: Name of the platform the module is running on in a native string
Returns a native string that labels the platform ("Linux", "Solaris", etc). Currently, this is
the result of calling :py:func:`platform.system`.
- '''
+ """
return platform.system()
# End deprecated functions
@@ -231,7 +231,7 @@ def get_all_subclasses(cls):
def heuristic_log_sanitize(data, no_log_values=None):
- ''' Remove strings that look like passwords from log messages '''
+ """ Remove strings that look like passwords from log messages """
# Currently filters:
# user:pass@foo/whatever and http://username:pass@wherever/foo
# This code has false positives and consumes parts of logs that are
@@ -296,7 +296,7 @@ def heuristic_log_sanitize(data, no_log_values=None):
def _load_params():
- ''' read the modules parameters and store them globally.
+ """ read the modules parameters and store them globally.
This function may be needed for certain very dynamic custom modules which
want to process the parameters that are being handed the module. Since
@@ -305,7 +305,7 @@ def _load_params():
will try not to break it gratuitously. It is certainly more future-proof
to call this function and consume its outputs than to implement the logic
inside it as a copy in your own code.
- '''
+ """
global _ANSIBLE_ARGS
if _ANSIBLE_ARGS is not None:
buffer = _ANSIBLE_ARGS
@@ -363,13 +363,13 @@ class AnsibleModule(object):
required_one_of=None, add_file_common_args=False,
supports_check_mode=False, required_if=None, required_by=None):
- '''
+ """
Common code for quickly building an ansible module in Python
(although you can write modules with anything that can return JSON).
See :ref:`developing_modules_general` for a general introduction
and :ref:`developing_program_flow_modules` for more detailed explanation.
- '''
+ """
self._name = os.path.basename(__file__) # initialize name until we can parse from options
self.argument_spec = argument_spec
@@ -516,13 +516,13 @@ class AnsibleModule(object):
self.log('[DEPRECATION WARNING] %s %s' % (msg, version))
def load_file_common_arguments(self, params, path=None):
- '''
+ """
many modules deal with files, this encapsulates common
options that the file module accepts such that it is directly
available to all modules and they can share code.
Allows to overwrite the path/dest module argument by providing path.
- '''
+ """
if path is None:
path = params.get('path', params.get('dest', None))
@@ -635,12 +635,12 @@ class AnsibleModule(object):
return (uid, gid)
def find_mount_point(self, path):
- '''
+ """
Takes a path and returns its mount point
:param path: a string type with a filesystem path
:returns: the path to the mount point as a text type
- '''
+ """
b_path = os.path.realpath(to_bytes(os.path.expanduser(os.path.expandvars(path)), errors='surrogate_or_strict'))
while not os.path.ismount(b_path):
@@ -1115,10 +1115,10 @@ class AnsibleModule(object):
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
def add_path_info(self, kwargs):
- '''
+ """
for results that are files, supplement the info about the file
in the return path with stats about the file path.
- '''
+ """
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
@@ -1155,10 +1155,10 @@ class AnsibleModule(object):
return kwargs
def _check_locale(self):
- '''
+ """
Uses the locale module to test the currently set locale
(per the LANG and LC_CTYPE environment settings)
- '''
+ """
try:
# setting the locale to '' uses the default locale
# as it would be returned by locale.getdefaultlocale()
@@ -1206,11 +1206,11 @@ class AnsibleModule(object):
return safe_eval(value, locals, include_exceptions)
def _load_params(self):
- ''' read the input and set the params attribute.
+ """ read the input and set the params attribute.
This method is for backwards compatibility. The guts of the function
were moved out in 2.1 so that custom modules could read the parameters.
- '''
+ """
# debug overrides to read args from file or cmdline
self.params = _load_params()
@@ -1297,7 +1297,7 @@ class AnsibleModule(object):
self._log_to_syslog(journal_msg)
def _log_invocation(self):
- ''' log that ansible ran the module '''
+ """ log that ansible ran the module """
# TODO: generalize a separate log function and make log_invocation use it
# Sanitize possible password argument when logging.
log_args = dict()
@@ -1350,7 +1350,7 @@ class AnsibleModule(object):
return None
def get_bin_path(self, arg, required=False, opt_dirs=None):
- '''
+ """
Find system executable in PATH.
:param arg: The executable to find.
@@ -1358,7 +1358,7 @@ class AnsibleModule(object):
:param opt_dirs: optional list of directories to search in addition to ``PATH``
:returns: if found return full path; otherwise return original arg, unless 'warning' then return None
:raises: Sysexit: if arg is not found and required=True (via fail_json)
- '''
+ """
bin_path = None
try:
@@ -1370,7 +1370,7 @@ class AnsibleModule(object):
return bin_path
def boolean(self, arg):
- '''Convert the argument to a boolean'''
+ """Convert the argument to a boolean"""
if arg is None:
return arg
@@ -1447,14 +1447,14 @@ class AnsibleModule(object):
print('\n%s' % self.jsonify(kwargs))
def exit_json(self, **kwargs):
- ''' return from the module, without error '''
+ """ return from the module, without error """
self.do_cleanup_files()
self._return_formatted(kwargs)
sys.exit(0)
def fail_json(self, msg, **kwargs):
- ''' return from the module, with an error message '''
+ """ return from the module, with an error message """
kwargs['failed'] = True
kwargs['msg'] = msg
@@ -1477,7 +1477,7 @@ class AnsibleModule(object):
self.fail_json(msg=to_native(e))
def digest_from_file(self, filename, algorithm):
- ''' Return hex digest of local file for a digest_method specified by name, or None if file is not present. '''
+ """ Return hex digest of local file for a digest_method specified by name, or None if file is not present. """
b_filename = to_bytes(filename, errors='surrogate_or_strict')
if not os.path.exists(b_filename):
@@ -1505,7 +1505,7 @@ class AnsibleModule(object):
return digest_method.hexdigest()
def md5(self, filename):
- ''' Return MD5 hex digest of local file using digest_from_file().
+ """ Return MD5 hex digest of local file using digest_from_file().
Do not use this function unless you have no other choice for:
1) Optional backwards compatibility
@@ -1514,21 +1514,21 @@ class AnsibleModule(object):
This function will not work on systems complying with FIPS-140-2.
Most uses of this function can use the module.sha1 function instead.
- '''
+ """
if 'md5' not in AVAILABLE_HASH_ALGORITHMS:
raise ValueError('MD5 not available. Possibly running in FIPS mode')
return self.digest_from_file(filename, 'md5')
def sha1(self, filename):
- ''' Return SHA1 hex digest of local file using digest_from_file(). '''
+ """ Return SHA1 hex digest of local file using digest_from_file(). """
return self.digest_from_file(filename, 'sha1')
def sha256(self, filename):
- ''' Return SHA-256 hex digest of local file using digest_from_file(). '''
+ """ Return SHA-256 hex digest of local file using digest_from_file(). """
return self.digest_from_file(filename, 'sha256')
def backup_local(self, fn):
- '''make a date-marked backup of the specified file, return True or False on success or failure'''
+ """make a date-marked backup of the specified file, return True or False on success or failure"""
backupdest = ''
if os.path.exists(fn):
@@ -1586,9 +1586,9 @@ class AnsibleModule(object):
self.set_attributes_if_different(dest, current_attribs, True)
def atomic_move(self, src, dest, unsafe_writes=False, keep_dest_attrs=True):
- '''atomically move src to dest, copying attributes from dest, returns true on success
+ """atomically move src to dest, copying attributes from dest, returns true on success
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
- to work around limitations, corner cases and ensure selinux context is saved if possible'''
+ to work around limitations, corner cases and ensure selinux context is saved if possible"""
context = None
dest_stat = None
b_src = to_bytes(src, errors='surrogate_or_strict')
@@ -1756,7 +1756,7 @@ class AnsibleModule(object):
def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None,
use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict',
expand_user_and_vars=True, pass_fds=None, before_communicate_callback=None, ignore_invalid_cwd=True, handle_exceptions=True):
- '''
+ """
Execute a command, returns rc, stdout, and stderr.
The mechanism of this method for reading stdout and stderr differs from
@@ -1825,7 +1825,7 @@ class AnsibleModule(object):
byte strings. On python3, stdout and stderr are text strings converted
according to the encoding and errors parameters. If you want byte
strings on python3, use encoding=None to turn decoding to text off.
- '''
+ """
# used by clean args later on
self._clean = None
diff --git a/lib/ansible/module_utils/common/_utils.py b/lib/ansible/module_utils/common/_utils.py
index 8323e7c643..deab1fcdf9 100644
--- a/lib/ansible/module_utils/common/_utils.py
+++ b/lib/ansible/module_utils/common/_utils.py
@@ -10,7 +10,7 @@ from __future__ import annotations
def get_all_subclasses(cls):
- '''
+ """
Recursively search and find all subclasses of a given class
:arg cls: A python class
@@ -21,7 +21,7 @@ def get_all_subclasses(cls):
of a class exist. However, `__subclasses__` only goes one level deep. This function searches
each child class's `__subclasses__` method to find all of the descendent classes. It then
returns an iterable of the descendent classes.
- '''
+ """
# Retrieve direct subclasses
subclasses = set(cls.__subclasses__())
to_visit = list(subclasses)
diff --git a/lib/ansible/module_utils/common/dict_transformations.py b/lib/ansible/module_utils/common/dict_transformations.py
index 9c59d4ade4..8d318f5ef6 100644
--- a/lib/ansible/module_utils/common/dict_transformations.py
+++ b/lib/ansible/module_utils/common/dict_transformations.py
@@ -109,9 +109,9 @@ def _camel_to_snake(name, reversible=False):
def dict_merge(a, b):
- '''recursively merges dicts. not just simple a['key'] = b['key'], if
+ """recursively merges dicts. not just simple a['key'] = b['key'], if
both a and b have a key whose value is a dict then dict_merge is called
- on both values and the result stored in the returned dictionary.'''
+ on both values and the result stored in the returned dictionary."""
if not isinstance(b, dict):
return b
result = deepcopy(a)
diff --git a/lib/ansible/module_utils/common/file.py b/lib/ansible/module_utils/common/file.py
index 1b976fd932..4c54b18411 100644
--- a/lib/ansible/module_utils/common/file.py
+++ b/lib/ansible/module_utils/common/file.py
@@ -55,7 +55,7 @@ def is_executable(path):
# This method is reused by the basic module,
# the repetition helps the basic module's html documentation come out right.
# http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_docstring_signature
- '''is_executable(path)
+ """is_executable(path)
is the given path executable?
@@ -66,7 +66,7 @@ def is_executable(path):
* Does not account for FSACLs.
* Most times we really want to know "Can the current user execute this
file". This function does not tell us that, only if any execute bit is set.
- '''
+ """
# These are all bitfields so first bitwise-or all the permissions we're
# looking for, then bitwise-and with the file's mode to determine if any
# execute bits are set.
diff --git a/lib/ansible/module_utils/common/json.py b/lib/ansible/module_utils/common/json.py
index 8038552e0a..fe65a8d701 100644
--- a/lib/ansible/module_utils/common/json.py
+++ b/lib/ansible/module_utils/common/json.py
@@ -42,9 +42,9 @@ def json_dump(structure):
class AnsibleJSONEncoder(json.JSONEncoder):
- '''
+ """
Simple encoder class to deal with JSON encoding of Ansible internal types
- '''
+ """
def __init__(self, preprocess_unsafe=False, vault_to_text=False, **kwargs):
self._preprocess_unsafe = preprocess_unsafe
diff --git a/lib/ansible/module_utils/common/locale.py b/lib/ansible/module_utils/common/locale.py
index 57b27a26eb..872931ced1 100644
--- a/lib/ansible/module_utils/common/locale.py
+++ b/lib/ansible/module_utils/common/locale.py
@@ -7,7 +7,7 @@ from ansible.module_utils.common.text.converters import to_native
def get_best_parsable_locale(module, preferences=None, raise_on_locale=False):
- '''
+ """
Attempts to return the best possible locale for parsing output in English
useful for scraping output with i18n tools. When this raises an exception
and the caller wants to continue, it should use the 'C' locale.
@@ -17,7 +17,7 @@ def get_best_parsable_locale(module, preferences=None, raise_on_locale=False):
:param raise_on_locale: boolean that determines if we raise exception or not
due to locale CLI issues
:returns: The first matched preferred locale or 'C' which is the default
- '''
+ """
found = 'C' # default posix, its ascii but always there
try:
diff --git a/lib/ansible/module_utils/common/process.py b/lib/ansible/module_utils/common/process.py
index 85ffd2195e..eb11f8e44d 100644
--- a/lib/ansible/module_utils/common/process.py
+++ b/lib/ansible/module_utils/common/process.py
@@ -10,7 +10,7 @@ from ansible.module_utils.common.warnings import deprecate
def get_bin_path(arg, opt_dirs=None, required=None):
- '''
+ """
Find system executable in PATH. Raises ValueError if the executable is not found.
:param arg: the executable to find
@@ -24,7 +24,7 @@ def get_bin_path(arg, opt_dirs=None, required=None):
In addition to PATH and opt_dirs, this function also looks through /sbin, /usr/sbin and /usr/local/sbin. A lot of
modules, especially for gathering facts, depend on this behaviour.
- '''
+ """
if required is not None:
deprecate(
msg="The `required` parameter in `get_bin_path` API is deprecated.",
diff --git a/lib/ansible/module_utils/common/respawn.py b/lib/ansible/module_utils/common/respawn.py
index 0f57c15457..ef44339aef 100644
--- a/lib/ansible/module_utils/common/respawn.py
+++ b/lib/ansible/module_utils/common/respawn.py
@@ -74,7 +74,7 @@ def _create_payload():
raise Exception('unable to access ansible.module_utils.basic._ANSIBLE_ARGS (not launched by AnsiballZ?)')
module_fqn = sys.modules['__main__']._module_fqn
modlib_path = sys.modules['__main__']._modlib_path
- respawn_code_template = '''
+ respawn_code_template = """
import runpy
import sys
@@ -89,7 +89,7 @@ if __name__ == '__main__':
basic._ANSIBLE_ARGS = smuggled_args
runpy.run_module(module_fqn, init_globals=dict(_respawned=True), run_name='__main__', alter_sys=True)
- '''
+ """
respawn_code = respawn_code_template.format(module_fqn=module_fqn, modlib_path=modlib_path, smuggled_args=smuggled_args.strip())
diff --git a/lib/ansible/module_utils/common/sys_info.py b/lib/ansible/module_utils/common/sys_info.py
index 6ca451016f..98dc3d631a 100644
--- a/lib/ansible/module_utils/common/sys_info.py
+++ b/lib/ansible/module_utils/common/sys_info.py
@@ -14,7 +14,7 @@ __all__ = ('get_distribution', 'get_distribution_version', 'get_platform_subclas
def get_distribution():
- '''
+ """
Return the name of the distribution the module is running on.
:rtype: NativeString or None
@@ -23,7 +23,7 @@ def get_distribution():
This function attempts to determine what distribution the code is running
on and return a string representing that value. If the platform is Linux
and the distribution cannot be determined, it returns ``OtherLinux``.
- '''
+ """
distribution = distro.id().capitalize()
if platform.system() == 'Linux':
@@ -38,14 +38,14 @@ def get_distribution():
def get_distribution_version():
- '''
+ """
Get the version of the distribution the code is running on
:rtype: NativeString or None
:returns: A string representation of the version of the distribution. If it
cannot determine the version, it returns an empty string. If this is not run on
a Linux machine it returns None.
- '''
+ """
version = None
needs_best_version = frozenset((
@@ -79,12 +79,12 @@ def get_distribution_version():
def get_distribution_codename():
- '''
+ """
Return the code name for this Linux Distribution
:rtype: NativeString or None
:returns: A string representation of the distribution's codename or None if not a Linux distro
- '''
+ """
codename = None
if platform.system() == 'Linux':
# Until this gets merged and we update our bundled copy of distro:
@@ -109,7 +109,7 @@ def get_distribution_codename():
def get_platform_subclass(cls):
- '''
+ """
Finds a subclass implementing desired functionality on the platform the code is running on
:arg cls: Class to find an appropriate subclass for
@@ -135,7 +135,7 @@ def get_platform_subclass(cls):
def __new__(cls, *args, **kwargs):
new_cls = get_platform_subclass(User)
return super(cls, new_cls).__new__(new_cls)
- '''
+ """
this_platform = platform.system()
distribution = get_distribution()
diff --git a/lib/ansible/module_utils/common/text/converters.py b/lib/ansible/module_utils/common/text/converters.py
index abef32d06d..6bfa8470b6 100644
--- a/lib/ansible/module_utils/common/text/converters.py
+++ b/lib/ansible/module_utils/common/text/converters.py
@@ -278,11 +278,11 @@ def jsonify(data, **kwargs):
def container_to_bytes(d, encoding='utf-8', errors='surrogate_or_strict'):
- ''' Recursively convert dict keys and values to byte str
+ """ Recursively convert dict keys and values to byte str
Specialized for json return because this only handles, lists, tuples,
and dict container types (the containers that the json module returns)
- '''
+ """
if isinstance(d, text_type):
return to_bytes(d, encoding=encoding, errors=errors)
diff --git a/lib/ansible/module_utils/distro/__init__.py b/lib/ansible/module_utils/distro/__init__.py
index 8af439005f..6cdb84ae50 100644
--- a/lib/ansible/module_utils/distro/__init__.py
+++ b/lib/ansible/module_utils/distro/__init__.py
@@ -16,9 +16,9 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
-'''
+"""
Compat distro library.
-'''
+"""
from __future__ import annotations
# The following makes it easier for us to script updates of the bundled code
diff --git a/lib/ansible/module_utils/facts/ansible_collector.py b/lib/ansible/module_utils/facts/ansible_collector.py
index ac81d1fd64..9fe1c8a84e 100644
--- a/lib/ansible/module_utils/facts/ansible_collector.py
+++ b/lib/ansible/module_utils/facts/ansible_collector.py
@@ -39,13 +39,13 @@ from ansible.module_utils.common.collections import is_string
class AnsibleFactCollector(collector.BaseFactCollector):
- '''A FactCollector that returns results under 'ansible_facts' top level key.
+ """A FactCollector that returns results under 'ansible_facts' top level key.
If a namespace if provided, facts will be collected under that namespace.
For ex, a ansible.module_utils.facts.namespace.PrefixFactNamespace(prefix='ansible_')
Has a 'from_gather_subset() constructor that populates collectors based on a
- gather_subset specifier.'''
+ gather_subset specifier."""
def __init__(self, collectors=None, namespace=None, filter_spec=None):
@@ -102,7 +102,7 @@ class AnsibleFactCollector(collector.BaseFactCollector):
class CollectorMetaDataCollector(collector.BaseFactCollector):
- '''Collector that provides a facts with the gather_subset metadata.'''
+ """Collector that provides a facts with the gather_subset metadata."""
name = 'gather_subset'
_fact_ids = set() # type: t.Set[str]
diff --git a/lib/ansible/module_utils/facts/collector.py b/lib/ansible/module_utils/facts/collector.py
index 0983df7aad..f3e144f7dd 100644
--- a/lib/ansible/module_utils/facts/collector.py
+++ b/lib/ansible/module_utils/facts/collector.py
@@ -38,13 +38,13 @@ from ansible.module_utils.facts import timeout
class CycleFoundInFactDeps(Exception):
- '''Indicates there is a cycle in fact collector deps
+ """Indicates there is a cycle in fact collector deps
If collector-B requires collector-A, and collector-A requires
collector-B, that is a cycle. In that case, there is no ordering
that will satisfy B before A and A and before B. That will cause this
error to be raised.
- '''
+ """
pass
@@ -64,9 +64,9 @@ class BaseFactCollector:
required_facts = set() # type: t.Set[str]
def __init__(self, collectors=None, namespace=None):
- '''Base class for things that collect facts.
+ """Base class for things that collect facts.
- 'collectors' is an optional list of other FactCollectors for composing.'''
+ 'collectors' is an optional list of other FactCollectors for composing."""
self.collectors = collectors or []
# self.namespace is a object with a 'transform' method that transforms
@@ -88,7 +88,7 @@ class BaseFactCollector:
return key_name
def _transform_dict_keys(self, fact_dict):
- '''update a dicts keys to use new names as transformed by self._transform_name'''
+ """update a dicts keys to use new names as transformed by self._transform_name"""
if fact_dict is None:
return {}
@@ -107,7 +107,7 @@ class BaseFactCollector:
return facts_dict
def collect(self, module=None, collected_facts=None):
- '''do the fact collection
+ """do the fact collection
'collected_facts' is a object (a dict, likely) that holds all previously
facts. This is intended to be used if a FactCollector needs to reference
@@ -115,7 +115,7 @@ class BaseFactCollector:
Returns a dict of facts.
- '''
+ """
facts_dict = {}
return facts_dict
@@ -125,12 +125,12 @@ def get_collector_names(valid_subsets=None,
gather_subset=None,
aliases_map=None,
platform_info=None):
- '''return a set of FactCollector names based on gather_subset spec.
+ """return a set of FactCollector names based on gather_subset spec.
gather_subset is a spec describing which facts to gather.
valid_subsets is a frozenset of potential matches for gather_subset ('all', 'network') etc
minimal_gather_subsets is a frozenset of matches to always use, even for gather_subset='!all'
- '''
+ """
# Retrieve module parameters
gather_subset = gather_subset or ['all']
@@ -267,11 +267,11 @@ def _get_requires_by_collector_name(collector_name, all_fact_subsets):
def find_unresolved_requires(collector_names, all_fact_subsets):
- '''Find any collector names that have unresolved requires
+ """Find any collector names that have unresolved requires
Returns a list of collector names that correspond to collector
classes whose .requires_facts() are not in collector_names.
- '''
+ """
unresolved = set()
for collector_name in collector_names:
@@ -351,7 +351,7 @@ def collector_classes_from_gather_subset(all_collector_classes=None,
gather_subset=None,
gather_timeout=None,
platform_info=None):
- '''return a list of collector classes that match the args'''
+ """return a list of collector classes that match the args"""
# use gather_name etc to get the list of collectors
diff --git a/lib/ansible/module_utils/facts/compat.py b/lib/ansible/module_utils/facts/compat.py
index 38953140d8..7d389cbc44 100644
--- a/lib/ansible/module_utils/facts/compat.py
+++ b/lib/ansible/module_utils/facts/compat.py
@@ -34,19 +34,19 @@ from ansible.module_utils.facts import ansible_collector
def get_all_facts(module):
- '''compat api for ansible 2.2/2.3 module_utils.facts.get_all_facts method
+ """compat api for ansible 2.2/2.3 module_utils.facts.get_all_facts method
Expects module to be an instance of AnsibleModule, with a 'gather_subset' param.
returns a dict mapping the bare fact name ('default_ipv4' with no 'ansible_' namespace) to
- the fact value.'''
+ the fact value."""
gather_subset = module.params['gather_subset']
return ansible_facts(module, gather_subset=gather_subset)
def ansible_facts(module, gather_subset=None):
- '''Compat api for ansible 2.0/2.2/2.3 module_utils.facts.ansible_facts method
+ """Compat api for ansible 2.0/2.2/2.3 module_utils.facts.ansible_facts method
2.3/2.3 expects a gather_subset arg.
2.0/2.1 does not except a gather_subset arg
@@ -57,7 +57,7 @@ def ansible_facts(module, gather_subset=None):
returns a dict mapping the bare fact name ('default_ipv4' with no 'ansible_' namespace) to
the fact value.
- '''
+ """
gather_subset = gather_subset or module.params.get('gather_subset', ['all'])
gather_timeout = module.params.get('gather_timeout', 10)
diff --git a/lib/ansible/module_utils/facts/hardware/freebsd.py b/lib/ansible/module_utils/facts/hardware/freebsd.py
index c7f6c6c48b..2ae5223963 100644
--- a/lib/ansible/module_utils/facts/hardware/freebsd.py
+++ b/lib/ansible/module_utils/facts/hardware/freebsd.py
@@ -224,9 +224,9 @@ class FreeBSDHardware(Hardware):
return device_facts
def get_dmi_facts(self):
- ''' learn dmi facts from system
+ """ learn dmi facts from system
- Use dmidecode executable if available'''
+ Use dmidecode executable if available"""
dmi_facts = {}
diff --git a/lib/ansible/module_utils/facts/hardware/linux.py b/lib/ansible/module_utils/facts/hardware/linux.py
index 293c75a250..f431c4e1f8 100644
--- a/lib/ansible/module_utils/facts/hardware/linux.py
+++ b/lib/ansible/module_utils/facts/hardware/linux.py
@@ -311,10 +311,10 @@ class LinuxHardware(Hardware):
return cpu_facts
def get_dmi_facts(self):
- ''' learn dmi facts from system
+ """ learn dmi facts from system
Try /sys first for dmi related facts.
- If that is not available, fall back to dmidecode executable '''
+ If that is not available, fall back to dmidecode executable """
dmi_facts = {}
@@ -423,13 +423,13 @@ class LinuxHardware(Hardware):
'NA'
)
sysinfo_re = re.compile(
- r'''
+ r"""
^
(?:Manufacturer:\s+(?P<system_vendor>.+))|
(?:Type:\s+(?P<product_name>.+))|
(?:Sequence\ Code:\s+0+(?P<product_serial>.+))
$
- ''',
+ """,
re.VERBOSE | re.MULTILINE
)
data = get_file_content('/proc/sysinfo')
diff --git a/lib/ansible/module_utils/facts/namespace.py b/lib/ansible/module_utils/facts/namespace.py
index 3d0eb25353..af195b21a1 100644
--- a/lib/ansible/module_utils/facts/namespace.py
+++ b/lib/ansible/module_utils/facts/namespace.py
@@ -33,7 +33,7 @@ class FactNamespace:
self.namespace_name = namespace_name
def transform(self, name):
- '''Take a text name, and transforms it as needed (add a namespace prefix, etc)'''
+ """Take a text name, and transforms it as needed (add a namespace prefix, etc)"""
return name
def _underscore(self, name):
diff --git a/lib/ansible/module_utils/facts/other/ohai.py b/lib/ansible/module_utils/facts/other/ohai.py
index 8f0e4dcaec..db62fe4d73 100644
--- a/lib/ansible/module_utils/facts/other/ohai.py
+++ b/lib/ansible/module_utils/facts/other/ohai.py
@@ -25,7 +25,7 @@ from ansible.module_utils.facts.collector import BaseFactCollector
class OhaiFactCollector(BaseFactCollector):
- '''This is a subclass of Facts for including information gathered from Ohai.'''
+ """This is a subclass of Facts for including information gathered from Ohai."""
name = 'ohai'
_fact_ids = set() # type: t.Set[str]
diff --git a/lib/ansible/module_utils/facts/system/distribution.py b/lib/ansible/module_utils/facts/system/distribution.py
index 7554ef1ae3..66c768a126 100644
--- a/lib/ansible/module_utils/facts/system/distribution.py
+++ b/lib/ansible/module_utils/facts/system/distribution.py
@@ -46,7 +46,7 @@ def _file_exists(path, allow_empty=False):
class DistributionFiles:
- '''has-a various distro file parsers (os-release, etc) and logic for finding the right one.'''
+ """has-a various distro file parsers (os-release, etc) and logic for finding the right one."""
# every distribution name mentioned here, must have one of
# - allowempty == True
# - be listed in SEARCH_STRING
diff --git a/lib/ansible/module_utils/facts/utils.py b/lib/ansible/module_utils/facts/utils.py
index f7f6f19cec..9131cd1c96 100644
--- a/lib/ansible/module_utils/facts/utils.py
+++ b/lib/ansible/module_utils/facts/utils.py
@@ -20,7 +20,7 @@ import os
def get_file_content(path, default=None, strip=True):
- '''
+ """
Return the contents of a given file path
:args path: path to file to return contents from
@@ -28,7 +28,7 @@ def get_file_content(path, default=None, strip=True):
:args strip: controls if we strip whitespace from the result or not
:returns: String with file contents (optionally stripped) or 'default' value
- '''
+ """
data = default
if os.path.exists(path) and os.access(path, os.R_OK):
datafile = None
@@ -62,7 +62,7 @@ def get_file_content(path, default=None, strip=True):
def get_file_lines(path, strip=True, line_sep=None):
- '''get list of lines from file'''
+ """get list of lines from file"""
data = get_file_content(path, strip=strip)
if data:
if line_sep is None:
diff --git a/lib/ansible/module_utils/json_utils.py b/lib/ansible/module_utils/json_utils.py
index c6d4c7642d..01fd2661d7 100644
--- a/lib/ansible/module_utils/json_utils.py
+++ b/lib/ansible/module_utils/json_utils.py
@@ -32,13 +32,13 @@ import json # pylint: disable=unused-import
# NB: a copy of this function exists in ../../modules/core/async_wrapper.py. Ensure any
# changes are propagated there.
def _filter_non_json_lines(data, objects_only=False):
- '''
+ """
Used to filter unrelated output around module JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
Filters leading lines before first line-starting occurrence of '{' or '[', and filter all
trailing lines after matching close character (working from the bottom of output).
- '''
+ """
warnings = []
# Filter initial junk
diff --git a/lib/ansible/module_utils/service.py b/lib/ansible/module_utils/service.py
index 3910ea0174..d98c56e913 100644
--- a/lib/ansible/module_utils/service.py
+++ b/lib/ansible/module_utils/service.py
@@ -42,13 +42,13 @@ from ansible.module_utils.common.text.converters import to_bytes, to_text
def sysv_is_enabled(name, runlevel=None):
- '''
+ """
This function will check if the service name supplied
is enabled in any of the sysv runlevels
:arg name: name of the service to test for
:kw runlevel: runlevel to check (default: None)
- '''
+ """
if runlevel:
if not os.path.isdir('/etc/rc0.d/'):
return bool(glob.glob('/etc/init.d/rc%s.d/S??%s' % (runlevel, name)))
@@ -60,12 +60,12 @@ def sysv_is_enabled(name, runlevel=None):
def get_sysv_script(name):
- '''
+ """
This function will return the expected path for an init script
corresponding to the service name supplied.
:arg name: name or path of the service to test for
- '''
+ """
if name.startswith('/'):
result = name
else:
@@ -75,19 +75,19 @@ def get_sysv_script(name):
def sysv_exists(name):
- '''
+ """
This function will return True or False depending on
the existence of an init script corresponding to the service name supplied.
:arg name: name of the service to test for
- '''
+ """
return os.path.exists(get_sysv_script(name))
def get_ps(module, pattern):
- '''
+ """
Last resort to find a service by trying to match pattern to programs in memory
- '''
+ """
found = False
if platform.system() == 'SunOS':
flags = '-ef'
@@ -106,7 +106,7 @@ def get_ps(module, pattern):
def fail_if_missing(module, found, service, msg=''):
- '''
+ """
This function will return an error or exit gracefully depending on check mode status
and if the service is missing or not.
@@ -114,16 +114,16 @@ def fail_if_missing(module, found, service, msg=''):
:arg found: boolean indicating if services were found or not
:arg service: name of service
:kw msg: extra info to append to error/success msg when missing
- '''
+ """
if not found:
module.fail_json(msg='Could not find the requested service %s: %s' % (service, msg))
def fork_process():
- '''
+ """
This function performs the double fork process to detach from the
parent process and execute.
- '''
+ """
pid = os.fork()
if pid == 0:
@@ -162,7 +162,7 @@ def fork_process():
def daemonize(module, cmd):
- '''
+ """
Execute a command while detaching as a daemon, returns rc, stdout, and stderr.
:arg module: is an AnsibleModule object, used for it's utility methods
@@ -171,7 +171,7 @@ def daemonize(module, cmd):
This is complex because daemonization is hard for people.
What we do is daemonize a part of this module, the daemon runs the command,
picks up the return code and output, and returns it to the main process.
- '''
+ """
# init some vars
chunk = 4096 # FIXME: pass in as arg?
diff --git a/lib/ansible/module_utils/splitter.py b/lib/ansible/module_utils/splitter.py
index e2a3da5054..5ae3393fd6 100644
--- a/lib/ansible/module_utils/splitter.py
+++ b/lib/ansible/module_utils/splitter.py
@@ -30,10 +30,10 @@ from __future__ import annotations
def _get_quote_state(token, quote_char):
- '''
+ """
the goal of this block is to determine if the quoted string
is unterminated in which case it needs to be put back together
- '''
+ """
# the char before the current one, used to see if
# the current character is escaped
prev_char = None
@@ -50,11 +50,11 @@ def _get_quote_state(token, quote_char):
def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
- '''
+ """
this function counts the number of opening/closing blocks for a
given opening/closing type and adjusts the current depth for that
block based on the difference
- '''
+ """
num_open = token.count(open_token)
num_close = token.count(close_token)
if num_open != num_close:
@@ -65,7 +65,7 @@ def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
def split_args(args):
- '''
+ """
Splits args on whitespace, but intelligently reassembles
those that may have been split over a jinja2 block or quotes.
@@ -78,7 +78,7 @@ def split_args(args):
Basically this is a variation shlex that has some more intelligence for
how Ansible needs to use it.
- '''
+ """
# the list of params parsed out of the arg string
# this is going to be the result value when we are done
@@ -212,7 +212,7 @@ def is_quoted(data):
def unquote(data):
- ''' removes first and last quotes from a string, if the string starts and ends with the same quotes '''
+ """ removes first and last quotes from a string, if the string starts and ends with the same quotes """
if is_quoted(data):
return data[1:-1]
return data
diff --git a/lib/ansible/module_utils/urls.py b/lib/ansible/module_utils/urls.py
index b3047f0164..c90f0b78fd 100644
--- a/lib/ansible/module_utils/urls.py
+++ b/lib/ansible/module_utils/urls.py
@@ -12,7 +12,7 @@
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
-'''
+"""
The **urls** utils module offers a replacement for the urllib python library.
urllib is the python stdlib way to retrieve files from the Internet but it
@@ -25,7 +25,7 @@ to replace urllib with a more secure library. However, all third party libraries
require that the library be installed on the managed machine. That is an extra step
for users making use of a module. If possible, avoid third party libraries by using
this code instead.
-'''
+"""
from __future__ import annotations
@@ -223,10 +223,10 @@ UnixHTTPSConnection = None
if HAS_SSL:
@contextmanager
def unix_socket_patch_httpconnection_connect():
- '''Monkey patch ``http.client.HTTPConnection.connect`` to be ``UnixHTTPConnection.connect``
+ """Monkey patch ``http.client.HTTPConnection.connect`` to be ``UnixHTTPConnection.connect``
so that when calling ``super(UnixHTTPSConnection, self).connect()`` we get the
correct behavior of creating self.sock for the unix socket
- '''
+ """
_connect = http.client.HTTPConnection.connect
http.client.HTTPConnection.connect = UnixHTTPConnection.connect
yield
@@ -270,7 +270,7 @@ if HAS_SSL:
class UnixHTTPConnection(http.client.HTTPConnection):
- '''Handles http requests to a unix socket file'''
+ """Handles http requests to a unix socket file"""
def __init__(self, unix_socket):
self._unix_socket = unix_socket
@@ -290,7 +290,7 @@ class UnixHTTPConnection(http.client.HTTPConnection):
class UnixHTTPHandler(urllib.request.HTTPHandler):
- '''Handler for Unix urls'''
+ """Handler for Unix urls"""
def __init__(self, unix_socket, **kwargs):
super().__init__(**kwargs)
@@ -301,29 +301,29 @@ class UnixHTTPHandler(urllib.request.HTTPHandler):
class ParseResultDottedDict(dict):
- '''
+ """
A dict that acts similarly to the ParseResult named tuple from urllib
- '''
+ """
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__dict__ = self
def as_list(self):
- '''
+ """
Generate a list from this dict, that looks like the ParseResult named tuple
- '''
+ """
return [self.get(k, None) for k in ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')]
def generic_urlparse(parts):
- '''
+ """
Returns a dictionary of url parts as parsed by urlparse,
but accounts for the fact that older versions of that
library do not support named attributes (ie. .netloc)
This method isn't of much use any longer, but is kept
in a minimal state for backwards compat.
- '''
+ """
result = ParseResultDottedDict(parts._asdict())
result.update({
'username': parts.username,
@@ -989,11 +989,11 @@ def open_url(url, data=None, headers=None, method=None, use_proxy=True,
client_cert=None, client_key=None, cookies=None,
use_gssapi=False, unix_socket=None, ca_path=None,
unredirected_headers=None, decompress=True, ciphers=None, use_netrc=True):
- '''
+ """
Sends a request via HTTP(S) or FTP using urllib (Python3)
Does not require the module environment
- '''
+ """
method = method or ('POST' if data else 'GET')
return Request().open(method, url, data=data, headers=headers, use_proxy=use_proxy,
force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
@@ -1117,10 +1117,10 @@ def basic_auth_header(username, password):
def url_argument_spec():
- '''
+ """
Creates an argument spec that can be used with any module
that will be requesting content via urllib/urllib2
- '''
+ """
return dict(
url=dict(type='str'),
force=dict(type='bool', default=False),
@@ -1333,7 +1333,7 @@ def _split_multiext(name, min=3, max=4, count=2):
def fetch_file(module, url, data=None, headers=None, method=None,
use_proxy=True, force=False, last_mod_time=None, timeout=10,
unredirected_headers=None, decompress=True, ciphers=None):
- '''Download and save a file via HTTP(S) or FTP (needs the module as parameter).
+ """Download and save a file via HTTP(S) or FTP (needs the module as parameter).
This is basically a wrapper around fetch_url().
:arg module: The AnsibleModule (used to get username, password etc. (s.b.).
@@ -1351,7 +1351,7 @@ def fetch_file(module, url, data=None, headers=None, method=None,
:kwarg ciphers: (optional) List of ciphers to use
:returns: A string, the path to the downloaded file.
- '''
+ """
# download file
bufsize = 65536
parts = urlparse(url)
diff --git a/lib/ansible/modules/add_host.py b/lib/ansible/modules/add_host.py
index 81930eab7d..80a2d0aef8 100644
--- a/lib/ansible/modules/add_host.py
+++ b/lib/ansible/modules/add_host.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: add_host
short_description: Add a host (and alternatively a group) to the ansible-playbook in-memory inventory
@@ -69,9 +69,9 @@ seealso:
author:
- Ansible Core Team
- Seth Vidal (@skvidal)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Add host to group 'just_created' with variable foo=42
ansible.builtin.add_host:
name: '{{ ip_from_ec2 }}'
@@ -111,4 +111,4 @@ EXAMPLES = r'''
name: '{{ item }}'
groups: done
loop: "{{ ansible_play_hosts }}"
-'''
+"""
diff --git a/lib/ansible/modules/apt.py b/lib/ansible/modules/apt.py
index 70a2a07cc0..266165f22a 100644
--- a/lib/ansible/modules/apt.py
+++ b/lib/ansible/modules/apt.py
@@ -9,7 +9,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: apt
short_description: Manages apt-packages
@@ -217,9 +217,9 @@ notes:
- If the interpreter can't import C(python-apt)/C(python3-apt) the module will check for it in system-owned interpreters as well.
If the dependency can't be found, the module will attempt to install it.
If the dependency is found or installed, the module will be respawned under the correct interpreter.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Install apache httpd (state=present is optional)
ansible.builtin.apt:
name: apache2
@@ -327,9 +327,9 @@ EXAMPLES = '''
- name: Run the equivalent of "apt-get clean" as a separate step
ansible.builtin.apt:
clean: yes
-'''
+"""
-RETURN = '''
+RETURN = """
cache_updated:
description: if the cache was updated or not
returned: success, in some cases
@@ -355,7 +355,7 @@ stderr:
returned: success, when needed
type: str
sample: "AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to ..."
-''' # NOQA
+""" # NOQA
# added to stave off future warnings about apt api
import warnings
@@ -1184,7 +1184,7 @@ def get_updated_cache_time():
# https://github.com/ansible/ansible-modules-core/issues/2951
def get_cache(module):
- '''Attempt to get the cache object and update till it works'''
+ """Attempt to get the cache object and update till it works"""
cache = None
try:
cache = apt.Cache()
diff --git a/lib/ansible/modules/apt_key.py b/lib/ansible/modules/apt_key.py
index ec86e829ba..3828f9a882 100644
--- a/lib/ansible/modules/apt_key.py
+++ b/lib/ansible/modules/apt_key.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: apt_key
author:
@@ -79,9 +79,9 @@ options:
on personally controlled sites using self-signed certificates.
type: bool
default: 'yes'
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: One way to avoid apt_key once it is removed from your distro, armored keys should use .asc extension, binary should use .gpg
block:
- name: somerepo | no apt key
@@ -133,9 +133,9 @@ EXAMPLES = '''
id: 9FED2BCBDCD29CDF762678CBAED4B06F473041FA
file: /tmp/apt.gpg
state: present
-'''
+"""
-RETURN = '''
+RETURN = """
after:
description: List of apt key ids or fingerprints after any modification
returned: on change
@@ -166,7 +166,7 @@ short_id:
returned: always
type: str
sample: "A88D21E9"
-'''
+"""
import os
diff --git a/lib/ansible/modules/apt_repository.py b/lib/ansible/modules/apt_repository.py
index 3fb027c0c3..b17801f5f8 100644
--- a/lib/ansible/modules/apt_repository.py
+++ b/lib/ansible/modules/apt_repository.py
@@ -9,7 +9,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: apt_repository
short_description: Add and remove APT repositories
@@ -101,9 +101,9 @@ requirements:
- python-apt (python 2)
- python3-apt (python 3)
- apt-key or gpg
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Add specified repository into sources list
ansible.builtin.apt_repository:
repo: deb http://archive.canonical.com/ubuntu hardy partner
@@ -145,9 +145,9 @@ EXAMPLES = '''
ansible.builtin.apt_repository:
repo: "deb [arch=amd64 signed-by=/etc/apt/keyrings/myrepo.asc] https://download.example.com/linux/ubuntu {{ ansible_distribution_release }} stable"
state: present
-'''
+"""
-RETURN = '''
+RETURN = """
repo:
description: A source string for the repository
returned: always
@@ -167,7 +167,7 @@ sources_removed:
type: list
sample: ["/etc/apt/sources.list.d/artifacts_elastic_co_packages_6_x_apt.list"]
version_added: "2.15"
-'''
+"""
import copy
import glob
@@ -245,7 +245,7 @@ class SourcesList(object):
self.load(file)
def __iter__(self):
- '''Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped.'''
+ """Simple iterator to go over all sources. Empty, non-source, and other not valid lines will be skipped."""
for file, sources in self.files.items():
for n, valid, enabled, source, comment in sources:
if valid:
@@ -315,9 +315,9 @@ class SourcesList(object):
@staticmethod
def _apt_cfg_file(filespec):
- '''
+ """
Wrapper for `apt_pkg` module for running with Python 2.5
- '''
+ """
try:
result = apt_pkg.config.find_file(filespec)
except AttributeError:
@@ -326,9 +326,9 @@ class SourcesList(object):
@staticmethod
def _apt_cfg_dir(dirspec):
- '''
+ """
Wrapper for `apt_pkg` module for running with Python 2.5
- '''
+ """
try:
result = apt_pkg.config.find_dir(dirspec)
except AttributeError:
@@ -413,10 +413,10 @@ class SourcesList(object):
return new
def modify(self, file, n, enabled=None, source=None, comment=None):
- '''
+ """
This function to be used with iterator, so we don't care of invalid sources.
If source, enabled, or comment is None, original value from line ``n`` will be preserved.
- '''
+ """
valid, enabled_old, source_old, comment_old = self.files[file][n][1:]
self.files[file][n] = (n, valid, self._choice(enabled, enabled_old), self._choice(source, source_old), self._choice(comment, comment_old))
@@ -616,7 +616,7 @@ class UbuntuSourcesList(SourcesList):
def revert_sources_list(sources_before, sources_after, sourceslist_before):
- '''Revert the sourcelist files to their previous state.'''
+ """Revert the sourcelist files to their previous state."""
# First remove any new files that were created:
for filename in set(sources_after.keys()).difference(sources_before.keys()):
diff --git a/lib/ansible/modules/assemble.py b/lib/ansible/modules/assemble.py
index bd8ddf6cff..ff570aee1b 100644
--- a/lib/ansible/modules/assemble.py
+++ b/lib/ansible/modules/assemble.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: assemble
short_description: Assemble configuration files from fragments
@@ -102,9 +102,9 @@ extends_documentation_fragment:
- action_common_attributes.files
- decrypt
- files
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Assemble from fragments from a directory
ansible.builtin.assemble:
src: /etc/someapp/fragments
@@ -121,9 +121,9 @@ EXAMPLES = r'''
src: /etc/ssh/conf.d/
dest: /etc/ssh/sshd_config
validate: /usr/sbin/sshd -t -f %s
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import codecs
import os
@@ -136,7 +136,7 @@ from ansible.module_utils.common.text.converters import to_native
def assemble_from_fragments(src_path, delimiter=None, compiled_regexp=None, ignore_hidden=False, tmpdir=None):
- ''' assemble a file from a directory of fragments '''
+ """ assemble a file from a directory of fragments """
tmpfd, temp_path = tempfile.mkstemp(dir=tmpdir)
tmp = os.fdopen(tmpfd, 'wb')
delimit_me = False
diff --git a/lib/ansible/modules/assert.py b/lib/ansible/modules/assert.py
index af758a53c5..90eeacb305 100644
--- a/lib/ansible/modules/assert.py
+++ b/lib/ansible/modules/assert.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: assert
short_description: Asserts given expressions are true
@@ -70,9 +70,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: A single condition can be supplied as string instead of list
ansible.builtin.assert:
that: "ansible_os_family != 'RedHat'"
@@ -106,4 +106,4 @@ EXAMPLES = r'''
- my_param <= 100
- my_param >= 0
quiet: true
-'''
+"""
diff --git a/lib/ansible/modules/async_status.py b/lib/ansible/modules/async_status.py
index e07143adb5..0a4eeb53ac 100644
--- a/lib/ansible/modules/async_status.py
+++ b/lib/ansible/modules/async_status.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: async_status
short_description: Obtain status of asynchronous task
@@ -51,9 +51,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
---
- name: Asynchronous dnf task
ansible.builtin.dnf:
@@ -75,9 +75,9 @@ EXAMPLES = r'''
ansible.builtin.async_status:
jid: '{{ dnf_sleeper.ansible_job_id }}'
mode: cleanup
-'''
+"""
-RETURN = r'''
+RETURN = r"""
ansible_job_id:
description: The asynchronous job id
returned: success
@@ -105,7 +105,7 @@ erased:
description: Path to erased job file
returned: when file is erased
type: str
-'''
+"""
import json
import os
diff --git a/lib/ansible/modules/async_wrapper.py b/lib/ansible/modules/async_wrapper.py
index cd87f1f4f2..d33ebe196e 100644
--- a/lib/ansible/modules/async_wrapper.py
+++ b/lib/ansible/modules/async_wrapper.py
@@ -75,13 +75,13 @@ def daemonize_self():
# NB: this function copied from module_utils/json_utils.py. Ensure any changes are propagated there.
# FUTURE: AnsibleModule-ify this module so it's Ansiballz-compatible and can use the module_utils copy of this function.
def _filter_non_json_lines(data):
- '''
+ """
Used to filter unrelated output around module JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
Filters leading lines before first line-starting occurrence of '{', and filter all
trailing lines after matching close character (working from the bottom of output).
- '''
+ """
warnings = []
# Filter initial junk
diff --git a/lib/ansible/modules/blockinfile.py b/lib/ansible/modules/blockinfile.py
index 602f0f0684..eec996796f 100644
--- a/lib/ansible/modules/blockinfile.py
+++ b/lib/ansible/modules/blockinfile.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: blockinfile
short_description: Insert/update/remove a text block surrounded by marker lines
@@ -125,9 +125,9 @@ attributes:
platforms: posix
vault:
support: none
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Before Ansible 2.3, option 'dest' or 'name' was used instead of 'path'
- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config prepending and appending a new line
ansible.builtin.blockinfile:
@@ -187,7 +187,7 @@ EXAMPLES = r'''
insertafter: '(?m)SID_LIST_LISTENER_DG =\n.*\(SID_LIST ='
marker: " <!-- {mark} ANSIBLE MANAGED BLOCK -->"
-'''
+"""
import re
import os
diff --git a/lib/ansible/modules/command.py b/lib/ansible/modules/command.py
index 42d9beeff4..2ce939ac28 100644
--- a/lib/ansible/modules/command.py
+++ b/lib/ansible/modules/command.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: command
short_description: Execute commands on targets
@@ -118,9 +118,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Return motd to registered var
ansible.builtin.command: cat /etc/motd
register: mymotd
@@ -174,9 +174,9 @@ EXAMPLES = r'''
- name: Safely use templated variable to run command. Always use the quote filter to avoid injection issues
ansible.builtin.command: cat {{ myfile|quote }}
register: myoutput
-'''
+"""
-RETURN = r'''
+RETURN = r"""
msg:
description: changed
returned: always
@@ -229,7 +229,7 @@ stderr_lines:
returned: always
type: list
sample: [u'ls cannot access foo: No such file or directory', u'ls …']
-'''
+"""
import datetime
import glob
diff --git a/lib/ansible/modules/copy.py b/lib/ansible/modules/copy.py
index bb9ea0493d..8a5297466f 100644
--- a/lib/ansible/modules/copy.py
+++ b/lib/ansible/modules/copy.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: copy
version_added: historical
@@ -154,9 +154,9 @@ attributes:
vault:
support: full
version_added: '2.2'
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Copy file with owner and permissions
ansible.builtin.copy:
src: /srv/myfiles/foo.conf
@@ -219,9 +219,9 @@ EXAMPLES = r'''
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: no
-'''
+"""
-RETURN = r'''
+RETURN = r"""
dest:
description: Destination file/path.
returned: success
@@ -282,7 +282,7 @@ state:
returned: success
type: str
sample: file
-'''
+"""
import errno
import filecmp
@@ -305,9 +305,9 @@ class AnsibleModuleError(Exception):
def split_pre_existing_dir(dirname):
- '''
+ """
Return the first pre-existing directory and a list of the new directories that will be created.
- '''
+ """
head, tail = os.path.split(dirname)
b_head = to_bytes(head, errors='surrogate_or_strict')
if head == '':
@@ -323,9 +323,9 @@ def split_pre_existing_dir(dirname):
def adjust_recursive_directory_permissions(pre_existing_dir, new_directory_list, module, directory_args, changed):
- '''
+ """
Walk the new directories list and make sure that permissions are as we would expect
- '''
+ """
if new_directory_list:
working_dir = os.path.join(pre_existing_dir, new_directory_list.pop(0))
diff --git a/lib/ansible/modules/cron.py b/lib/ansible/modules/cron.py
index dcd350159c..b9966a0933 100644
--- a/lib/ansible/modules/cron.py
+++ b/lib/ansible/modules/cron.py
@@ -10,7 +10,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: cron
short_description: Manage cron.d and crontab entries
@@ -150,9 +150,9 @@ attributes:
platform:
support: full
platforms: posix
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null"
ansible.builtin.cron:
name: "check dirs"
@@ -205,9 +205,9 @@ EXAMPLES = r'''
name: APP_HOME
env: yes
state: absent
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import os
import platform
diff --git a/lib/ansible/modules/deb822_repository.py b/lib/ansible/modules/deb822_repository.py
index 0fa33c73d7..a27af10786 100644
--- a/lib/ansible/modules/deb822_repository.py
+++ b/lib/ansible/modules/deb822_repository.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
author: 'Ansible Core Team (@ansible)'
short_description: 'Add and remove deb822 formatted repositories'
description:
@@ -145,9 +145,9 @@ options:
requirements:
- python3-debian / python-debian
version_added: '2.15'
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Add debian repo
deb822_repository:
name: debian
@@ -189,9 +189,9 @@ EXAMPLES = '''
components: stable
architectures: amd64
signed_by: https://download.example.com/linux/ubuntu/gpg
-'''
+"""
-RETURN = '''
+RETURN = """
repo:
description: A source string for the repository
returned: always
@@ -224,7 +224,7 @@ key_filename:
returned: always
type: str
sample: /etc/apt/keyrings/debian.gpg
-'''
+"""
import os
import re
diff --git a/lib/ansible/modules/debconf.py b/lib/ansible/modules/debconf.py
index 7a32c4b0e8..701c19dabb 100644
--- a/lib/ansible/modules/debconf.py
+++ b/lib/ansible/modules/debconf.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: debconf
short_description: Configure a .deb package
@@ -86,9 +86,9 @@ options:
default: false
author:
- Brian Coca (@bcoca)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Set default locale to fr_FR.UTF-8
ansible.builtin.debconf:
name: locales
@@ -121,9 +121,9 @@ EXAMPLES = r'''
value: "{{ site_passphrase }}"
vtype: password
no_log: True
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
from ansible.module_utils.common.text.converters import to_text, to_native
from ansible.module_utils.basic import AnsibleModule
diff --git a/lib/ansible/modules/debug.py b/lib/ansible/modules/debug.py
index 325d2541c2..c90b1eea80 100644
--- a/lib/ansible/modules/debug.py
+++ b/lib/ansible/modules/debug.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: debug
short_description: Print statements during execution
@@ -68,9 +68,9 @@ seealso:
author:
- Dag Wieers (@dagwieers)
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Print the gateway for each host when defined
ansible.builtin.debug:
msg: System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}
@@ -95,4 +95,4 @@ EXAMPLES = r'''
msg:
- "Provisioning based on YOUR_KEY which is: {{ lookup('ansible.builtin.env', 'YOUR_KEY') }}"
- "These servers were built using the password of '{{ password_used }}'. Please retain this for later use."
-'''
+"""
diff --git a/lib/ansible/modules/dnf.py b/lib/ansible/modules/dnf.py
index c9ddbb5ae5..7ab874a941 100644
--- a/lib/ansible/modules/dnf.py
+++ b/lib/ansible/modules/dnf.py
@@ -9,7 +9,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: dnf
version_added: 1.9
@@ -306,9 +306,9 @@ author:
- Cristian van Ee (@DJMuggs) <cristian at cvee.org>
- Berend De Schouwer (@berenddeschouwer)
- Adam Miller (@maxamillion) <admiller@redhat.com>
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Install the latest version of Apache
ansible.builtin.dnf:
name: httpd
@@ -394,7 +394,7 @@ EXAMPLES = '''
ansible.builtin.dnf:
name: '@postgresql/client'
state: present
-'''
+"""
import os
import sys
diff --git a/lib/ansible/modules/dpkg_selections.py b/lib/ansible/modules/dpkg_selections.py
index a1fa672732..31841306d8 100644
--- a/lib/ansible/modules/dpkg_selections.py
+++ b/lib/ansible/modules/dpkg_selections.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: dpkg_selections
short_description: Dpkg package selection selections
@@ -39,8 +39,8 @@ attributes:
platforms: debian
notes:
- This module will not cause any packages to be installed/removed/purged, use the M(ansible.builtin.apt) module for that.
-'''
-EXAMPLES = '''
+"""
+EXAMPLES = """
- name: Prevent python from being upgraded
ansible.builtin.dpkg_selections:
name: python
@@ -50,7 +50,7 @@ EXAMPLES = '''
ansible.builtin.dpkg_selections:
name: python
selection: install
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.locale import get_best_parsable_locale
diff --git a/lib/ansible/modules/expect.py b/lib/ansible/modules/expect.py
index 760d7148d6..90ece7d76f 100644
--- a/lib/ansible/modules/expect.py
+++ b/lib/ansible/modules/expect.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: expect
version_added: '2.0'
@@ -83,9 +83,9 @@ seealso:
- module: ansible.builtin.script
- module: ansible.builtin.shell
author: "Matt Martz (@sivel)"
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Case insensitive password string match
ansible.builtin.expect:
command: passwd username
@@ -116,7 +116,7 @@ EXAMPLES = r'''
- "{{ db_username }}"
"Database password":
- "{{ db_password }}"
-'''
+"""
import datetime
import os
diff --git a/lib/ansible/modules/fail.py b/lib/ansible/modules/fail.py
index e7a057e3fe..7e68c77070 100644
--- a/lib/ansible/modules/fail.py
+++ b/lib/ansible/modules/fail.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: fail
short_description: Fail with custom message
@@ -52,11 +52,11 @@ seealso:
- module: ansible.builtin.meta
author:
- Dag Wieers (@dagwieers)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Example using fail and when together
ansible.builtin.fail:
msg: The system may not be provisioned according to the CMDB status.
when: cmdb_status != "to-be-staged"
-'''
+"""
diff --git a/lib/ansible/modules/fetch.py b/lib/ansible/modules/fetch.py
index a5edb767df..5886a82ce8 100644
--- a/lib/ansible/modules/fetch.py
+++ b/lib/ansible/modules/fetch.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: fetch
short_description: Fetch files from remote nodes
@@ -95,9 +95,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Store file into /tmp/fetched/host.example.com/tmp/somefile
ansible.builtin.fetch:
src: /tmp/somefile
@@ -120,4 +120,4 @@ EXAMPLES = r'''
src: /tmp/uniquefile
dest: special/prefix-{{ inventory_hostname }}
flat: yes
-'''
+"""
diff --git a/lib/ansible/modules/file.py b/lib/ansible/modules/file.py
index 38d2fe77e8..f4761fc492 100644
--- a/lib/ansible/modules/file.py
+++ b/lib/ansible/modules/file.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: file
version_added: historical
@@ -123,9 +123,9 @@ attributes:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Change file ownership, group and permissions
ansible.builtin.file:
path: /etc/foo.conf
@@ -214,8 +214,8 @@ EXAMPLES = r'''
path: /etc/foo
state: absent
-'''
-RETURN = r'''
+"""
+RETURN = r"""
dest:
description: Destination file/path, equal to the value passed to O(path).
returned: O(state=touch), O(state=hard), O(state=link)
@@ -226,7 +226,7 @@ path:
returned: O(state=absent), O(state=directory), O(state=file)
type: str
sample: /path/to/file.txt
-'''
+"""
import errno
import os
@@ -296,7 +296,7 @@ def additional_parameter_handling(module):
def get_state(path):
- ''' Find out current state '''
+ """ Find out current state """
b_path = to_bytes(path, errors='surrogate_or_strict')
try:
diff --git a/lib/ansible/modules/find.py b/lib/ansible/modules/find.py
index a516b354bc..0e25923a32 100644
--- a/lib/ansible/modules/find.py
+++ b/lib/ansible/modules/find.py
@@ -9,7 +9,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: find
author: Brian Coca (@bcoca)
@@ -174,10 +174,10 @@ attributes:
platforms: posix
seealso:
- module: ansible.windows.win_find
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Recursively find /tmp files older than 2 days
ansible.builtin.find:
paths: /tmp
@@ -246,9 +246,9 @@ EXAMPLES = r'''
use_regex: true
recurse: true
limit: 1
-'''
+"""
-RETURN = r'''
+RETURN = r"""
files:
description: All matches found with the specified criteria (see stat module for full output of each dictionary)
returned: success
@@ -279,7 +279,7 @@ skipped_paths:
type: dict
sample: {"/laskdfj": "'/laskdfj' is not a directory"}
version_added: '2.12'
-'''
+"""
import errno
import fnmatch
@@ -302,7 +302,7 @@ class _Object:
def pfilter(f, patterns=None, excludes=None, use_regex=False):
- '''filter using glob patterns'''
+ """filter using glob patterns"""
if not patterns and not excludes:
return True
@@ -341,7 +341,7 @@ def pfilter(f, patterns=None, excludes=None, use_regex=False):
def agefilter(st, now, age, timestamp):
- '''filter files older than age'''
+ """filter files older than age"""
if age is None:
return True
elif age >= 0 and now - getattr(st, "st_%s" % timestamp) >= abs(age):
@@ -352,7 +352,7 @@ def agefilter(st, now, age, timestamp):
def sizefilter(st, size):
- '''filter files greater than size'''
+ """filter files greater than size"""
if size is None:
return True
elif size >= 0 and st.st_size >= abs(size):
diff --git a/lib/ansible/modules/gather_facts.py b/lib/ansible/modules/gather_facts.py
index 5787bbb3f8..3d0275a0f6 100644
--- a/lib/ansible/modules/gather_facts.py
+++ b/lib/ansible/modules/gather_facts.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: gather_facts
version_added: 2.8
@@ -57,7 +57,7 @@ notes:
Order is not guaranteed, when doing parallel gathering on multiple modules.
author:
- "Ansible Core Team"
-'''
+"""
RETURN = """
# depends on the fact module called
diff --git a/lib/ansible/modules/get_url.py b/lib/ansible/modules/get_url.py
index 965e5f6196..52c812c0c6 100644
--- a/lib/ansible/modules/get_url.py
+++ b/lib/ansible/modules/get_url.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: get_url
short_description: Downloads files from HTTP, HTTPS, or FTP to node
@@ -219,9 +219,9 @@ seealso:
- module: ansible.windows.win_get_url
author:
- Jan-Piet Mens (@jpmens)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Download foo.conf
ansible.builtin.get_url:
url: http://example.com/path/file.conf
@@ -272,9 +272,9 @@ EXAMPLES = r'''
dest: /etc/foo.conf
username: bar
password: '{{ mysecret }}'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
backup_file:
description: name of backup file created after download
returned: changed and if backup=yes
@@ -365,7 +365,7 @@ url:
returned: always
type: str
sample: https://www.ansible.com/
-'''
+"""
import email.message
import os
diff --git a/lib/ansible/modules/getent.py b/lib/ansible/modules/getent.py
index b07fb82351..1938af1fcf 100644
--- a/lib/ansible/modules/getent.py
+++ b/lib/ansible/modules/getent.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: getent
short_description: A wrapper to the unix getent utility
@@ -58,9 +58,9 @@ notes:
- Not all databases support enumeration, check system documentation for details.
author:
- Brian Coca (@bcoca)
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Get root user info
ansible.builtin.getent:
database: passwd
@@ -97,9 +97,9 @@ EXAMPLES = '''
- ansible.builtin.debug:
var: ansible_facts.getent_shadow
-'''
+"""
-RETURN = '''
+RETURN = """
ansible_facts:
description: Facts to add to ansible_facts.
returned: always
@@ -112,7 +112,7 @@ ansible_facts:
- Starting at 2.11 it now returns multiple duplicate entries, previously it only returned the last one
returned: always
type: list
-'''
+"""
import traceback
diff --git a/lib/ansible/modules/git.py b/lib/ansible/modules/git.py
index c9ccff4bfc..288d18d820 100644
--- a/lib/ansible/modules/git.py
+++ b/lib/ansible/modules/git.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: git
author:
@@ -236,9 +236,9 @@ notes:
one solution is to use the option accept_hostkey. Another solution is to
add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling
the git module, with the following command: C(ssh-keyscan -H remote_host.com >> /etc/ssh/ssh_known_hosts)."
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Git checkout
ansible.builtin.git:
repo: 'https://github.com/ansible/ansible.git'
@@ -295,9 +295,9 @@ EXAMPLES = '''
environment:
GIT_TERMINAL_PROMPT: 0 # reports "terminal prompts disabled" on missing password
# or GIT_ASKPASS: /bin/true # for git before version 2.3.0, reports "Authentication failed" on missing password
-'''
+"""
-RETURN = '''
+RETURN = """
after:
description: Last commit revision of the repository retrieved during the update.
returned: success
@@ -328,7 +328,7 @@ git_dir_before:
returned: success
type: str
sample: /path/to/old/git/dir
-'''
+"""
import filecmp
import os
@@ -366,7 +366,7 @@ def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir):
def head_splitter(headfile, remote, module=None, fail_on_error=False):
- '''Extract the head reference'''
+ """Extract the head reference"""
# https://github.com/ansible/ansible-modules-core/pull/907
res = None
@@ -429,11 +429,11 @@ def get_submodule_update_params(module, git_path, cwd):
def write_ssh_wrapper(module):
- '''
+ """
This writes an shell wrapper for ssh options to be used with git
this is only relevant for older versions of gitthat cannot
handle the options themselves. Returns path to the script
- '''
+ """
try:
# make sure we have full permission to the module_dir, which
# may not be the case if we're sudo'ing to a non-root user
@@ -466,10 +466,10 @@ def write_ssh_wrapper(module):
def set_git_ssh_env(key_file, ssh_opts, git_version, module):
- '''
+ """
use environment variables to configure git's ssh execution,
which varies by version but this function should handle all.
- '''
+ """
# initialise to existing ssh opts and/or append user provided
if ssh_opts is None:
@@ -519,7 +519,7 @@ def set_git_ssh_env(key_file, ssh_opts, git_version, module):
def get_version(module, git_path, dest, ref="HEAD"):
- ''' samples the version of the git repo '''
+ """ samples the version of the git repo """
cmd = "%s rev-parse %s" % (git_path, ref)
rc, stdout, stderr = module.run_command(cmd, cwd=dest)
@@ -571,7 +571,7 @@ def get_submodule_versions(git_path, module, dest, version='HEAD'):
def clone(git_path, module, repo, dest, remote, depth, version, bare,
reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_allowlist, single_branch):
- ''' makes a new git repo if it does not already exist '''
+ """ makes a new git repo if it does not already exist """
dest_dirname = os.path.dirname(dest)
try:
os.makedirs(dest_dirname)
@@ -653,17 +653,17 @@ def has_local_mods(module, git_path, dest, bare):
def reset(git_path, module, dest):
- '''
+ """
Resets the index and working tree to HEAD.
Discards any changes to tracked files in working
tree since that commit.
- '''
+ """
cmd = "%s reset --hard HEAD" % (git_path,)
return module.run_command(cmd, check_rc=True, cwd=dest)
def get_diff(module, git_path, dest, repo, remote, depth, bare, before, after):
- ''' Return the difference between 2 versions '''
+ """ Return the difference between 2 versions """
if before is None:
return {'prepared': '>> Newly checked out %s' % after}
elif before != after:
@@ -817,13 +817,13 @@ def get_repo_path(dest, bare):
def get_head_branch(git_path, module, dest, remote, bare=False):
- '''
+ """
Determine what branch HEAD is associated with. This is partly
taken from lib/ansible/utils/__init__.py. It finds the correct
path to .git/HEAD and reads from that file the branch that HEAD is
associated with. In the case of a detached HEAD, this will look
up the branch in .git/refs/remotes/<remote>/HEAD.
- '''
+ """
try:
repo_path = get_repo_path(dest, bare)
except (IOError, ValueError) as err:
@@ -845,7 +845,7 @@ def get_head_branch(git_path, module, dest, remote, bare=False):
def get_remote_url(git_path, module, dest, remote):
- '''Return URL of remote source for repo.'''
+ """Return URL of remote source for repo."""
command = [git_path, 'ls-remote', '--get-url', remote]
(rc, out, err) = module.run_command(command, cwd=dest)
if rc != 0:
@@ -856,7 +856,7 @@ def get_remote_url(git_path, module, dest, remote):
def set_remote_url(git_path, module, repo, dest, remote):
- ''' updates repo from remote sources '''
+ """ updates repo from remote sources """
# Return if remote URL isn't changing.
remote_url = get_remote_url(git_path, module, dest, remote)
if remote_url == repo or unfrackgitpath(remote_url) == unfrackgitpath(repo):
@@ -874,7 +874,7 @@ def set_remote_url(git_path, module, repo, dest, remote):
def fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=False):
- ''' updates repo from remote sources '''
+ """ updates repo from remote sources """
set_remote_url(git_path, module, repo, dest, remote)
commands = []
@@ -981,7 +981,7 @@ def submodules_fetch(git_path, module, remote, track_submodules, dest):
def submodule_update(git_path, module, dest, track_submodules, force=False):
- ''' init and update any submodules '''
+ """ init and update any submodules """
# get the valid submodule params
params = get_submodule_update_params(module, git_path, dest)
diff --git a/lib/ansible/modules/group.py b/lib/ansible/modules/group.py
index 716e7e0a51..a31b9f8c73 100644
--- a/lib/ansible/modules/group.py
+++ b/lib/ansible/modules/group.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: group
version_added: "0.0.2"
@@ -91,9 +91,9 @@ seealso:
- module: ansible.windows.win_group
author:
- Stephen Fromm (@sfromm)
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Ensure group "somegroup" exists
ansible.builtin.group:
name: somegroup
@@ -104,9 +104,9 @@ EXAMPLES = '''
name: docker
state: present
gid: 1750
-'''
+"""
-RETURN = r'''
+RETURN = r"""
gid:
description: Group ID of the group.
returned: When O(state) is C(present)
@@ -127,7 +127,7 @@ system:
returned: When O(state) is C(present)
type: bool
sample: False
-'''
+"""
import grp
import os
diff --git a/lib/ansible/modules/group_by.py b/lib/ansible/modules/group_by.py
index 6efe800151..5fc7b690af 100644
--- a/lib/ansible/modules/group_by.py
+++ b/lib/ansible/modules/group_by.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: group_by
short_description: Create Ansible groups based on facts
@@ -65,9 +65,9 @@ seealso:
- module: ansible.builtin.add_host
author:
- Jeroen Hoekx (@jhoekx)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Create groups based on the machine architecture
ansible.builtin.group_by:
key: machine_{{ ansible_machine }}
@@ -85,4 +85,4 @@ EXAMPLES = r'''
- name: Add all active hosts to a static group
ansible.builtin.group_by:
key: done
-'''
+"""
diff --git a/lib/ansible/modules/hostname.py b/lib/ansible/modules/hostname.py
index 4b2ee682f2..79f9bcb070 100644
--- a/lib/ansible/modules/hostname.py
+++ b/lib/ansible/modules/hostname.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: hostname
author:
@@ -52,9 +52,9 @@ attributes:
support: full
platform:
platforms: posix
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Set a hostname
ansible.builtin.hostname:
name: web01
@@ -63,7 +63,7 @@ EXAMPLES = '''
ansible.builtin.hostname:
name: web01
use: systemd
-'''
+"""
import os
import platform
diff --git a/lib/ansible/modules/import_playbook.py b/lib/ansible/modules/import_playbook.py
index a4c7809637..71f1693241 100644
--- a/lib/ansible/modules/import_playbook.py
+++ b/lib/ansible/modules/import_playbook.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
author: Ansible Core Team (@ansible)
module: import_playbook
@@ -42,9 +42,9 @@ seealso:
- module: ansible.builtin.include_tasks
- ref: playbooks_reuse
description: More information related to including and importing playbooks, roles and tasks.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- hosts: localhost
tasks:
- ansible.builtin.debug:
@@ -69,8 +69,8 @@ EXAMPLES = r'''
- name: This fails because I'm inside a play already
ansible.builtin.import_playbook: stuff.yaml
-'''
+"""
-RETURN = r'''
+RETURN = r"""
# This module does not return anything except plays to execute.
-'''
+"""
diff --git a/lib/ansible/modules/import_role.py b/lib/ansible/modules/import_role.py
index 719d4297b9..0b9eff7124 100644
--- a/lib/ansible/modules/import_role.py
+++ b/lib/ansible/modules/import_role.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
author: Ansible Core Team (@ansible)
module: import_role
@@ -87,9 +87,9 @@ seealso:
- module: ansible.builtin.include_tasks
- ref: playbooks_reuse
description: More information related to including and importing playbooks, roles and tasks.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- hosts: all
tasks:
- ansible.builtin.import_role:
@@ -110,8 +110,8 @@ EXAMPLES = r'''
ansible.builtin.import_role:
name: myrole
when: not idontwanttorun
-'''
+"""
-RETURN = r'''
+RETURN = r"""
# This module does not return anything except tasks to execute.
-'''
+"""
diff --git a/lib/ansible/modules/import_tasks.py b/lib/ansible/modules/import_tasks.py
index 4d60368dcb..26ef9d9019 100644
--- a/lib/ansible/modules/import_tasks.py
+++ b/lib/ansible/modules/import_tasks.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
author: Ansible Core Team (@ansible)
module: import_tasks
@@ -46,9 +46,9 @@ seealso:
- module: ansible.builtin.include_tasks
- ref: playbooks_reuse
description: More information related to including and importing playbooks, roles and tasks.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- hosts: all
tasks:
- ansible.builtin.debug:
@@ -69,8 +69,8 @@ EXAMPLES = r'''
- name: Apply conditional to all imported tasks
ansible.builtin.import_tasks: stuff.yaml
when: hostvar is defined
-'''
+"""
-RETURN = r'''
+RETURN = r"""
# This module does not return anything except tasks to execute.
-'''
+"""
diff --git a/lib/ansible/modules/include_role.py b/lib/ansible/modules/include_role.py
index 9fa07034df..e800c5e61c 100644
--- a/lib/ansible/modules/include_role.py
+++ b/lib/ansible/modules/include_role.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
author: Ansible Core Team (@ansible)
module: include_role
@@ -92,9 +92,9 @@ seealso:
- module: ansible.builtin.include_tasks
- ref: playbooks_reuse
description: More information related to including and importing playbooks, roles and tasks.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- ansible.builtin.include_role:
name: myrole
@@ -131,8 +131,8 @@ EXAMPLES = r'''
- install
tags:
- always
-'''
+"""
-RETURN = r'''
+RETURN = r"""
# This module does not return anything except tasks to execute.
-'''
+"""
diff --git a/lib/ansible/modules/include_tasks.py b/lib/ansible/modules/include_tasks.py
index 82fb586512..d2657960d9 100644
--- a/lib/ansible/modules/include_tasks.py
+++ b/lib/ansible/modules/include_tasks.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
author: Ansible Core Team (@ansible)
module: include_tasks
@@ -50,9 +50,9 @@ seealso:
- module: ansible.builtin.include_role
- ref: playbooks_reuse
description: More information related to including and importing playbooks, roles and tasks.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- hosts: all
tasks:
- ansible.builtin.debug:
@@ -91,8 +91,8 @@ EXAMPLES = r'''
- install
tags:
- always
-'''
+"""
-RETURN = r'''
+RETURN = r"""
# This module does not return anything except tasks to execute.
-'''
+"""
diff --git a/lib/ansible/modules/include_vars.py b/lib/ansible/modules/include_vars.py
index 9238682dea..b2e3c44e38 100644
--- a/lib/ansible/modules/include_vars.py
+++ b/lib/ansible/modules/include_vars.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
author: Allen Sanabria (@linuxdynasty)
module: include_vars
@@ -112,9 +112,9 @@ seealso:
- module: ansible.builtin.set_fact
- ref: playbooks_delegation
description: More information related to task delegation.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Include vars of stuff.yaml into the 'stuff' variable (2.2).
ansible.builtin.include_vars:
file: stuff.yaml
@@ -179,9 +179,9 @@ EXAMPLES = r'''
- 'yaml'
- 'yml'
- 'json'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
ansible_facts:
description: Variables that were included and their values
returned: success
@@ -193,4 +193,4 @@ ansible_included_var_files:
type: list
sample: [ /path/to/file.json, /path/to/file.yaml ]
version_added: '2.4'
-'''
+"""
diff --git a/lib/ansible/modules/iptables.py b/lib/ansible/modules/iptables.py
index fad9b405ae..164b53960b 100644
--- a/lib/ansible/modules/iptables.py
+++ b/lib/ansible/modules/iptables.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: iptables
short_description: Modify iptables rules
@@ -394,9 +394,9 @@ options:
type: bool
default: false
version_added: "2.15"
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Block specific IP
ansible.builtin.iptables:
chain: INPUT
@@ -543,7 +543,7 @@ EXAMPLES = r'''
- "443"
- "8081:8083"
jump: ACCEPT
-'''
+"""
import re
diff --git a/lib/ansible/modules/known_hosts.py b/lib/ansible/modules/known_hosts.py
index b4155660e1..c001915115 100644
--- a/lib/ansible/modules/known_hosts.py
+++ b/lib/ansible/modules/known_hosts.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: known_hosts
short_description: Add or remove a host from the C(known_hosts) file
@@ -65,9 +65,9 @@ extends_documentation_fragment:
- action_common_attributes
author:
- Matthew Vernon (@mcv21)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Tell the host about our servers it might want to ssh to
ansible.builtin.known_hosts:
path: /etc/ssh/ssh_known_hosts
@@ -87,7 +87,7 @@ EXAMPLES = r'''
key: '[host1.example.com]:2222 ssh-rsa ASDeararAIUHI324324' # some key gibberish
path: /etc/ssh/ssh_known_hosts
state: present
-'''
+"""
# Makes sure public host keys are present or absent in the given known_hosts
# file.
@@ -195,13 +195,13 @@ def enforce_state(module, params):
def sanity_check(module, host, key, sshkeygen):
- '''Check supplied key is sensible
+ """Check supplied key is sensible
host and key are parameters provided by the user; If the host
provided is inconsistent with the key supplied, then this function
quits, providing an error to the user.
sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
- '''
+ """
# If no key supplied, we're doing a removal, and have nothing to check here.
if not key:
return
@@ -232,7 +232,7 @@ def sanity_check(module, host, key, sshkeygen):
def search_for_host_key(module, host, key, path, sshkeygen):
- '''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line)
+ """search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line)
Looks up host and keytype in the known_hosts file path; if it's there, looks to see
if one of those entries matches key. Returns:
@@ -241,7 +241,7 @@ def search_for_host_key(module, host, key, path, sshkeygen):
found_line (int or None): the line where a key of the same type was found
if found=False, then replace is always False.
sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
- '''
+ """
if os.path.exists(path) is False:
return False, False, None
@@ -304,14 +304,14 @@ def hash_host_key(host, key):
def normalize_known_hosts_key(key):
- '''
+ """
Transform a key, either taken from a known_host file or provided by the
user, into a normalized form.
The host part (which might include multiple hostnames or be hashed) gets
replaced by the provided host. Also, any spurious information gets removed
from the end (like the username@host tag usually present in hostkeys, but
absent in known_hosts files)
- '''
+ """
key = key.strip() # trim trailing newline
k = key.split()
d = dict()
diff --git a/lib/ansible/modules/lineinfile.py b/lib/ansible/modules/lineinfile.py
index 105fcc8660..0ef882f484 100644
--- a/lib/ansible/modules/lineinfile.py
+++ b/lib/ansible/modules/lineinfile.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: lineinfile
short_description: Manage lines in text files
@@ -152,9 +152,9 @@ author:
- Daniel Hokka Zakrissoni (@dhozac)
- Ahti Kitsik (@ahtik)
- Jose Angel Munoz (@imjoseangel)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- name: Ensure SELinux is set to enforcing mode
ansible.builtin.lineinfile:
@@ -237,9 +237,9 @@ EXAMPLES = r'''
regexp: ^(host=).*
line: \g<1>{{ hostname }}
backrefs: yes
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import os
import re
diff --git a/lib/ansible/modules/meta.py b/lib/ansible/modules/meta.py
index 91b3f0403f..b10a56e244 100644
--- a/lib/ansible/modules/meta.py
+++ b/lib/ansible/modules/meta.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: meta
short_description: Execute Ansible 'actions'
version_added: '1.2'
@@ -78,9 +78,9 @@ seealso:
- module: ansible.builtin.fail
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Example showing flushing handlers on demand, not at end of play
- ansible.builtin.template:
src: new.j2
@@ -126,4 +126,4 @@ EXAMPLES = r'''
when:
- ansible_distribution == 'CentOS'
- ansible_distribution_major_version == '6'
-'''
+"""
diff --git a/lib/ansible/modules/package.py b/lib/ansible/modules/package.py
index 54d88999ef..adc390c08f 100644
--- a/lib/ansible/modules/package.py
+++ b/lib/ansible/modules/package.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: package
version_added: 2.0
@@ -66,8 +66,8 @@ attributes:
notes:
- While M(ansible.builtin.package) abstracts package managers to ease dealing with multiple distributions, package name often differs for the same software.
-'''
-EXAMPLES = '''
+"""
+EXAMPLES = """
- name: Install ntpdate
ansible.builtin.package:
name: ntpdate
@@ -85,4 +85,4 @@ EXAMPLES = '''
- httpd
- mariadb-server
state: latest
-'''
+"""
diff --git a/lib/ansible/modules/package_facts.py b/lib/ansible/modules/package_facts.py
index bec6c34260..df10c4694d 100644
--- a/lib/ansible/modules/package_facts.py
+++ b/lib/ansible/modules/package_facts.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: package_facts
short_description: Package information as facts
description:
@@ -67,9 +67,9 @@ attributes:
support: full
platform:
platforms: posix
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Gather the package facts
ansible.builtin.package_facts:
manager: auto
@@ -83,9 +83,9 @@ EXAMPLES = '''
msg: "{{ ansible_facts.packages['foobar'] | length }} versions of foobar are installed!"
when: "'foobar' in ansible_facts.packages"
-'''
+"""
-RETURN = '''
+RETURN = """
ansible_facts:
description: Facts to add to ansible_facts.
returned: always
@@ -248,7 +248,7 @@ ansible_facts:
],
}
}
-'''
+"""
import re
diff --git a/lib/ansible/modules/pause.py b/lib/ansible/modules/pause.py
index 68ac945708..5be9b5b997 100644
--- a/lib/ansible/modules/pause.py
+++ b/lib/ansible/modules/pause.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: pause
short_description: Pause playbook execution
@@ -65,9 +65,9 @@ attributes:
notes:
- Starting in 2.2, if you specify 0 or negative for minutes or seconds, it will wait for 1 second, previously it would wait indefinitely.
- User input is not captured or echoed, regardless of echo setting, when minutes or seconds is specified.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Pause for 5 minutes to build app cache
ansible.builtin.pause:
minutes: 5
@@ -83,9 +83,9 @@ EXAMPLES = '''
ansible.builtin.pause:
prompt: "Enter a secret"
echo: no
-'''
+"""
-RETURN = '''
+RETURN = """
user_input:
description: User input from interactive console
returned: if no waiting time set
@@ -116,4 +116,4 @@ echo:
returned: always
type: bool
sample: true
-'''
+"""
diff --git a/lib/ansible/modules/ping.py b/lib/ansible/modules/ping.py
index a29e1442b8..f65c2699c0 100644
--- a/lib/ansible/modules/ping.py
+++ b/lib/ansible/modules/ping.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -41,9 +41,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ansible.builtin.ping
@@ -53,15 +53,15 @@ EXAMPLES = '''
- name: Induce an exception to see what happens
ansible.builtin.ping:
data: crash
-'''
+"""
-RETURN = '''
+RETURN = """
ping:
description: Value provided with the O(data) parameter.
returned: success
type: str
sample: pong
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/lib/ansible/modules/pip.py b/lib/ansible/modules/pip.py
index 3868b89c70..028ef3f6e3 100644
--- a/lib/ansible/modules/pip.py
+++ b/lib/ansible/modules/pip.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: pip
short_description: Manages Python library dependencies
@@ -145,9 +145,9 @@ requirements:
- setuptools or packaging
author:
- Matt Wright (@mattupstate)
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Install bottle python package
ansible.builtin.pip:
name: bottle
@@ -262,9 +262,9 @@ EXAMPLES = '''
vars:
venv_dir: /tmp/pick-a-better-venv-path
venv_python: "{{ venv_dir }}/bin/python"
-'''
+"""
-RETURN = '''
+RETURN = """
cmd:
description: pip command used by the module
returned: success
@@ -290,7 +290,7 @@ virtualenv:
returned: success, if a virtualenv path was provided
type: str
sample: "/tmp/virtualenv"
-'''
+"""
import argparse
import os
@@ -417,7 +417,7 @@ def _get_cmd_options(module, cmd):
def _get_packages(module, pip, chdir):
- '''Return results of pip command to get packages.'''
+ """Return results of pip command to get packages."""
# Try 'pip list' command first.
command = pip + ['list', '--format=freeze']
locale = get_best_parsable_locale(module)
@@ -435,7 +435,7 @@ def _get_packages(module, pip, chdir):
def _is_present(module, req, installed_pkgs, pkg_command):
- '''Return whether or not package is installed.'''
+ """Return whether or not package is installed."""
for pkg in installed_pkgs:
if '==' in pkg:
pkg_name, pkg_version = pkg.split('==')
diff --git a/lib/ansible/modules/raw.py b/lib/ansible/modules/raw.py
index 75ff754ca1..5825a46502 100644
--- a/lib/ansible/modules/raw.py
+++ b/lib/ansible/modules/raw.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: raw
short_description: Executes a low-down and dirty command
@@ -70,9 +70,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Bootstrap a host without python2 installed
ansible.builtin.raw: dnf install -y python2 python2-dnf libselinux-python
@@ -86,4 +86,4 @@ EXAMPLES = r'''
- name: List user accounts on a Windows system
ansible.builtin.raw: Get-WmiObject -Class Win32_UserAccount
-'''
+"""
diff --git a/lib/ansible/modules/reboot.py b/lib/ansible/modules/reboot.py
index 6d8dbd6feb..a54b334aa8 100644
--- a/lib/ansible/modules/reboot.py
+++ b/lib/ansible/modules/reboot.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: reboot
short_description: Reboot a machine
notes:
@@ -100,9 +100,9 @@ seealso:
author:
- Matt Davis (@nitzmahone)
- Sam Doran (@samdoran)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Unconditionally reboot the machine with all defaults
ansible.builtin.reboot:
@@ -124,9 +124,9 @@ EXAMPLES = r'''
ansible.builtin.reboot:
msg: "Rebooting machine in 5 seconds"
-'''
+"""
-RETURN = r'''
+RETURN = r"""
rebooted:
description: true if the machine was rebooted
returned: always
@@ -137,4 +137,4 @@ elapsed:
returned: always
type: int
sample: 23
-'''
+"""
diff --git a/lib/ansible/modules/replace.py b/lib/ansible/modules/replace.py
index d09635a33b..f67037af15 100644
--- a/lib/ansible/modules/replace.py
+++ b/lib/ansible/modules/replace.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: replace
author: Evan Kaufman (@EvanK)
@@ -106,9 +106,9 @@ notes:
See U(https://github.com/ansible/ansible/issues/31354) for details.
- Option O(ignore:follow) has been removed in Ansible 2.5, because this module modifies the contents of the file
so O(ignore:follow=no) does not make sense.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Replace old hostname with new hostname (requires Ansible >= 2.4)
ansible.builtin.replace:
path: /etc/hosts
@@ -175,9 +175,9 @@ EXAMPLES = r'''
path: /etc/ssh/sshd_config
regexp: '^(?P<dctv>ListenAddress[ ]+)(?P<host>[^\n]+)$'
replace: '#\g<dctv>\g<host>\n\g<dctv>0.0.0.0'
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import os
import re
diff --git a/lib/ansible/modules/rpm_key.py b/lib/ansible/modules/rpm_key.py
index 3c7904df88..1cdc8a3a0c 100644
--- a/lib/ansible/modules/rpm_key.py
+++ b/lib/ansible/modules/rpm_key.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: rpm_key
author:
@@ -52,9 +52,9 @@ attributes:
support: none
platform:
platforms: rhel
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Import a key from a url
ansible.builtin.rpm_key:
state: present
@@ -81,9 +81,9 @@ EXAMPLES = '''
fingerprint:
- EBC6 E12C 62B1 C734 026B 2122 A20E 5214 6B8D 79E6
- 19B7 913E 6284 8E3F 4D78 D6B4 ECD9 1AB2 2EB6 8D86
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import re
import os.path
diff --git a/lib/ansible/modules/script.py b/lib/ansible/modules/script.py
index 0705c891bb..5d4b45f782 100644
--- a/lib/ansible/modules/script.py
+++ b/lib/ansible/modules/script.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: script
version_added: "0.9"
@@ -80,9 +80,9 @@ attributes:
support: none
vault:
support: full
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Run a script with arguments (free form)
ansible.builtin.script: /some/local/script.sh --some-argument 1234
@@ -112,4 +112,4 @@ EXAMPLES = r'''
- name: Run a Powershell script on a Windows host
script: subdirectories/under/path/with/your/playbook/script.ps1
-'''
+"""
diff --git a/lib/ansible/modules/service.py b/lib/ansible/modules/service.py
index d3cf84b099..7db499cd99 100644
--- a/lib/ansible/modules/service.py
+++ b/lib/ansible/modules/service.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: service
version_added: "0.1"
@@ -114,9 +114,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Start service httpd, if not started
ansible.builtin.service:
name: httpd
@@ -153,9 +153,9 @@ EXAMPLES = r'''
name: network
state: restarted
args: eth0
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import glob
import json
diff --git a/lib/ansible/modules/service_facts.py b/lib/ansible/modules/service_facts.py
index 810e8d2a38..e37ddd69b3 100644
--- a/lib/ansible/modules/service_facts.py
+++ b/lib/ansible/modules/service_facts.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: service_facts
short_description: Return service state information as fact data
@@ -36,9 +36,9 @@ notes:
- AIX SRC was added in version 2.11.
author:
- Adam Miller (@maxamillion)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Populate service facts
ansible.builtin.service_facts:
@@ -58,9 +58,9 @@ EXAMPLES = r'''
name: ntpd.service
when: ansible_facts['services']['ntpd.service']['status'] | default('not-found') != 'not-found'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
ansible_facts:
description: Facts to add to ansible_facts about the services on the system
returned: always
@@ -99,7 +99,7 @@ ansible_facts:
returned: always
type: str
sample: arp-ethers.service
-'''
+"""
import os
diff --git a/lib/ansible/modules/set_fact.py b/lib/ansible/modules/set_fact.py
index c9ab09bb11..ef4989c44f 100644
--- a/lib/ansible/modules/set_fact.py
+++ b/lib/ansible/modules/set_fact.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: set_fact
short_description: Set host variable(s) and fact(s).
@@ -77,9 +77,9 @@ seealso:
description: More information related to variable precedence and which type of variable wins over others.
author:
- Dag Wieers (@dagwieers)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Setting host facts using key=value pairs, this format can only create strings or booleans
ansible.builtin.set_fact: one_fact="something" other_fact="{{ local_var }}"
@@ -116,4 +116,4 @@ EXAMPLES = r'''
ansible.builtin.set_fact:
two_dict: {'something': here2, 'other': somewhere}
two_list: [1,2,3]
-'''
+"""
diff --git a/lib/ansible/modules/set_stats.py b/lib/ansible/modules/set_stats.py
index a375e432a5..f4900a6a44 100644
--- a/lib/ansible/modules/set_stats.py
+++ b/lib/ansible/modules/set_stats.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: set_stats
short_description: Define and display stats for the current ansible run
@@ -56,9 +56,9 @@ notes:
- In order for custom stats to be displayed, you must set C(show_custom_stats) in section C([defaults]) in C(ansible.cfg)
or by defining environment variable C(ANSIBLE_SHOW_CUSTOM_STATS) to V(true). See the P(ansible.builtin.default#callback) callback plugin for details.
version_added: "2.3"
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Aggregating packages_installed stat per host
ansible.builtin.set_stats:
data:
@@ -78,4 +78,4 @@ EXAMPLES = r'''
data:
the_answer: 42
aggregate: no
-'''
+"""
diff --git a/lib/ansible/modules/setup.py b/lib/ansible/modules/setup.py
index 05d3dca4c0..1f6a81c412 100644
--- a/lib/ansible/modules/setup.py
+++ b/lib/ansible/modules/setup.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: setup
version_added: historical
@@ -110,7 +110,7 @@ notes:
author:
- "Ansible Core Team"
- "Michael DeHaan"
-'''
+"""
EXAMPLES = r"""
# Display facts from all hosts and store them indexed by `hostname` at `/tmp/facts`.
diff --git a/lib/ansible/modules/shell.py b/lib/ansible/modules/shell.py
index 5cedd62525..38a65477be 100644
--- a/lib/ansible/modules/shell.py
+++ b/lib/ansible/modules/shell.py
@@ -10,7 +10,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: shell
short_description: Execute shell commands on targets
@@ -99,9 +99,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Execute the command in remote shell; stdout goes to the specified file on the remote
ansible.builtin.shell: somescript.sh >> somelog.txt
@@ -150,9 +150,9 @@ EXAMPLES = r'''
args:
executable: /usr/bin/expect
delegate_to: localhost
-'''
+"""
-RETURN = r'''
+RETURN = r"""
msg:
description: changed
returned: always
@@ -203,4 +203,4 @@ stderr_lines:
returned: always
type: list
sample: [u'ls cannot access foo: No such file or directory', u'ls …']
-'''
+"""
diff --git a/lib/ansible/modules/slurp.py b/lib/ansible/modules/slurp.py
index e9a65471a3..83ba4ad31f 100644
--- a/lib/ansible/modules/slurp.py
+++ b/lib/ansible/modules/slurp.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: slurp
version_added: historical
@@ -39,9 +39,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan (@mpdehaan)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Find out what the remote machine's mounts are
ansible.builtin.slurp:
src: /proc/mounts
@@ -61,9 +61,9 @@ EXAMPLES = r'''
# }
# $ echo MjE3OQo= | base64 -d
# 2179
-'''
+"""
-RETURN = r'''
+RETURN = r"""
content:
description: Encoded file content
returned: success
@@ -79,7 +79,7 @@ source:
returned: success
type: str
sample: "/var/run/sshd.pid"
-'''
+"""
import base64
import errno
diff --git a/lib/ansible/modules/stat.py b/lib/ansible/modules/stat.py
index 98392e9d70..274374c28d 100644
--- a/lib/ansible/modules/stat.py
+++ b/lib/ansible/modules/stat.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: stat
version_added: "1.3"
@@ -72,9 +72,9 @@ seealso:
- module: ansible.builtin.file
- module: ansible.windows.win_stat
author: Bruce Pennypacker (@bpennypacker)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Obtain the stats of /etc/foo.conf, and check that the file still belongs
# to 'root'. Fail otherwise.
- name: Get stats of a file
@@ -137,9 +137,9 @@ EXAMPLES = r'''
ansible.builtin.stat:
path: /path/to/something
checksum_algorithm: sha256
-'''
+"""
-RETURN = r'''
+RETURN = r"""
stat:
description: Dictionary containing all the stat data, some platforms might add additional fields.
returned: success
@@ -366,7 +366,7 @@ stat:
type: str
sample: "381700746"
version_added: 2.3
-'''
+"""
import errno
import grp
diff --git a/lib/ansible/modules/subversion.py b/lib/ansible/modules/subversion.py
index db1238b2d5..6e49bf9b15 100644
--- a/lib/ansible/modules/subversion.py
+++ b/lib/ansible/modules/subversion.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: subversion
short_description: Deploys a subversion repository
@@ -106,9 +106,9 @@ notes:
requirements:
- subversion (the command line tool with C(svn) entrypoint)
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Checkout subversion repository to specified folder
ansible.builtin.subversion:
repo: svn+ssh://an.example.org/path/to/repo
@@ -126,9 +126,9 @@ EXAMPLES = '''
dest: /src/checkout
checkout: no
update: no
-'''
+"""
-RETURN = r'''#'''
+RETURN = r"""#"""
import os
import re
@@ -161,7 +161,7 @@ class Subversion(object):
return LooseVersion(version) >= LooseVersion('1.10.0')
def _exec(self, args, check_rc=True):
- '''Execute a subversion command, and return output. If check_rc is False, returns the return code instead of the output.'''
+ """Execute a subversion command, and return output. If check_rc is False, returns the return code instead of the output."""
bits = [
self.svn_path,
'--non-interactive',
@@ -189,12 +189,12 @@ class Subversion(object):
return rc
def is_svn_repo(self):
- '''Checks if path is a SVN Repo.'''
+ """Checks if path is a SVN Repo."""
rc = self._exec(["info", self.dest], check_rc=False)
return rc == 0
def checkout(self, force=False):
- '''Creates new svn working directory if it does not already exist.'''
+ """Creates new svn working directory if it does not already exist."""
cmd = ["checkout"]
if force:
cmd.append("--force")
@@ -202,7 +202,7 @@ class Subversion(object):
self._exec(cmd)
def export(self, force=False):
- '''Export svn repo to directory'''
+ """Export svn repo to directory"""
cmd = ["export"]
if force:
cmd.append("--force")
@@ -211,7 +211,7 @@ class Subversion(object):
self._exec(cmd)
def switch(self):
- '''Change working directory's repo.'''
+ """Change working directory's repo."""
# switch to ensure we are pointing at correct repo.
# it also updates!
output = self._exec(["switch", "--revision", self.revision, self.repo, self.dest])
@@ -221,7 +221,7 @@ class Subversion(object):
return False
def update(self):
- '''Update existing svn working directory.'''
+ """Update existing svn working directory."""
output = self._exec(["update", "-r", self.revision, self.dest])
for line in output:
@@ -230,7 +230,7 @@ class Subversion(object):
return False
def revert(self):
- '''Revert svn working directory.'''
+ """Revert svn working directory."""
output = self._exec(["revert", "-R", self.dest])
for line in output:
if re.search(r'^Reverted ', line) is None:
@@ -238,7 +238,7 @@ class Subversion(object):
return False
def get_revision(self):
- '''Revision and URL of subversion working directory.'''
+ """Revision and URL of subversion working directory."""
text = '\n'.join(self._exec(["info", self.dest]))
rev = re.search(self.REVISION_RE, text, re.MULTILINE)
if rev:
@@ -255,7 +255,7 @@ class Subversion(object):
return rev, url
def get_remote_revision(self):
- '''Revision and URL of subversion working directory.'''
+ """Revision and URL of subversion working directory."""
text = '\n'.join(self._exec(["info", self.repo]))
rev = re.search(self.REVISION_RE, text, re.MULTILINE)
if rev:
@@ -265,7 +265,7 @@ class Subversion(object):
return rev
def has_local_mods(self):
- '''True if revisioned files have been added or modified. Unrevisioned files are ignored.'''
+ """True if revisioned files have been added or modified. Unrevisioned files are ignored."""
lines = self._exec(["status", "--quiet", "--ignore-externals", self.dest])
# The --quiet option will return only modified files.
# Match only revisioned files, i.e. ignore status '?'.
diff --git a/lib/ansible/modules/systemd_service.py b/lib/ansible/modules/systemd_service.py
index 9c77ee80d5..4e58ba2e4d 100644
--- a/lib/ansible/modules/systemd_service.py
+++ b/lib/ansible/modules/systemd_service.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: systemd_service
author:
- Ansible Core Team
@@ -98,9 +98,9 @@ notes:
It has been reported that C(systemctl) can behave differently depending on the order of operations if you do the same manually.
requirements:
- A system managed by systemd.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Make sure a service unit is running
ansible.builtin.systemd_service:
state: started
@@ -149,9 +149,9 @@ EXAMPLES = '''
scope: user
environment:
XDG_RUNTIME_DIR: "/run/user/{{ myuid }}"
-'''
+"""
-RETURN = '''
+RETURN = """
status:
description: A dictionary with the key=value pairs returned from C(systemctl show).
returned: success
@@ -279,7 +279,7 @@ status:
"WatchdogTimestampMonotonic": "0",
"WatchdogUSec": "0",
}
-''' # NOQA
+""" # NOQA
import os
diff --git a/lib/ansible/modules/sysvinit.py b/lib/ansible/modules/sysvinit.py
index 8788162819..22621975d0 100644
--- a/lib/ansible/modules/sysvinit.py
+++ b/lib/ansible/modules/sysvinit.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: sysvinit
author:
- "Ansible Core Team"
@@ -77,9 +77,9 @@ notes:
- The service names might vary by specific OS/distribution.
requirements:
- That the service managed has a corresponding init script.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Make sure apache2 is started
ansible.builtin.sysvinit:
name: apache2
@@ -100,9 +100,9 @@ EXAMPLES = '''
runlevels:
- 3
- 5
-'''
+"""
-RETURN = r'''
+RETURN = r"""
results:
description: results from actions taken
returned: always
@@ -131,7 +131,7 @@ results:
"stdout": "Stopping web server: apache2.\n"
}
}
-'''
+"""
import re
from time import sleep
diff --git a/lib/ansible/modules/tempfile.py b/lib/ansible/modules/tempfile.py
index 03176a4612..a9a8d64430 100644
--- a/lib/ansible/modules/tempfile.py
+++ b/lib/ansible/modules/tempfile.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: tempfile
version_added: "2.3"
@@ -53,7 +53,7 @@ seealso:
- module: ansible.windows.win_tempfile
author:
- Krzysztof Magosa (@krzysztof-magosa)
-'''
+"""
EXAMPLES = """
- name: Create temporary build directory
@@ -80,13 +80,13 @@ EXAMPLES = """
when: tempfile_1.path is defined
"""
-RETURN = '''
+RETURN = """
path:
description: Path to created file or directory.
returned: success
type: str
sample: "/tmp/ansible.bMlvdk"
-'''
+"""
from os import close
from tempfile import mkstemp, mkdtemp
diff --git a/lib/ansible/modules/template.py b/lib/ansible/modules/template.py
index 92c60d2b59..31f5f342c4 100644
--- a/lib/ansible/modules/template.py
+++ b/lib/ansible/modules/template.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: template
version_added: historical
@@ -60,9 +60,9 @@ attributes:
support: full
vault:
support: full
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Template a file to /etc/file.conf
ansible.builtin.template:
src: /mytemplates/foo.j2
@@ -108,9 +108,9 @@ EXAMPLES = r'''
mode: '0600'
validate: /usr/sbin/sshd -t -f %s
backup: yes
-'''
+"""
-RETURN = r'''
+RETURN = r"""
dest:
description: Destination file/path, equal to the value passed to I(dest).
returned: success
@@ -161,4 +161,4 @@ src:
returned: changed
type: str
sample: /home/httpd/.ansible/tmp/ansible-tmp-1423796390.97-147729857856000/source
-'''
+"""
diff --git a/lib/ansible/modules/unarchive.py b/lib/ansible/modules/unarchive.py
index 0d56da53a4..0b192ab569 100644
--- a/lib/ansible/modules/unarchive.py
+++ b/lib/ansible/modules/unarchive.py
@@ -10,7 +10,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: unarchive
version_added: '1.4'
@@ -150,9 +150,9 @@ seealso:
- module: community.general.iso_extract
- module: community.windows.win_unzip
author: Michael DeHaan
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Extract foo.tgz into /var/lib/foo
ansible.builtin.unarchive:
src: foo.tgz
@@ -177,9 +177,9 @@ EXAMPLES = r'''
extra_opts:
- --transform
- s/^xxx/yyy/
-'''
+"""
-RETURN = r'''
+RETURN = r"""
dest:
description: Path to the destination directory.
returned: always
@@ -237,7 +237,7 @@ uid:
returned: always
type: int
sample: 1000
-'''
+"""
import binascii
import codecs
@@ -280,7 +280,7 @@ SIZE_DIFF_RE = re.compile(r': Size differs$')
def crc32(path, buffer_size):
- ''' Return a CRC32 checksum of a file '''
+ """ Return a CRC32 checksum of a file """
crc = binascii.crc32(b'')
with open(path, 'rb') as f:
@@ -290,7 +290,7 @@ def crc32(path, buffer_size):
def shell_escape(string):
- ''' Quote meta-characters in the args for the unix shell '''
+ """ Quote meta-characters in the args for the unix shell """
return re.sub(r'([^A-Za-z0-9_])', r'\\\1', string)
@@ -321,7 +321,7 @@ class ZipArchive(object):
)
def _permstr_to_octal(self, modestr, umask):
- ''' Convert a Unix permission string (rw-r--r--) into a mode (0644) '''
+ """ Convert a Unix permission string (rw-r--r--) into a mode (0644) """
revstr = modestr[::-1]
mode = 0
for j in range(0, 3):
diff --git a/lib/ansible/modules/uri.py b/lib/ansible/modules/uri.py
index ab390bc2b9..b19628b9aa 100644
--- a/lib/ansible/modules/uri.py
+++ b/lib/ansible/modules/uri.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: uri
short_description: Interacts with webservices
@@ -250,9 +250,9 @@ seealso:
- module: ansible.windows.win_uri
author:
- Romeo Theriault (@romeotheriault)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Check that you can connect (GET) to a page and it returns a status 200
ansible.builtin.uri:
url: http://www.example.com
@@ -387,9 +387,9 @@ EXAMPLES = r'''
uri:
url: https://example.org
ciphers: '@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
# The return information includes all the HTTP headers in lower-case.
content:
description: The response body content.
@@ -438,7 +438,7 @@ url:
returned: always
type: str
sample: https://www.ansible.com/
-'''
+"""
import json
import os
@@ -527,7 +527,7 @@ def absolute_location(url, location):
def kv_list(data):
- ''' Convert data into a list of key-value tuples '''
+ """ Convert data into a list of key-value tuples """
if data is None:
return None
@@ -541,7 +541,7 @@ def kv_list(data):
def form_urlencoded(body):
- ''' Convert data into a form-urlencoded string '''
+ """ Convert data into a form-urlencoded string """
if isinstance(body, string_types):
return body
diff --git a/lib/ansible/modules/user.py b/lib/ansible/modules/user.py
index 27e2d0d235..3ea95e8875 100644
--- a/lib/ansible/modules/user.py
+++ b/lib/ansible/modules/user.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: user
version_added: "0.2"
short_description: Manage user accounts
@@ -319,9 +319,9 @@ seealso:
- module: ansible.windows.win_user
author:
- Stephen Fromm (@sfromm)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Add the user 'johnd' with a specific uid and a primary group of 'admin'
ansible.builtin.user:
name: johnd
@@ -385,9 +385,9 @@ EXAMPLES = r'''
ansible.builtin.user:
name: jimholden2016
password_expire_account_disable: 15
-'''
+"""
-RETURN = r'''
+RETURN = r"""
append:
description: Whether or not to append the user to groups.
returned: When O(state) is V(present) and the user exists
@@ -486,7 +486,7 @@ uid:
returned: When O(uid) is passed to the module
type: int
sample: 1044
-'''
+"""
import ctypes.util
@@ -1091,7 +1091,7 @@ class User(object):
return groups
def user_group_membership(self, exclude_primary=True):
- ''' Return a list of groups the user belongs to '''
+ """ Return a list of groups the user belongs to """
groups = []
info = self.get_pwd_info()
for group in grp.getgrall():
@@ -2423,7 +2423,7 @@ class DarwinUser(User):
return groups
def _get_user_property(self, property):
- '''Return user PROPERTY as given my dscl(1) read or None if not found.'''
+ """Return user PROPERTY as given my dscl(1) read or None if not found."""
cmd = self._get_dscl()
cmd += ['-read', '/Users/%s' % self.name, property]
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False)
@@ -2443,10 +2443,10 @@ class DarwinUser(User):
return None
def _get_next_uid(self, system=None):
- '''
+ """
Return the next available uid. If system=True, then
uid should be below of 500, if possible.
- '''
+ """
cmd = self._get_dscl()
cmd += ['-list', '/Users', 'UniqueID']
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False)
@@ -2472,10 +2472,10 @@ class DarwinUser(User):
return max_uid + 1
def _change_user_password(self):
- '''Change password for SELF.NAME against SELF.PASSWORD.
+ """Change password for SELF.NAME against SELF.PASSWORD.
Please note that password must be cleartext.
- '''
+ """
# some documentation on how is stored passwords on OSX:
# http://blog.lostpassword.com/2012/07/cracking-mac-os-x-lion-accounts-passwords/
# http://null-byte.wonderhowto.com/how-to/hack-mac-os-x-lion-passwords-0130036/
@@ -2494,7 +2494,7 @@ class DarwinUser(User):
return (rc, out, err)
def _make_group_numerical(self):
- '''Convert SELF.GROUP to is stringed numerical value suitable for dscl.'''
+ """Convert SELF.GROUP to is stringed numerical value suitable for dscl."""
if self.group is None:
self.group = 'nogroup'
try:
@@ -2505,8 +2505,8 @@ class DarwinUser(User):
self.group = str(self.group)
def __modify_group(self, group, action):
- '''Add or remove SELF.NAME to or from GROUP depending on ACTION.
- ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. '''
+ """Add or remove SELF.NAME to or from GROUP depending on ACTION.
+ ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. """
if action == 'add':
option = '-a'
else:
@@ -2519,8 +2519,8 @@ class DarwinUser(User):
return (rc, out, err)
def _modify_group(self):
- '''Add or remove SELF.NAME to or from GROUP depending on ACTION.
- ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. '''
+ """Add or remove SELF.NAME to or from GROUP depending on ACTION.
+ ACTION can be 'add' or 'remove' otherwise 'remove' is assumed. """
rc = 0
out = ''
@@ -2551,9 +2551,9 @@ class DarwinUser(User):
return (rc, out, err, changed)
def _update_system_user(self):
- '''Hide or show user on login window according SELF.SYSTEM.
+ """Hide or show user on login window according SELF.SYSTEM.
- Returns 0 if a change has been made, None otherwise.'''
+ Returns 0 if a change has been made, None otherwise."""
plist_file = '/Library/Preferences/com.apple.loginwindow.plist'
@@ -2592,14 +2592,14 @@ class DarwinUser(User):
return 0
def user_exists(self):
- '''Check is SELF.NAME is a known user on the system.'''
+ """Check is SELF.NAME is a known user on the system."""
cmd = self._get_dscl()
cmd += ['-read', '/Users/%s' % self.name, 'UniqueID']
(rc, out, err) = self.execute_command(cmd, obey_checkmode=False)
return rc == 0
def remove_user(self):
- '''Delete SELF.NAME. If SELF.FORCE is true, remove its home directory.'''
+ """Delete SELF.NAME. If SELF.FORCE is true, remove its home directory."""
info = self.user_info()
cmd = self._get_dscl()
diff --git a/lib/ansible/modules/validate_argument_spec.py b/lib/ansible/modules/validate_argument_spec.py
index 22246a7125..8c75e8abb4 100644
--- a/lib/ansible/modules/validate_argument_spec.py
+++ b/lib/ansible/modules/validate_argument_spec.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: validate_argument_spec
short_description: Validate role argument specs.
@@ -46,9 +46,9 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: verify vars needed for this task file are present when included
ansible.builtin.validate_argument_spec:
argument_spec: '{{ required_data }}'
@@ -82,9 +82,9 @@ EXAMPLES = r'''
vars:
stuff: knows
but: nobuts!
-'''
+"""
-RETURN = r'''
+RETURN = r"""
argument_errors:
description: A list of arg validation errors.
returned: failure
@@ -114,4 +114,4 @@ validate_args_context:
type: role
path: /home/user/roles/my_role/
argument_spec_name: main
-'''
+"""
diff --git a/lib/ansible/modules/wait_for.py b/lib/ansible/modules/wait_for.py
index 2230e6ee75..3b64142379 100644
--- a/lib/ansible/modules/wait_for.py
+++ b/lib/ansible/modules/wait_for.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: wait_for
short_description: Waits for a condition before continuing
@@ -120,9 +120,9 @@ author:
- Jeroen Hoekx (@jhoekx)
- John Jarvis (@jarv)
- Andrii Radyk (@AnderEnder)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Sleep for 300 seconds and continue with play
ansible.builtin.wait_for:
timeout: 300
@@ -198,9 +198,9 @@ EXAMPLES = r'''
delay: 10
vars:
ansible_connection: local
-'''
+"""
-RETURN = r'''
+RETURN = r"""
elapsed:
description: The number of seconds that elapsed while waiting
returned: always
@@ -220,7 +220,7 @@ match_groupdict:
{
'group': 'match'
}
-'''
+"""
import binascii
import contextlib
diff --git a/lib/ansible/modules/wait_for_connection.py b/lib/ansible/modules/wait_for_connection.py
index 8aeba019f8..8007b10ee2 100644
--- a/lib/ansible/modules/wait_for_connection.py
+++ b/lib/ansible/modules/wait_for_connection.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: wait_for_connection
short_description: Waits until remote system is reachable/usable
@@ -62,9 +62,9 @@ seealso:
- module: community.windows.win_wait_for_process
author:
- Dag Wieers (@dagwieers)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Wait 600 seconds for target connection to become reachable/usable
ansible.builtin.wait_for_connection:
@@ -110,12 +110,12 @@ EXAMPLES = r'''
- name: Gather facts for first time
ansible.builtin.setup:
-'''
+"""
-RETURN = r'''
+RETURN = r"""
elapsed:
description: The number of seconds that elapsed waiting for the connection to appear.
returned: always
type: float
sample: 23.1
-'''
+"""
diff --git a/lib/ansible/modules/yum_repository.py b/lib/ansible/modules/yum_repository.py
index e1e2423922..c63932f1e5 100644
--- a/lib/ansible/modules/yum_repository.py
+++ b/lib/ansible/modules/yum_repository.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: yum_repository
author: Jiri Tyr (@jtyr)
@@ -385,9 +385,9 @@ notes:
on disk until you run C(yum clean all). Use a notification handler for this.
- "The O(ignore:params) parameter was removed in Ansible 2.5 due to circumventing Ansible's parameter
handling"
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Add repository
ansible.builtin.yum_repository:
name: epel
@@ -427,9 +427,9 @@ EXAMPLES = '''
name: epel
file: external_repos
state: absent
-'''
+"""
-RETURN = '''
+RETURN = """
repo:
description: repository name
returned: success
@@ -440,7 +440,7 @@ state:
returned: success
type: str
sample: "present"
-'''
+"""
import configparser
import os
diff --git a/lib/ansible/parsing/dataloader.py b/lib/ansible/parsing/dataloader.py
index b2eaaafba5..47b6cfb12c 100644
--- a/lib/ansible/parsing/dataloader.py
+++ b/lib/ansible/parsing/dataloader.py
@@ -32,7 +32,7 @@ RE_TASKS = re.compile(u'(?:^|%s)+tasks%s?$' % (os.path.sep, os.path.sep))
class DataLoader:
- '''
+ """
The DataLoader class is used to load and parse YAML or JSON content,
either from a given file name or from a string that was previously
read in through other means. A Vault password can be specified, and
@@ -47,7 +47,7 @@ class DataLoader:
# optionally: dl.set_vault_secrets([('default', ansible.parsing.vault.PrompVaultSecret(...),)])
ds = dl.load('...')
ds = dl.load_from_file('/path/to/file')
- '''
+ """
def __init__(self):
@@ -74,11 +74,11 @@ class DataLoader:
self._vault.secrets = vault_secrets
def load(self, data: str, file_name: str = '<string>', show_content: bool = True, json_only: bool = False) -> t.Any:
- '''Backwards compat for now'''
+ """Backwards compat for now"""
return from_yaml(data, file_name, show_content, self._vault.secrets, json_only=json_only)
def load_from_file(self, file_name: str, cache: str = 'all', unsafe: bool = False, json_only: bool = False) -> t.Any:
- '''
+ """
Loads data from a file, which can contain either JSON or YAML.
:param file_name: The name of the file to load data from.
@@ -86,7 +86,7 @@ class DataLoader:
:param unsafe: If True, returns the parsed data as-is without deep copying.
:param json_only: If True, only loads JSON data from the file.
:return: The loaded data, optionally deep-copied for safety.
- '''
+ """
# Resolve the file name
file_name = self.path_dwim(file_name)
@@ -133,12 +133,12 @@ class DataLoader:
return os.listdir(path)
def is_executable(self, path: str) -> bool:
- '''is the given path executable?'''
+ """is the given path executable?"""
path = self.path_dwim(path)
return is_executable(path)
def _decrypt_if_vault_data(self, b_vault_data: bytes, b_file_name: bytes | None = None) -> tuple[bytes, bool]:
- '''Decrypt b_vault_data if encrypted and return b_data and the show_content flag'''
+ """Decrypt b_vault_data if encrypted and return b_data and the show_content flag"""
if not is_encrypted(b_vault_data):
show_content = True
@@ -151,7 +151,7 @@ class DataLoader:
return b_data, show_content
def _get_file_contents(self, file_name: str) -> tuple[bytes, bool]:
- '''
+ """
Reads the file contents from the given file name
If the contents are vault-encrypted, it will decrypt them and return
@@ -162,7 +162,7 @@ class DataLoader:
:raises AnsibleFileNotFound: if the file_name does not refer to a file
:raises AnsibleParserError: if we were unable to read the file
:return: Returns a byte string of the file contents
- '''
+ """
if not file_name or not isinstance(file_name, (binary_type, text_type)):
raise AnsibleParserError("Invalid filename: '%s'" % to_native(file_name))
@@ -180,19 +180,19 @@ class DataLoader:
raise AnsibleParserError("an error occurred while trying to read the file '%s': %s" % (file_name, to_native(e)), orig_exc=e)
def get_basedir(self) -> str:
- ''' returns the current basedir '''
+ """ returns the current basedir """
return self._basedir
def set_basedir(self, basedir: str) -> None:
- ''' sets the base directory, used to find files when a relative path is given '''
+ """ sets the base directory, used to find files when a relative path is given """
if basedir is not None:
self._basedir = to_text(basedir)
def path_dwim(self, given: str) -> str:
- '''
+ """
make relative paths work like folks expect.
- '''
+ """
given = unquote(given)
given = to_text(given, errors='surrogate_or_strict')
@@ -206,7 +206,7 @@ class DataLoader:
return unfrackpath(path, follow=False)
def _is_role(self, path: str) -> bool:
- ''' imperfect role detection, roles are still valid w/o tasks|meta/main.yml|yaml|etc '''
+ """ imperfect role detection, roles are still valid w/o tasks|meta/main.yml|yaml|etc """
b_path = to_bytes(path, errors='surrogate_or_strict')
b_path_dirname = os.path.dirname(b_path)
@@ -240,13 +240,13 @@ class DataLoader:
return False
def path_dwim_relative(self, path: str, dirname: str, source: str, is_role: bool = False) -> str:
- '''
+ """
find one file in either a role or playbook dir with or without
explicitly named dirname subdirs
Used in action plugins and lookups to find supplemental files that
could be in either place.
- '''
+ """
search = []
source = to_text(source, errors='surrogate_or_strict')
@@ -295,7 +295,7 @@ class DataLoader:
return candidate
def path_dwim_relative_stack(self, paths: list[str], dirname: str, source: str, is_role: bool = False) -> str:
- '''
+ """
find one file in first path in stack taking roles into account and adding play basedir as fallback
:arg paths: A list of text strings which are the paths to look for the filename in.
@@ -305,7 +305,7 @@ class DataLoader:
:rtype: A text string
:returns: An absolute path to the filename ``source`` if found
:raises: An AnsibleFileNotFound Exception if the file is found to exist in the search paths
- '''
+ """
b_dirname = to_bytes(dirname, errors='surrogate_or_strict')
b_source = to_bytes(source, errors='surrogate_or_strict')
@@ -353,7 +353,7 @@ class DataLoader:
return result
def _create_content_tempfile(self, content: str | bytes) -> str:
- ''' Create a tempfile containing defined content '''
+ """ Create a tempfile containing defined content """
fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
diff --git a/lib/ansible/parsing/mod_args.py b/lib/ansible/parsing/mod_args.py
index b4956bc3f9..aed543d095 100644
--- a/lib/ansible/parsing/mod_args.py
+++ b/lib/ansible/parsing/mod_args.py
@@ -132,12 +132,12 @@ class ModuleArgsParser:
self.resolved_action = None
def _split_module_string(self, module_string):
- '''
+ """
when module names are expressed like:
action: copy src=a dest=b
the first part of the string is the name of the module
and the rest are strings pertaining to the arguments.
- '''
+ """
tokens = split_args(module_string)
if len(tokens) > 1:
@@ -146,9 +146,9 @@ class ModuleArgsParser:
return (tokens[0].strip(), "")
def _normalize_parameters(self, thing, action=None, additional_args=None):
- '''
+ """
arguments can be fuzzy. Deal with all the forms.
- '''
+ """
additional_args = {} if additional_args is None else additional_args
@@ -205,7 +205,7 @@ class ModuleArgsParser:
return (action, final_args)
def _normalize_new_style_args(self, thing, action):
- '''
+ """
deals with fuzziness in new style module invocations
accepting key=value pairs and dictionaries, and returns
a dictionary of arguments
@@ -215,7 +215,7 @@ class ModuleArgsParser:
{'region': 'xyz'}, 'ec2'
standardized outputs like:
{ _raw_params: 'echo hi', _uses_shell: True }
- '''
+ """
if isinstance(thing, dict):
# form is like: { xyz: { x: 2, y: 3 } }
@@ -232,7 +232,7 @@ class ModuleArgsParser:
return args
def _normalize_old_style_args(self, thing):
- '''
+ """
deals with fuzziness in old-style (action/local_action) module invocations
returns tuple of (module_name, dictionary_args)
@@ -242,7 +242,7 @@ class ModuleArgsParser:
{'module': 'ec2', 'x': 1 }
standardized outputs like:
('ec2', { 'x': 1} )
- '''
+ """
action = None
args = None
@@ -270,11 +270,11 @@ class ModuleArgsParser:
return (action, args)
def parse(self, skip_action_validation=False):
- '''
+ """
Given a task in one of the supported forms, parses and returns
returns the action, arguments, and delegate_to values for the
task, dealing with all sorts of levels of fuzziness.
- '''
+ """
thing = None
diff --git a/lib/ansible/parsing/plugin_docs.py b/lib/ansible/parsing/plugin_docs.py
index 8b12086b8c..c18230806b 100644
--- a/lib/ansible/parsing/plugin_docs.py
+++ b/lib/ansible/parsing/plugin_docs.py
@@ -24,19 +24,19 @@ string_to_vars = {
def _var2string(value):
- ''' reverse lookup of the dict above '''
+ """ reverse lookup of the dict above """
for k, v in string_to_vars.items():
if v == value:
return k
def _init_doc_dict():
- ''' initialize a return dict for docs with the expected structure '''
+ """ initialize a return dict for docs with the expected structure """
return {k: None for k in string_to_vars.values()}
def read_docstring_from_yaml_file(filename, verbose=True, ignore_errors=True):
- ''' Read docs from 'sidecar' yaml file doc for a plugin '''
+ """ Read docs from 'sidecar' yaml file doc for a plugin """
data = _init_doc_dict()
file_data = {}
@@ -168,7 +168,7 @@ def read_docstring_from_python_file(filename, verbose=True, ignore_errors=True):
def read_docstring(filename, verbose=True, ignore_errors=True):
- ''' returns a documentation dictionary from Ansible plugin docstrings '''
+ """ returns a documentation dictionary from Ansible plugin docstrings """
# NOTE: adjacency of doc file to code file is responsibility of caller
if filename.endswith(C.YAML_DOC_EXTENSIONS):
diff --git a/lib/ansible/parsing/quoting.py b/lib/ansible/parsing/quoting.py
index 45e7fcbde9..6aaf09fc35 100644
--- a/lib/ansible/parsing/quoting.py
+++ b/lib/ansible/parsing/quoting.py
@@ -23,7 +23,7 @@ def is_quoted(data):
def unquote(data):
- ''' removes first and last quotes from a string, if the string starts and ends with the same quotes '''
+ """ removes first and last quotes from a string, if the string starts and ends with the same quotes """
if is_quoted(data):
return data[1:-1]
return data
diff --git a/lib/ansible/parsing/splitter.py b/lib/ansible/parsing/splitter.py
index a67524f4ad..3f61347a4a 100644
--- a/lib/ansible/parsing/splitter.py
+++ b/lib/ansible/parsing/splitter.py
@@ -28,13 +28,13 @@ from ansible.parsing.quoting import unquote
# Decode escapes adapted from rspeer's answer here:
# http://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python
_HEXCHAR = '[a-fA-F0-9]'
-_ESCAPE_SEQUENCE_RE = re.compile(r'''
+_ESCAPE_SEQUENCE_RE = re.compile(r"""
( \\U{0} # 8-digit hex escapes
| \\u{1} # 4-digit hex escapes
| \\x{2} # 2-digit hex escapes
| \\N\{{[^}}]+\}} # Unicode characters by name
| \\[\\'"abfnrtv] # Single-character escapes
- )'''.format(_HEXCHAR * 8, _HEXCHAR * 4, _HEXCHAR * 2), re.UNICODE | re.VERBOSE)
+ )""".format(_HEXCHAR * 8, _HEXCHAR * 4, _HEXCHAR * 2), re.UNICODE | re.VERBOSE)
def _decode_escapes(s):
@@ -45,12 +45,12 @@ def _decode_escapes(s):
def parse_kv(args, check_raw=False):
- '''
+ """
Convert a string of key/value items to a dict. If any free-form params
are found and the check_raw option is set to True, they will be added
to a new parameter called '_raw_params'. If check_raw is not enabled,
they will simply be ignored.
- '''
+ """
args = to_text(args, nonstring='passthru')
@@ -94,10 +94,10 @@ def parse_kv(args, check_raw=False):
def _get_quote_state(token, quote_char):
- '''
+ """
the goal of this block is to determine if the quoted string
is unterminated in which case it needs to be put back together
- '''
+ """
# the char before the current one, used to see if
# the current character is escaped
prev_char = None
@@ -114,11 +114,11 @@ def _get_quote_state(token, quote_char):
def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
- '''
+ """
this function counts the number of opening/closing blocks for a
given opening/closing type and adjusts the current depth for that
block based on the difference
- '''
+ """
num_open = token.count(open_token)
num_close = token.count(close_token)
if num_open != num_close:
@@ -129,10 +129,10 @@ def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
def join_args(s):
- '''
+ """
Join the original cmd based on manipulations by split_args().
This retains the original newlines and whitespaces.
- '''
+ """
result = ''
for p in s:
if len(result) == 0 or result.endswith('\n'):
@@ -143,7 +143,7 @@ def join_args(s):
def split_args(args):
- '''
+ """
Splits args on whitespace, but intelligently reassembles
those that may have been split over a jinja2 block or quotes.
@@ -156,7 +156,7 @@ def split_args(args):
Basically this is a variation shlex that has some more intelligence for
how Ansible needs to use it.
- '''
+ """
if not args:
return []
diff --git a/lib/ansible/parsing/utils/addresses.py b/lib/ansible/parsing/utils/addresses.py
index f15aae1ba9..33982d0485 100644
--- a/lib/ansible/parsing/utils/addresses.py
+++ b/lib/ansible/parsing/utils/addresses.py
@@ -23,21 +23,21 @@ from ansible.errors import AnsibleParserError, AnsibleError
# Components that match a numeric or alphanumeric begin:end or begin:end:step
# range expression inside square brackets.
-numeric_range = r'''
+numeric_range = r"""
\[
(?:[0-9]+:[0-9]+) # numeric begin:end
(?::[0-9]+)? # numeric :step (optional)
\]
-'''
+"""
-hexadecimal_range = r'''
+hexadecimal_range = r"""
\[
(?:[0-9a-f]+:[0-9a-f]+) # hexadecimal begin:end
(?::[0-9]+)? # numeric :step (optional)
\]
-'''
+"""
-alphanumeric_range = r'''
+alphanumeric_range = r"""
\[
(?:
[a-z]:[a-z]| # one-char alphabetic range
@@ -45,56 +45,56 @@ alphanumeric_range = r'''
)
(?::[0-9]+)? # numeric :step (optional)
\]
-'''
+"""
# Components that match a 16-bit portion of an IPv6 address in hexadecimal
# notation (0..ffff) or an 8-bit portion of an IPv4 address in decimal notation
# (0..255) or an [x:y(:z)] numeric range.
-ipv6_component = r'''
+ipv6_component = r"""
(?:
[0-9a-f]{{1,4}}| # 0..ffff
{range} # or a numeric range
)
-'''.format(range=hexadecimal_range)
+""".format(range=hexadecimal_range)
-ipv4_component = r'''
+ipv4_component = r"""
(?:
[01]?[0-9]{{1,2}}| # 0..199
2[0-4][0-9]| # 200..249
25[0-5]| # 250..255
{range} # or a numeric range
)
-'''.format(range=numeric_range)
+""".format(range=numeric_range)
# A hostname label, e.g. 'foo' in 'foo.example.com'. Consists of alphanumeric
# characters plus dashes (and underscores) or valid ranges. The label may not
# start or end with a hyphen or an underscore. This is interpolated into the
# hostname pattern below. We don't try to enforce the 63-char length limit.
-label = r'''
+label = r"""
(?:[\w]|{range}) # Starts with an alphanumeric or a range
(?:[\w_-]|{range})* # Then zero or more of the same or [_-]
(?<![_-]) # ...as long as it didn't end with [_-]
-'''.format(range=alphanumeric_range)
+""".format(range=alphanumeric_range)
patterns = {
# This matches a square-bracketed expression with a port specification. What
# is inside the square brackets is validated later.
'bracketed_hostport': re.compile(
- r'''^
+ r"""^
\[(.+)\] # [host identifier]
:([0-9]+) # :port number
$
- ''', re.X
+ """, re.X
),
# This matches a bare IPv4 address or hostname (or host pattern including
# [x:y(:z)] ranges) with a port specification.
'hostport': re.compile(
- r'''^
+ r"""^
((?: # We want to match:
[^:\[\]] # (a non-range character
| # ...or...
@@ -102,16 +102,16 @@ patterns = {
)*) # repeated as many times as possible
:([0-9]+) # followed by a port number
$
- ''', re.X
+ """, re.X
),
# This matches an IPv4 address, but also permits range expressions.
'ipv4': re.compile(
- r'''^
+ r"""^
(?:{i4}\.){{3}}{i4} # Three parts followed by dots plus one
$
- '''.format(i4=ipv4_component), re.X | re.I
+ """.format(i4=ipv4_component), re.X | re.I
),
# This matches an IPv6 address, but also permits range expressions.
@@ -125,7 +125,7 @@ patterns = {
# accept ranges in place of each component.
'ipv6': re.compile(
- r'''^
+ r"""^
(?:{0}:){{7}}{0}| # uncompressed: 1:2:3:4:5:6:7:8
(?:{0}:){{1,6}}:| # compressed variants, which are all
(?:{0}:)(?::{0}){{1,6}}| # a::b for various lengths of a,b
@@ -141,7 +141,7 @@ patterns = {
::(?:ffff:)?(?:{0}\.){{3}}{0}|
(?:0:){{5}}ffff:(?:{0}\.){{3}}{0}
$
- '''.format(ipv6_component), re.X | re.I
+ """.format(ipv6_component), re.X | re.I
),
# This matches a hostname or host pattern including [x:y(:z)] ranges.
@@ -155,11 +155,11 @@ patterns = {
# 253 characters total) or make any attempt to process IDNs.
'hostname': re.compile(
- r'''^
+ r"""^
{label} # We must have at least one label
(?:\.{label})* # Followed by zero or more .labels
$
- '''.format(label=label), re.X | re.I | re.UNICODE
+ """.format(label=label), re.X | re.I | re.UNICODE
),
}
diff --git a/lib/ansible/parsing/utils/jsonify.py b/lib/ansible/parsing/utils/jsonify.py
index 3be931c1f3..0ebd756409 100644
--- a/lib/ansible/parsing/utils/jsonify.py
+++ b/lib/ansible/parsing/utils/jsonify.py
@@ -21,7 +21,7 @@ import json
def jsonify(result, format=False):
- ''' format JSON output (uncompressed or uncompressed) '''
+ """ format JSON output (uncompressed or uncompressed) """
if result is None:
return "{}"
diff --git a/lib/ansible/parsing/utils/yaml.py b/lib/ansible/parsing/utils/yaml.py
index 98a9f94ff7..9462eba8aa 100644
--- a/lib/ansible/parsing/utils/yaml.py
+++ b/lib/ansible/parsing/utils/yaml.py
@@ -21,11 +21,11 @@ __all__ = ('from_yaml',)
def _handle_error(json_exc, yaml_exc, file_name, show_content):
- '''
+ """
Optionally constructs an object (AnsibleBaseYAMLObject) to encapsulate the
file name/position where a YAML exception occurred, and raises an AnsibleParserError
to display the syntax exception information.
- '''
+ """
# if the YAML exception contains a problem mark, use it to construct
# an object the error class can use to display the faulty line
@@ -42,7 +42,7 @@ def _handle_error(json_exc, yaml_exc, file_name, show_content):
def _safe_load(stream, file_name=None, vault_secrets=None):
- ''' Implements yaml.safe_load(), except using our custom loader class. '''
+ """ Implements yaml.safe_load(), except using our custom loader class. """
loader = AnsibleLoader(stream, file_name, vault_secrets)
try:
@@ -55,10 +55,10 @@ def _safe_load(stream, file_name=None, vault_secrets=None):
def from_yaml(data, file_name='<string>', show_content=True, vault_secrets=None, json_only=False):
- '''
+ """
Creates a python datastructure from the given data, which can be either
a JSON or YAML string.
- '''
+ """
new_data = None
try:
diff --git a/lib/ansible/parsing/vault/__init__.py b/lib/ansible/parsing/vault/__init__.py
index fb835bd3cf..e3121b5dbb 100644
--- a/lib/ansible/parsing/vault/__init__.py
+++ b/lib/ansible/parsing/vault/__init__.py
@@ -253,19 +253,19 @@ def parse_vaulttext(b_vaulttext):
def verify_secret_is_not_empty(secret, msg=None):
- '''Check the secret against minimal requirements.
+ """Check the secret against minimal requirements.
Raises: AnsibleVaultPasswordError if the password does not meet requirements.
Currently, only requirement is that the password is not None or an empty string.
- '''
+ """
msg = msg or 'Invalid vault password was provided'
if not secret:
raise AnsibleVaultPasswordError(msg)
class VaultSecret:
- '''Opaque/abstract objects for a single vault secret. ie, a password or a key.'''
+ """Opaque/abstract objects for a single vault secret. ie, a password or a key."""
def __init__(self, _bytes=None):
# FIXME: ? that seems wrong... Unset etc?
@@ -273,10 +273,10 @@ class VaultSecret:
@property
def bytes(self):
- '''The secret as a bytestring.
+ """The secret as a bytestring.
Sub classes that store text types will need to override to encode the text to bytes.
- '''
+ """
return self._bytes
def load(self):
@@ -335,7 +335,7 @@ class PromptVaultSecret(VaultSecret):
def script_is_client(filename):
- '''Determine if a vault secret script is a client script that can be given --vault-id args'''
+ """Determine if a vault secret script is a client script that can be given --vault-id args"""
# if password script is 'something-client' or 'something-client.[sh|py|rb|etc]'
# script_name can still have '.' or could be entire filename if there is no ext
@@ -349,7 +349,7 @@ def script_is_client(filename):
def get_file_vault_secret(filename=None, vault_id=None, encoding=None, loader=None):
- ''' Get secret from file content or execute file and get secret from stdout '''
+ """ Get secret from file content or execute file and get secret from stdout """
# we unfrack but not follow the full path/context to possible vault script
# so when the script uses 'adjacent' file for configuration or similar
@@ -519,7 +519,7 @@ class ClientScriptVaultSecret(ScriptVaultSecret):
def match_secrets(secrets, target_vault_ids):
- '''Find all VaultSecret objects that are mapped to any of the target_vault_ids in secrets'''
+ """Find all VaultSecret objects that are mapped to any of the target_vault_ids in secrets"""
if not secrets:
return []
@@ -528,10 +528,10 @@ def match_secrets(secrets, target_vault_ids):
def match_best_secret(secrets, target_vault_ids):
- '''Find the best secret from secrets that matches target_vault_ids
+ """Find the best secret from secrets that matches target_vault_ids
Since secrets should be ordered so the early secrets are 'better' than later ones, this
- just finds all the matches, then returns the first secret'''
+ just finds all the matches, then returns the first secret"""
matches = match_secrets(secrets, target_vault_ids)
if matches:
return matches[0]
@@ -560,7 +560,7 @@ def match_encrypt_vault_id_secret(secrets, encrypt_vault_id=None):
def match_encrypt_secret(secrets, encrypt_vault_id=None):
- '''Find the best/first/only secret in secrets to use for encrypting'''
+ """Find the best/first/only secret in secrets to use for encrypting"""
display.vvvv(u'encrypt_vault_id=%s' % to_text(encrypt_vault_id))
# See if the --encrypt-vault-id matches a vault-id
@@ -634,7 +634,7 @@ class VaultLib:
return b_vaulttext
def decrypt(self, vaulttext, filename=None, obj=None):
- '''Decrypt a piece of vault encrypted data.
+ """Decrypt a piece of vault encrypted data.
:arg vaulttext: a string to decrypt. Since vault encrypted data is an
ascii text format this can be either a byte str or unicode string.
@@ -643,7 +643,7 @@ class VaultLib:
decrypted.
:returns: a byte string containing the decrypted data and the vault-id that was used
- '''
+ """
plaintext, vault_id, vault_secret = self.decrypt_and_get_vault_id(vaulttext, filename=filename, obj=obj)
return plaintext
diff --git a/lib/ansible/parsing/yaml/dumper.py b/lib/ansible/parsing/yaml/dumper.py
index 11a1431b94..4888e4fd10 100644
--- a/lib/ansible/parsing/yaml/dumper.py
+++ b/lib/ansible/parsing/yaml/dumper.py
@@ -29,10 +29,10 @@ from ansible.vars.manager import VarsWithSources
class AnsibleDumper(SafeDumper):
- '''
+ """
A simple stub class that allows us to add representers
for our overridden object types.
- '''
+ """
def represent_hostvars(self, data):
diff --git a/lib/ansible/parsing/yaml/objects.py b/lib/ansible/parsing/yaml/objects.py
index 6ec4850b19..f3ebcb8fc0 100644
--- a/lib/ansible/parsing/yaml/objects.py
+++ b/lib/ansible/parsing/yaml/objects.py
@@ -26,11 +26,11 @@ from ansible.module_utils.common.text.converters import to_bytes, to_text, to_na
class AnsibleBaseYAMLObject(object):
- '''
+ """
the base class used to sub-class python built-in objects
so that we can add attributes to them during yaml parsing
- '''
+ """
_data_source = None
_line_number = 0
_column_number = 0
@@ -54,22 +54,22 @@ class AnsibleBaseYAMLObject(object):
class AnsibleMapping(AnsibleBaseYAMLObject, dict):
- ''' sub class for dictionaries '''
+ """ sub class for dictionaries """
pass
class AnsibleUnicode(AnsibleBaseYAMLObject, text_type):
- ''' sub class for unicode objects '''
+ """ sub class for unicode objects """
pass
class AnsibleSequence(AnsibleBaseYAMLObject, list):
- ''' sub class for lists '''
+ """ sub class for lists """
pass
class AnsibleVaultEncryptedUnicode(Sequence, AnsibleBaseYAMLObject):
- '''Unicode like object that is not evaluated (decrypted) until it needs to be'''
+ """Unicode like object that is not evaluated (decrypted) until it needs to be"""
__UNSAFE__ = True
__ENCRYPTED__ = True
yaml_tag = u'!vault'
@@ -85,13 +85,13 @@ class AnsibleVaultEncryptedUnicode(Sequence, AnsibleBaseYAMLObject):
return avu
def __init__(self, ciphertext):
- '''A AnsibleUnicode with a Vault attribute that can decrypt it.
+ """A AnsibleUnicode with a Vault attribute that can decrypt it.
ciphertext is a byte string (str on PY2, bytestring on PY3).
The .data attribute is a property that returns the decrypted plaintext
of the ciphertext as a PY2 unicode or PY3 string object.
- '''
+ """
super(AnsibleVaultEncryptedUnicode, self).__init__()
# after construction, calling code has to set the .vault attribute to a vaultlib object
diff --git a/lib/ansible/playbook/base.py b/lib/ansible/playbook/base.py
index 729344a205..a762548fdd 100644
--- a/lib/ansible/playbook/base.py
+++ b/lib/ansible/playbook/base.py
@@ -119,7 +119,7 @@ class FieldAttributeBase:
return self._finalized
def dump_me(self, depth=0):
- ''' this is never called from production code, it is here to be used when debugging as a 'complex print' '''
+ """ this is never called from production code, it is here to be used when debugging as a 'complex print' """
if depth == 0:
display.debug("DUMPING OBJECT ------------------------------------------------------")
display.debug("%s- %s (%s, id=%s)" % (" " * depth, self.__class__.__name__, self, id(self)))
@@ -133,11 +133,11 @@ class FieldAttributeBase:
self._play.dump_me(depth + 2)
def preprocess_data(self, ds):
- ''' infrequently used method to do some pre-processing of legacy terms '''
+ """ infrequently used method to do some pre-processing of legacy terms """
return ds
def load_data(self, ds, variable_manager=None, loader=None):
- ''' walk the input datastructure and assign any values '''
+ """ walk the input datastructure and assign any values """
if ds is None:
raise AnsibleAssertionError('ds (%s) should not be None but it is.' % ds)
@@ -198,10 +198,10 @@ class FieldAttributeBase:
return value
def _validate_attributes(self, ds):
- '''
+ """
Ensures that there are no keys in the datastructure which do
not map to attributes for this object.
- '''
+ """
valid_attrs = frozenset(self.fattributes)
for key in ds:
@@ -209,7 +209,7 @@ class FieldAttributeBase:
raise AnsibleParserError("'%s' is not a valid attribute for a %s" % (key, self.__class__.__name__), obj=ds)
def validate(self, all_vars=None):
- ''' validation that is done at parse time, not load time '''
+ """ validation that is done at parse time, not load time """
all_vars = {} if all_vars is None else all_vars
if not self._validated:
@@ -402,20 +402,20 @@ class FieldAttributeBase:
display.vvvvv("Could not resolve action %s in module_defaults" % action_name)
def squash(self):
- '''
+ """
Evaluates all attributes and sets them to the evaluated version,
so that all future accesses of attributes do not need to evaluate
parent attributes.
- '''
+ """
if not self._squashed:
for name in self.fattributes:
setattr(self, name, getattr(self, name))
self._squashed = True
def copy(self):
- '''
+ """
Create a copy of this object and return it.
- '''
+ """
try:
new_me = self.__class__()
@@ -497,7 +497,7 @@ class FieldAttributeBase:
return value
def set_to_context(self, name):
- ''' set to parent inherited value or Sentinel as appropriate'''
+ """ set to parent inherited value or Sentinel as appropriate"""
attribute = self.fattributes[name]
if isinstance(attribute, NonInheritableFieldAttribute):
@@ -511,11 +511,11 @@ class FieldAttributeBase:
setattr(self, name, Sentinel)
def post_validate(self, templar):
- '''
+ """
we can't tell that everything is of the right type until we have
all the variables. Run basic types (from isa) as well as
any _post_validate_<foo> functions.
- '''
+ """
# save the omit value for later checking
omit_value = templar.available_variables.get('omit')
@@ -580,9 +580,9 @@ class FieldAttributeBase:
self._finalized = True
def _load_vars(self, attr, ds):
- '''
+ """
Vars in a play must be specified as a dictionary.
- '''
+ """
def _validate_variable_keys(ds):
for key in ds:
@@ -604,11 +604,11 @@ class FieldAttributeBase:
raise AnsibleParserError("Invalid variable name in vars specified for %s: %s" % (self.__class__.__name__, e), obj=ds, orig_exc=e)
def _extend_value(self, value, new_value, prepend=False):
- '''
+ """
Will extend the value given with new_value (and will turn both
into lists if they are not so already). The values are run through
a set to remove duplicate values.
- '''
+ """
if not isinstance(value, list):
value = [value]
@@ -629,9 +629,9 @@ class FieldAttributeBase:
return [i for i, dummy in itertools.groupby(combined) if i is not None]
def dump_attrs(self):
- '''
+ """
Dumps all attributes to a dictionary
- '''
+ """
attrs = {}
for (name, attribute) in self.fattributes.items():
attr = getattr(self, name)
@@ -642,9 +642,9 @@ class FieldAttributeBase:
return attrs
def from_attrs(self, attrs):
- '''
+ """
Loads attributes from a dictionary
- '''
+ """
for (attr, value) in attrs.items():
if attr in self.fattributes:
attribute = self.fattributes[attr]
@@ -663,13 +663,13 @@ class FieldAttributeBase:
self._squashed = True
def serialize(self):
- '''
+ """
Serializes the object derived from the base object into
a dictionary of values. This only serializes the field
attributes for the object, so this may need to be overridden
for any classes which wish to add additional items not stored
as field attributes.
- '''
+ """
repr = self.dump_attrs()
@@ -681,12 +681,12 @@ class FieldAttributeBase:
return repr
def deserialize(self, data):
- '''
+ """
Given a dictionary of values, load up the field attributes for
this object. As with serialize(), if there are any non-field
attribute data members, this method will need to be overridden
and extended.
- '''
+ """
if not isinstance(data, dict):
raise AnsibleAssertionError('data (%s) should be a dict but is a %s' % (data, type(data)))
@@ -744,7 +744,7 @@ class Base(FieldAttributeBase):
DEPRECATED_ATTRIBUTES = [] # type: list[str]
def get_path(self):
- ''' return the absolute path of the playbook object and its line number '''
+ """ return the absolute path of the playbook object and its line number """
path = ""
try:
@@ -764,10 +764,10 @@ class Base(FieldAttributeBase):
return None
def get_search_path(self):
- '''
+ """
Return the list of paths you should search for files, in order.
This follows role/playbook dependency chain.
- '''
+ """
path_stack = []
dep_chain = self.get_dep_chain()
diff --git a/lib/ansible/playbook/block.py b/lib/ansible/playbook/block.py
index fa8c13ee49..f7dd8994e2 100644
--- a/lib/ansible/playbook/block.py
+++ b/lib/ansible/playbook/block.py
@@ -61,18 +61,18 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
return "BLOCK(uuid=%s)(id=%s)(parent=%s)" % (self._uuid, id(self), self._parent)
def __eq__(self, other):
- '''object comparison based on _uuid'''
+ """object comparison based on _uuid"""
return self._uuid == other._uuid
def __ne__(self, other):
- '''object comparison based on _uuid'''
+ """object comparison based on _uuid"""
return self._uuid != other._uuid
def get_vars(self):
- '''
+ """
Blocks do not store variables directly, however they may be a member
of a role or task include which does, so return those if present.
- '''
+ """
all_vars = {}
@@ -100,10 +100,10 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
return is_block
def preprocess_data(self, ds):
- '''
+ """
If a simple task is given, an implicit block for that single task
is created, which goes in the main portion of the block
- '''
+ """
if not Block.is_block(ds):
if isinstance(ds, list):
@@ -219,10 +219,10 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
return new_me
def serialize(self):
- '''
+ """
Override of the default serialize method, since when we're serializing
a task we don't want to include the attribute list of tasks.
- '''
+ """
data = dict()
for attr in self.fattributes:
@@ -240,10 +240,10 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
return data
def deserialize(self, data):
- '''
+ """
Override of the default deserialize method, to match the above overridden
serialize method
- '''
+ """
# import is here to avoid import loops
from ansible.playbook.task_include import TaskInclude
@@ -290,9 +290,9 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
dep.set_loader(loader)
def _get_parent_attribute(self, attr, omit=False):
- '''
+ """
Generic logic to get the attribute or parent attribute for a block value.
- '''
+ """
fattr = self.fattributes[attr]
extend = fattr.extend
@@ -363,9 +363,9 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
return value
def filter_tagged_tasks(self, all_vars):
- '''
+ """
Creates a new block, with task lists filtered based on the tags.
- '''
+ """
def evaluate_and_append_task(target):
tmp_list = []
@@ -417,12 +417,12 @@ class Block(Base, Conditional, CollectionSearch, Taggable, Notifiable, Delegatab
return dict()
def all_parents_static(self):
- '''
+ """
Determine if all of the parents of this block were statically loaded
or not. Since Task/TaskInclude objects may be in the chain, they simply
call their parents all_parents_static() method. Only Block objects in
the chain check the statically_loaded value of the parent.
- '''
+ """
from ansible.playbook.task_include import TaskInclude
if self._parent:
if isinstance(self._parent, TaskInclude) and not self._parent.statically_loaded:
diff --git a/lib/ansible/playbook/conditional.py b/lib/ansible/playbook/conditional.py
index 43cf99f297..21a9cf4c17 100644
--- a/lib/ansible/playbook/conditional.py
+++ b/lib/ansible/playbook/conditional.py
@@ -29,10 +29,10 @@ display = Display()
class Conditional:
- '''
+ """
This is a mix-in class, to be used with Base to allow the object
to be run conditionally when a condition is met or skipped.
- '''
+ """
when = FieldAttribute(isa='list', default=list, extend=True, prepend=True)
@@ -52,10 +52,10 @@ class Conditional:
setattr(self, name, [value])
def evaluate_conditional(self, templar: Templar, all_vars: dict[str, t.Any]) -> bool:
- '''
+ """
Loops through the conditionals set on this object, returning
False if any of them evaluate as such.
- '''
+ """
return self.evaluate_conditional_with_result(templar, all_vars)[0]
def evaluate_conditional_with_result(self, templar: Templar, all_vars: dict[str, t.Any]) -> tuple[bool, t.Optional[str]]:
diff --git a/lib/ansible/playbook/handler.py b/lib/ansible/playbook/handler.py
index a7b4a5388b..c9cba6a6c3 100644
--- a/lib/ansible/playbook/handler.py
+++ b/lib/ansible/playbook/handler.py
@@ -34,7 +34,7 @@ class Handler(Task):
super(Handler, self).__init__(block=block, role=role, task_include=task_include)
def __repr__(self):
- ''' returns a human-readable representation of the handler '''
+ """ returns a human-readable representation of the handler """
return "HANDLER: %s" % self.get_name()
def _validate_listen(self, attr, name, value):
diff --git a/lib/ansible/playbook/helpers.py b/lib/ansible/playbook/helpers.py
index f0ef498d19..6686d4f242 100644
--- a/lib/ansible/playbook/helpers.py
+++ b/lib/ansible/playbook/helpers.py
@@ -29,11 +29,11 @@ display = Display()
def load_list_of_blocks(ds, play, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
- '''
+ """
Given a list of mixed task/block data (parsed from YAML),
return a list of Block() objects, where implicit blocks
are created for each bare Task.
- '''
+ """
# we import here to prevent a circular dependency with imports
from ansible.playbook.block import Block
@@ -80,10 +80,10 @@ def load_list_of_blocks(ds, play, parent_block=None, role=None, task_include=Non
def load_list_of_tasks(ds, play, block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None):
- '''
+ """
Given a list of task datastructures (parsed from YAML),
return a list of Task() or TaskInclude() objects.
- '''
+ """
# we import here to prevent a circular dependency with imports
from ansible.playbook.block import Block
diff --git a/lib/ansible/playbook/loop_control.py b/lib/ansible/playbook/loop_control.py
index f7783f0f3c..c8e9af0e23 100644
--- a/lib/ansible/playbook/loop_control.py
+++ b/lib/ansible/playbook/loop_control.py
@@ -40,8 +40,8 @@ class LoopControl(FieldAttributeBase):
return t.load_data(data, variable_manager=variable_manager, loader=loader)
def _post_validate_break_when(self, attr, value, templar):
- '''
+ """
break_when is evaluated after the execution of the loop is complete,
and should not be templated during the regular post_validate step.
- '''
+ """
return value
diff --git a/lib/ansible/playbook/play.py b/lib/ansible/playbook/play.py
index aea7ba5a80..a76365bfcc 100644
--- a/lib/ansible/playbook/play.py
+++ b/lib/ansible/playbook/play.py
@@ -127,7 +127,7 @@ class Play(Base, Taggable, CollectionSearch):
raise AnsibleParserError("Hosts list must be a sequence or string. Please check your playbook.")
def get_name(self):
- ''' return the name of the Play '''
+ """ return the name of the Play """
if self.name:
return self.name
@@ -146,9 +146,9 @@ class Play(Base, Taggable, CollectionSearch):
return p.load_data(data, variable_manager=variable_manager, loader=loader)
def preprocess_data(self, ds):
- '''
+ """
Adjusts play datastructure to cleanup old/legacy items
- '''
+ """
if not isinstance(ds, dict):
raise AnsibleAssertionError('while preprocessing data (%s), ds should be a dict but was a %s' % (ds, type(ds)))
@@ -169,40 +169,40 @@ class Play(Base, Taggable, CollectionSearch):
return super(Play, self).preprocess_data(ds)
def _load_tasks(self, attr, ds):
- '''
+ """
Loads a list of blocks from a list which may be mixed tasks/blocks.
Bare tasks outside of a block are given an implicit block.
- '''
+ """
try:
return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading tasks: %s" % to_native(e), obj=self._ds, orig_exc=e)
def _load_pre_tasks(self, attr, ds):
- '''
+ """
Loads a list of blocks from a list which may be mixed tasks/blocks.
Bare tasks outside of a block are given an implicit block.
- '''
+ """
try:
return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading pre_tasks", obj=self._ds, orig_exc=e)
def _load_post_tasks(self, attr, ds):
- '''
+ """
Loads a list of blocks from a list which may be mixed tasks/blocks.
Bare tasks outside of a block are given an implicit block.
- '''
+ """
try:
return load_list_of_blocks(ds=ds, play=self, variable_manager=self._variable_manager, loader=self._loader)
except AssertionError as e:
raise AnsibleParserError("A malformed block was encountered while loading post_tasks", obj=self._ds, orig_exc=e)
def _load_handlers(self, attr, ds):
- '''
+ """
Loads a list of blocks from a list which may be mixed handlers/blocks.
Bare handlers outside of a block are given an implicit block.
- '''
+ """
try:
return self._extend_value(
self.handlers,
@@ -213,10 +213,10 @@ class Play(Base, Taggable, CollectionSearch):
raise AnsibleParserError("A malformed block was encountered while loading handlers", obj=self._ds, orig_exc=e)
def _load_roles(self, attr, ds):
- '''
+ """
Loads and returns a list of RoleInclude objects from the datastructure
list of role definitions and creates the Role from those objects
- '''
+ """
if ds is None:
ds = []
@@ -249,13 +249,13 @@ class Play(Base, Taggable, CollectionSearch):
return vars_prompts
def _compile_roles(self):
- '''
+ """
Handles the role compilation step, returning a flat list of tasks
with the lowest level dependencies first. For example, if a role R
has a dependency D1, which also has a dependency D2, the tasks from
D2 are merged first, followed by D1, and lastly by the tasks from
the parent role R last. This is done for all roles in the Play.
- '''
+ """
block_list = []
@@ -270,10 +270,10 @@ class Play(Base, Taggable, CollectionSearch):
return block_list
def compile_roles_handlers(self):
- '''
+ """
Handles the role handler compilation step, returning a flat list of Handlers
This is done for all roles in the Play.
- '''
+ """
block_list = []
@@ -286,11 +286,11 @@ class Play(Base, Taggable, CollectionSearch):
return block_list
def compile(self):
- '''
+ """
Compiles and returns the task list for this play, compiled from the
roles (which are themselves compiled recursively) and/or the list of
tasks specified in the play.
- '''
+ """
# create a block containing a single flush handlers meta
# task, so we can be sure to run handlers at certain points
# of the playbook execution
diff --git a/lib/ansible/playbook/play_context.py b/lib/ansible/playbook/play_context.py
index 2fe9539322..e384ce0fb2 100644
--- a/lib/ansible/playbook/play_context.py
+++ b/lib/ansible/playbook/play_context.py
@@ -65,11 +65,11 @@ RESET_VARS = (
class PlayContext(Base):
- '''
+ """
This class is used to consolidate the connection information for
hosts in a play and child tasks, where the task may override some
connection/authentication information.
- '''
+ """
# base
module_compression = FieldAttribute(isa='string', default=C.DEFAULT_MODULE_COMPRESSION)
@@ -158,11 +158,11 @@ class PlayContext(Base):
self.force_handlers = play.force_handlers
def set_attributes_from_cli(self):
- '''
+ """
Configures this connection information instance with data from
options specified by the user on the command line. These have a
lower precedence than those set on the play or host.
- '''
+ """
if context.CLIARGS.get('timeout', False):
self.timeout = int(context.CLIARGS['timeout'])
@@ -175,14 +175,14 @@ class PlayContext(Base):
self.start_at_task = context.CLIARGS.get('start_at_task', None) # Else default
def set_task_and_variable_override(self, task, variables, templar):
- '''
+ """
Sets attributes from the task if they are set, which will override
those from the play.
:arg task: the task object with the parameters that were set on it
:arg variables: variables from inventory
:arg templar: templar instance if templating variables is needed
- '''
+ """
new_info = self.copy()
@@ -312,10 +312,10 @@ class PlayContext(Base):
self._become_plugin = plugin
def update_vars(self, variables):
- '''
+ """
Adds 'magic' variables relating to connections to the variable dictionary provided.
In case users need to access from the play, this is a legacy from runner.
- '''
+ """
for prop, var_list in C.MAGIC_VARIABLE_MAPPING.items():
try:
diff --git a/lib/ansible/playbook/playbook_include.py b/lib/ansible/playbook/playbook_include.py
index 8f1e03d7e7..8e7c6c0508 100644
--- a/lib/ansible/playbook/playbook_include.py
+++ b/lib/ansible/playbook/playbook_include.py
@@ -47,10 +47,10 @@ class PlaybookInclude(Base, Conditional, Taggable):
return PlaybookInclude().load_data(ds=data, basedir=basedir, variable_manager=variable_manager, loader=loader)
def load_data(self, ds, variable_manager=None, loader=None, basedir=None):
- '''
+ """
Overrides the base load_data(), as we're actually going to return a new
Playbook() object rather than a PlaybookInclude object
- '''
+ """
# import here to avoid a dependency loop
from ansible.playbook import Playbook
@@ -122,10 +122,10 @@ class PlaybookInclude(Base, Conditional, Taggable):
return pb
def preprocess_data(self, ds):
- '''
+ """
Reorganizes the data for a PlaybookInclude datastructure to line
up with what we expect the proper attributes to be
- '''
+ """
if not isinstance(ds, dict):
raise AnsibleAssertionError('ds (%s) should be a dict but was a %s' % (ds, type(ds)))
@@ -152,9 +152,9 @@ class PlaybookInclude(Base, Conditional, Taggable):
return super(PlaybookInclude, self).preprocess_data(new_ds)
def _preprocess_import(self, ds, new_ds, k, v):
- '''
+ """
Splits the playbook import line up into filename and parameters
- '''
+ """
if v is None:
raise AnsibleParserError("playbook import parameter is missing", obj=ds)
elif not isinstance(v, string_types):
diff --git a/lib/ansible/playbook/role/__init__.py b/lib/ansible/playbook/role/__init__.py
index 05e6bef044..0887a77d7a 100644
--- a/lib/ansible/playbook/role/__init__.py
+++ b/lib/ansible/playbook/role/__init__.py
@@ -316,7 +316,7 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
return getattr(self._metadata, 'argument_specs', {})
def _prepend_validation_task(self, task_data, argspecs):
- '''Insert a role validation task if we have a role argument spec.
+ """Insert a role validation task if we have a role argument spec.
This method will prepend a validation task to the front of the role task
list to perform argument spec validation before any other tasks, if an arg spec
@@ -326,7 +326,7 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
:param argspecs: The role argument spec data dict.
:returns: The (possibly modified) task list.
- '''
+ """
if argspecs:
# Determine the role entry point so we can retrieve the correct argument spec.
# This comes from the `tasks_from` value to include_role or import_role.
@@ -345,13 +345,13 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
return task_data
def _create_validation_task(self, argument_spec, entrypoint_name):
- '''Create a new task data structure that uses the validate_argument_spec action plugin.
+ """Create a new task data structure that uses the validate_argument_spec action plugin.
:param argument_spec: The arg spec definition for a particular role entry point.
This will be the entire arg spec for the entry point as read from the input file.
:param entrypoint_name: The name of the role entry point associated with the
supplied `argument_spec`.
- '''
+ """
# If the arg spec provides a short description, use it to flesh out the validation task name
task_name = "Validating arguments against arg spec '%s'" % entrypoint_name
@@ -376,7 +376,7 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
}
def _load_role_yaml(self, subdir, main=None, allow_dir=False):
- '''
+ """
Find and load role YAML files and return data found.
:param subdir: subdir of role to search (vars, files, tasks, handlers, defaults)
:type subdir: string
@@ -387,7 +387,7 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
:type allow_dir: bool
:returns: data from the matched file(s), type can be dict or list depending on vars or tasks.
- '''
+ """
data = None
file_path = os.path.join(self._role_path, subdir)
if self._loader.path_exists(file_path) and self._loader.is_directory(file_path):
@@ -430,10 +430,10 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
return data
def _load_dependencies(self):
- '''
+ """
Recursively loads role dependencies from the metadata list of
dependencies, if it exists
- '''
+ """
deps = []
for role_include in self._metadata.dependencies:
@@ -445,7 +445,7 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
# other functions
def add_parent(self, parent_role):
- ''' adds a role to the list of this roles parents '''
+ """ adds a role to the list of this roles parents """
if not isinstance(parent_role, Role):
raise AnsibleAssertionError()
@@ -533,10 +533,10 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
return self._dependencies[:]
def get_all_dependencies(self):
- '''
+ """
Returns a list of all deps, built recursively from all child dependencies,
in the proper order in which they should be executed or evaluated.
- '''
+ """
if self._all_dependencies is None:
self._all_dependencies = []
@@ -579,15 +579,15 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
return block_list
def has_run(self, host):
- '''
+ """
Returns true if this role has been iterated over completely and
at least one task was run
- '''
+ """
return host.name in self._completed
def compile(self, play, dep_chain=None):
- '''
+ """
Returns the task list for this role, which is created by first
recursively compiling the tasks for all direct dependencies, and
then adding on the tasks for this role.
@@ -595,7 +595,7 @@ class Role(Base, Conditional, Taggable, CollectionSearch, Delegatable):
The role compile() also remembers and saves the dependency chain
with each task, so tasks know by which route they were found, and
can correctly take their parent's tags/conditionals into account.
- '''
+ """
from ansible.playbook.block import Block
from ansible.playbook.task import Task
diff --git a/lib/ansible/playbook/role/definition.py b/lib/ansible/playbook/role/definition.py
index 12d6ce182c..50758869b3 100644
--- a/lib/ansible/playbook/role/definition.py
+++ b/lib/ansible/playbook/role/definition.py
@@ -110,11 +110,11 @@ class RoleDefinition(Base, Conditional, Taggable, CollectionSearch):
return new_ds
def _load_role_name(self, ds):
- '''
+ """
Returns the role name (either the role: or name: field) from
the role definition, or (when the role definition is a simple
string), just that string
- '''
+ """
if isinstance(ds, string_types):
return ds
@@ -133,12 +133,12 @@ class RoleDefinition(Base, Conditional, Taggable, CollectionSearch):
return role_name
def _load_role_path(self, role_name):
- '''
+ """
the 'role', as specified in the ds (or as a bare string), can either
be a simple name or a full path. If it is a full path, we use the
basename as the role name, otherwise we take the name as-given and
append it to the default role path
- '''
+ """
# create a templar class to template the dependency names, in
# case they contain variables
@@ -201,10 +201,10 @@ class RoleDefinition(Base, Conditional, Taggable, CollectionSearch):
raise AnsibleError("the role '%s' was not found in %s" % (role_name, ":".join(searches)), obj=self._ds)
def _split_role_params(self, ds):
- '''
+ """
Splits any random role params off from the role spec and store
them in a dictionary of params for parsing later
- '''
+ """
role_def = dict()
role_params = dict()
diff --git a/lib/ansible/playbook/role/metadata.py b/lib/ansible/playbook/role/metadata.py
index 482539a75d..6606d862c9 100644
--- a/lib/ansible/playbook/role/metadata.py
+++ b/lib/ansible/playbook/role/metadata.py
@@ -32,10 +32,10 @@ __all__ = ['RoleMetadata']
class RoleMetadata(Base, CollectionSearch):
- '''
+ """
This class wraps the parsing and validation of the optional metadata
within each Role (meta/main.yml).
- '''
+ """
allow_duplicates = NonInheritableFieldAttribute(isa='bool', default=False)
dependencies = NonInheritableFieldAttribute(isa='list', default=list)
@@ -48,9 +48,9 @@ class RoleMetadata(Base, CollectionSearch):
@staticmethod
def load(data, owner, variable_manager=None, loader=None):
- '''
+ """
Returns a new RoleMetadata object based on the datastructure passed in.
- '''
+ """
if not isinstance(data, dict):
raise AnsibleParserError("the 'meta/main.yml' for role %s is not a dictionary" % owner.get_name())
@@ -59,10 +59,10 @@ class RoleMetadata(Base, CollectionSearch):
return m
def _load_dependencies(self, attr, ds):
- '''
+ """
This is a helper loading function for the dependencies list,
which returns a list of RoleInclude objects
- '''
+ """
roles = []
if ds:
diff --git a/lib/ansible/playbook/role_include.py b/lib/ansible/playbook/role_include.py
index 628f26ec0a..1894d6df8f 100644
--- a/lib/ansible/playbook/role_include.py
+++ b/lib/ansible/playbook/role_include.py
@@ -61,7 +61,7 @@ class IncludeRole(TaskInclude):
self._role_path = None
def get_name(self):
- ''' return the name of the task '''
+ """ return the name of the task """
return self.name or "%s : %s" % (self.action, self._role_name)
def get_block_list(self, play=None, variable_manager=None, loader=None):
diff --git a/lib/ansible/playbook/taggable.py b/lib/ansible/playbook/taggable.py
index 3b481270a6..79810a41ea 100644
--- a/lib/ansible/playbook/taggable.py
+++ b/lib/ansible/playbook/taggable.py
@@ -48,7 +48,7 @@ class Taggable:
raise AnsibleError('tags must be specified as a list', obj=ds)
def evaluate_tags(self, only_tags, skip_tags, all_vars):
- ''' this checks if the current item should be executed depending on tag options '''
+ """ this checks if the current item should be executed depending on tag options """
if self.tags:
templar = Templar(loader=self._loader, variables=all_vars)
diff --git a/lib/ansible/playbook/task.py b/lib/ansible/playbook/task.py
index d42e1df77e..3f43bfbe7c 100644
--- a/lib/ansible/playbook/task.py
+++ b/lib/ansible/playbook/task.py
@@ -86,7 +86,7 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
loop_with = NonInheritableFieldAttribute(isa='string', private=True)
def __init__(self, block=None, role=None, task_include=None):
- ''' constructors a task, without the Task.load classmethod, it will be pretty blank '''
+ """ constructors a task, without the Task.load classmethod, it will be pretty blank """
self._role = role
self._parent = None
@@ -101,7 +101,7 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
super(Task, self).__init__()
def get_name(self, include_role_fqcn=True):
- ''' return the name of the task '''
+ """ return the name of the task """
if self._role:
role_name = self._role.get_name(include_role_fqcn=include_role_fqcn)
@@ -136,14 +136,14 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
return t.load_data(data, variable_manager=variable_manager, loader=loader)
def __repr__(self):
- ''' returns a human-readable representation of the task '''
+ """ returns a human-readable representation of the task """
if self.action in C._ACTION_META:
return "TASK: meta (%s)" % self.args['_raw_params']
else:
return "TASK: %s" % self.get_name()
def _preprocess_with_loop(self, ds, new_ds, k, v):
- ''' take a lookup plugin name and store it correctly '''
+ """ take a lookup plugin name and store it correctly """
loop_name = k.removeprefix("with_")
if new_ds.get('loop') is not None or new_ds.get('loop_with') is not None:
@@ -156,10 +156,10 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
# version="2.10", collection_name='ansible.builtin')
def preprocess_data(self, ds):
- '''
+ """
tasks are especially complex arguments so need pre-processing.
keep it short.
- '''
+ """
if not isinstance(ds, dict):
raise AnsibleAssertionError('ds (%s) should be a dict but was a %s' % (ds, type(ds)))
@@ -281,10 +281,10 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
raise AnsibleParserError(f"Invalid variable name in 'register' specified: '{value}'")
def post_validate(self, templar):
- '''
+ """
Override of base class post_validate, to also do final validation on
the block and task include (if any) to which this task belongs.
- '''
+ """
if self._parent:
self._parent.post_validate(templar)
@@ -295,17 +295,17 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
super(Task, self).post_validate(templar)
def _post_validate_loop(self, attr, value, templar):
- '''
+ """
Override post validation for the loop field, which is templated
specially in the TaskExecutor class when evaluating loops.
- '''
+ """
return value
def _post_validate_environment(self, attr, value, templar):
- '''
+ """
Override post validation of vars on the play, as we don't want to
template these too early.
- '''
+ """
env = {}
if value is not None:
@@ -343,24 +343,24 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
return env
def _post_validate_changed_when(self, attr, value, templar):
- '''
+ """
changed_when is evaluated after the execution of the task is complete,
and should not be templated during the regular post_validate step.
- '''
+ """
return value
def _post_validate_failed_when(self, attr, value, templar):
- '''
+ """
failed_when is evaluated after the execution of the task is complete,
and should not be templated during the regular post_validate step.
- '''
+ """
return value
def _post_validate_until(self, attr, value, templar):
- '''
+ """
until is evaluated after the execution of the task is complete,
and should not be templated during the regular post_validate step.
- '''
+ """
return value
def get_vars(self):
@@ -450,11 +450,11 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
super(Task, self).deserialize(data)
def set_loader(self, loader):
- '''
+ """
Sets the loader on this object and recursively on parent, child objects.
This is used primarily after the Task has been serialized/deserialized, which
does not preserve the loader.
- '''
+ """
self._loader = loader
@@ -462,9 +462,9 @@ class Task(Base, Conditional, Taggable, CollectionSearch, Notifiable, Delegatabl
self._parent.set_loader(loader)
def _get_parent_attribute(self, attr, omit=False):
- '''
+ """
Generic logic to get the attribute or parent attribute for a task value.
- '''
+ """
fattr = self.fattributes[attr]
extend = fattr.extend
diff --git a/lib/ansible/playbook/task_include.py b/lib/ansible/playbook/task_include.py
index 94f57e5326..4bb0f2114a 100644
--- a/lib/ansible/playbook/task_include.py
+++ b/lib/ansible/playbook/task_include.py
@@ -58,12 +58,12 @@ class TaskInclude(Task):
return task
def check_options(self, task, data):
- '''
+ """
Method for options validation to use in 'load_data' for TaskInclude and HandlerTaskInclude
since they share the same validations. It is not named 'validate_options' on purpose
to prevent confusion with '_validate_*" methods. Note that the task passed might be changed
as a side-effect of this method.
- '''
+ """
my_arg_names = frozenset(task.args.keys())
# validate bad args, otherwise we silently ignore
@@ -104,10 +104,10 @@ class TaskInclude(Task):
return new_me
def build_parent_block(self):
- '''
+ """
This method is used to create the parent block for the included tasks
when ``apply`` is specified
- '''
+ """
apply_attrs = self.args.pop('apply', {})
if apply_attrs:
apply_attrs['block'] = []
diff --git a/lib/ansible/plugins/__init__.py b/lib/ansible/plugins/__init__.py
index 23f11d170e..ff9068effa 100644
--- a/lib/ansible/plugins/__init__.py
+++ b/lib/ansible/plugins/__init__.py
@@ -102,13 +102,13 @@ class AnsiblePlugin(ABC):
C.handle_config_noise(display)
def set_options(self, task_keys=None, var_options=None, direct=None):
- '''
+ """
Sets the _options attribute with the configuration/keyword information for this plugin
:arg task_keys: Dict with playbook keywords that affect this option
:arg var_options: Dict with either 'connection variables'
:arg direct: Dict with 'direct assignment'
- '''
+ """
self._options = C.config.get_plugin_options(self.plugin_type, self._load_name, keys=task_keys, variables=var_options, direct=direct)
# allow extras/wildcards from vars that are not directly consumed in configuration
diff --git a/lib/ansible/plugins/action/__init__.py b/lib/ansible/plugins/action/__init__.py
index de0f58a96b..e0d500a8a8 100644
--- a/lib/ansible/plugins/action/__init__.py
+++ b/lib/ansible/plugins/action/__init__.py
@@ -51,12 +51,12 @@ def _validate_utf8_json(d):
class ActionBase(ABC):
- '''
+ """
This class is the base class for all action plugins, and defines
code common to all actions. The base class handles the connection
by putting/getting files and executing commands based on the current
action in use.
- '''
+ """
# A set of valid arguments
_VALID_ARGS = frozenset([]) # type: frozenset[str]
@@ -219,10 +219,10 @@ class ActionBase(ABC):
return False
def _configure_module(self, module_name, module_args, task_vars):
- '''
+ """
Handles the loading and templating of the module code through the
modify_module() function.
- '''
+ """
if self._task.delegate_to:
use_vars = task_vars.get('ansible_delegated_vars')[self._task.delegate_to]
else:
@@ -330,9 +330,9 @@ class ActionBase(ABC):
return (module_style, module_shebang, module_data, module_path)
def _compute_environment_string(self, raw_environment_out=None):
- '''
+ """
Builds the environment string to be used when executing the remote task.
- '''
+ """
final_environment = dict()
if self._task.environment is not None:
@@ -363,16 +363,16 @@ class ActionBase(ABC):
return self._connection._shell.env_prefix(**final_environment)
def _early_needs_tmp_path(self):
- '''
+ """
Determines if a tmp path should be created before the action is executed.
- '''
+ """
return getattr(self, 'TRANSFERS_FILES', False)
def _is_pipelining_enabled(self, module_style, wrap_async=False):
- '''
+ """
Determines if we are required and can do pipelining
- '''
+ """
try:
is_enabled = self._connection.get_option('pipelining')
@@ -400,15 +400,15 @@ class ActionBase(ABC):
return all(conditions)
def _get_admin_users(self):
- '''
+ """
Returns a list of admin users that are configured for the current shell
plugin
- '''
+ """
return self.get_shell_option('admin_users', ['root'])
def _get_remote_addr(self, tvars):
- ''' consistently get the 'remote_address' for the action plugin '''
+ """ consistently get the 'remote_address' for the action plugin """
remote_addr = tvars.get('delegated_vars', {}).get('ansible_host', tvars.get('ansible_host', tvars.get('inventory_hostname', None)))
for variation in ('remote_addr', 'host'):
try:
@@ -422,7 +422,7 @@ class ActionBase(ABC):
return remote_addr
def _get_remote_user(self):
- ''' consistently get the 'remote_user' for the action plugin '''
+ """ consistently get the 'remote_user' for the action plugin """
# TODO: use 'current user running ansible' as fallback when moving away from play_context
# pwd.getpwuid(os.getuid()).pw_name
remote_user = None
@@ -437,10 +437,10 @@ class ActionBase(ABC):
return remote_user
def _is_become_unprivileged(self):
- '''
+ """
The user is not the same as the connection user and is not part of the
shell configured admin users
- '''
+ """
# if we don't use become then we know we aren't switching to a
# different unprivileged user
if not self._connection.become:
@@ -454,9 +454,9 @@ class ActionBase(ABC):
return bool(become_user and become_user not in admin_users + [remote_user])
def _make_tmp_path(self, remote_user=None):
- '''
+ """
Create and return a temporary path on a remote box.
- '''
+ """
# Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
# As such, we want to avoid using remote_user for paths as remote_user may not line up with the local user
@@ -517,11 +517,11 @@ class ActionBase(ABC):
return rc
def _should_remove_tmp_path(self, tmp_path):
- '''Determine if temporary path should be deleted or kept by user request/config'''
+ """Determine if temporary path should be deleted or kept by user request/config"""
return tmp_path and self._cleanup_remote_tmp and not C.DEFAULT_KEEP_REMOTE_FILES and "-tmp-" in tmp_path
def _remove_tmp_path(self, tmp_path, force=False):
- '''Remove a temporary path we created. '''
+ """Remove a temporary path we created. """
if tmp_path is None and self._connection._shell.tmpdir:
tmp_path = self._connection._shell.tmpdir
@@ -557,9 +557,9 @@ class ActionBase(ABC):
return remote_path
def _transfer_data(self, remote_path, data):
- '''
+ """
Copies the module data out to the temporary module path.
- '''
+ """
if isinstance(data, dict):
data = jsonify(data)
@@ -802,41 +802,41 @@ class ActionBase(ABC):
to_native(res['stderr']), become_link))
def _remote_chmod(self, paths, mode, sudoable=False):
- '''
+ """
Issue a remote chmod command
- '''
+ """
cmd = self._connection._shell.chmod(paths, mode)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_chown(self, paths, user, sudoable=False):
- '''
+ """
Issue a remote chown command
- '''
+ """
cmd = self._connection._shell.chown(paths, user)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_chgrp(self, paths, group, sudoable=False):
- '''
+ """
Issue a remote chgrp command
- '''
+ """
cmd = self._connection._shell.chgrp(paths, group)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _remote_set_user_facl(self, paths, user, mode, sudoable=False):
- '''
+ """
Issue a remote call to setfacl
- '''
+ """
cmd = self._connection._shell.set_user_facl(paths, user, mode)
res = self._low_level_execute_command(cmd, sudoable=sudoable)
return res
def _execute_remote_stat(self, path, all_vars, follow, tmp=None, checksum=True):
- '''
+ """
Get information from remote file.
- '''
+ """
if tmp is not None:
display.warning('_execute_remote_stat no longer honors the tmp parameter. Action'
' plugins should set self._connection._shell.tmpdir to share'
@@ -876,7 +876,7 @@ class ActionBase(ABC):
return mystat['stat']
def _remote_expand_user(self, path, sudoable=True, pathsep=None):
- ''' takes a remote path and performs tilde/$HOME expansion on the remote host '''
+ """ takes a remote path and performs tilde/$HOME expansion on the remote host """
# We only expand ~/path and ~username/path
if not path.startswith('~'):
@@ -930,9 +930,9 @@ class ActionBase(ABC):
return expanded
def _strip_success_message(self, data):
- '''
+ """
Removes the BECOME-SUCCESS message from the data.
- '''
+ """
if data.strip().startswith('BECOME-SUCCESS-'):
data = re.sub(r'^((\r)?\n)?BECOME-SUCCESS.*(\r)?\n', '', data)
return data
@@ -1003,9 +1003,9 @@ class ActionBase(ABC):
def _execute_module(self, module_name=None, module_args=None, tmp=None, task_vars=None, persist_files=False, delete_remote_tmp=None, wrap_async=False,
ignore_unknown_opts: bool = False):
- '''
+ """
Transfer and run a module along with its arguments.
- '''
+ """
if tmp is not None:
display.warning('_execute_module no longer honors the tmp parameter. Action plugins'
' should set self._connection._shell.tmpdir to share the tmpdir')
@@ -1266,7 +1266,7 @@ class ActionBase(ABC):
# FIXME: move to connection base
def _low_level_execute_command(self, cmd, sudoable=True, in_data=None, executable=None, encoding_errors='surrogate_then_replace', chdir=None):
- '''
+ """
This is the function which executes the low level shell command, which
may be commands to create/remove directories for temporary files, or to
run the module code or python directly when pipelining.
@@ -1279,7 +1279,7 @@ class ActionBase(ABC):
verbatim, then this won't work. May have to use some sort of
replacement strategy (python3 could use surrogateescape)
:kwarg chdir: cd into this directory before executing the command.
- '''
+ """
display.debug("_low_level_execute_command(): starting")
# if not cmd:
@@ -1422,11 +1422,11 @@ class ActionBase(ABC):
return diff
def _find_needle(self, dirname, needle):
- '''
+ """
find a needle in haystack of paths, optionally using 'dirname' as a subdir.
This will build the ordered list of paths to search and pass them to dwim
to get back the first existing file found.
- '''
+ """
# dwim already deals with playbook basedirs
path_stack = self._task.get_search_path()
diff --git a/lib/ansible/plugins/action/add_host.py b/lib/ansible/plugins/action/add_host.py
index 9039e347b7..7ed64c8166 100644
--- a/lib/ansible/plugins/action/add_host.py
+++ b/lib/ansible/plugins/action/add_host.py
@@ -31,7 +31,7 @@ display = Display()
class ActionModule(ActionBase):
- ''' Create inventory hosts and groups in the memory inventory'''
+ """ Create inventory hosts and groups in the memory inventory"""
# We need to be able to modify the inventory
BYPASS_HOST_LOOP = True
diff --git a/lib/ansible/plugins/action/assemble.py b/lib/ansible/plugins/action/assemble.py
index 6d0634c485..bedf819109 100644
--- a/lib/ansible/plugins/action/assemble.py
+++ b/lib/ansible/plugins/action/assemble.py
@@ -37,7 +37,7 @@ class ActionModule(ActionBase):
TRANSFERS_FILES = True
def _assemble_from_fragments(self, src_path, delimiter=None, compiled_regexp=None, ignore_hidden=False, decrypt=True):
- ''' assemble a file from a directory of fragments '''
+ """ assemble a file from a directory of fragments """
tmpfd, temp_path = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
tmp = os.fdopen(tmpfd, 'wb')
diff --git a/lib/ansible/plugins/action/assert.py b/lib/ansible/plugins/action/assert.py
index 578320cf5a..5e18749af0 100644
--- a/lib/ansible/plugins/action/assert.py
+++ b/lib/ansible/plugins/action/assert.py
@@ -24,7 +24,7 @@ from ansible.module_utils.parsing.convert_bool import boolean
class ActionModule(ActionBase):
- ''' Fail with custom message '''
+ """ Fail with custom message """
_requires_connection = False
diff --git a/lib/ansible/plugins/action/copy.py b/lib/ansible/plugins/action/copy.py
index 3799d110fd..348def6033 100644
--- a/lib/ansible/plugins/action/copy.py
+++ b/lib/ansible/plugins/action/copy.py
@@ -389,7 +389,7 @@ class ActionModule(ActionBase):
return result
def _create_content_tempfile(self, content):
- ''' Create a tempfile containing defined content '''
+ """ Create a tempfile containing defined content """
fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP, prefix='.')
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
@@ -407,7 +407,7 @@ class ActionModule(ActionBase):
os.remove(content_tempfile)
def run(self, tmp=None, task_vars=None):
- ''' handler for file transfer operations '''
+ """ handler for file transfer operations """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/debug.py b/lib/ansible/plugins/action/debug.py
index 579ffcef64..eefc2b74a3 100644
--- a/lib/ansible/plugins/action/debug.py
+++ b/lib/ansible/plugins/action/debug.py
@@ -24,7 +24,7 @@ from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
- ''' Print statements during execution '''
+ """ Print statements during execution """
TRANSFERS_FILES = False
_VALID_ARGS = frozenset(('msg', 'var', 'verbosity'))
diff --git a/lib/ansible/plugins/action/fail.py b/lib/ansible/plugins/action/fail.py
index 998d8a9244..82820ba94d 100644
--- a/lib/ansible/plugins/action/fail.py
+++ b/lib/ansible/plugins/action/fail.py
@@ -21,7 +21,7 @@ from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
- ''' Fail with custom message '''
+ """ Fail with custom message """
TRANSFERS_FILES = False
_VALID_ARGS = frozenset(('msg',))
diff --git a/lib/ansible/plugins/action/fetch.py b/lib/ansible/plugins/action/fetch.py
index b7b6f30f9f..d099fd357c 100644
--- a/lib/ansible/plugins/action/fetch.py
+++ b/lib/ansible/plugins/action/fetch.py
@@ -33,7 +33,7 @@ display = Display()
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
- ''' handler for fetch operations '''
+ """ handler for fetch operations """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/group_by.py b/lib/ansible/plugins/action/group_by.py
index 369e89b79f..27c433ac69 100644
--- a/lib/ansible/plugins/action/group_by.py
+++ b/lib/ansible/plugins/action/group_by.py
@@ -21,7 +21,7 @@ from ansible.module_utils.six import string_types
class ActionModule(ActionBase):
- ''' Create inventory groups based on variables '''
+ """ Create inventory groups based on variables """
# We need to be able to modify the inventory
TRANSFERS_FILES = False
diff --git a/lib/ansible/plugins/action/package.py b/lib/ansible/plugins/action/package.py
index a20819a637..13b2cdf776 100644
--- a/lib/ansible/plugins/action/package.py
+++ b/lib/ansible/plugins/action/package.py
@@ -33,7 +33,7 @@ class ActionModule(ActionBase):
BUILTIN_PKG_MGR_MODULES = {manager['name'] for manager in PKG_MGRS}
def run(self, tmp=None, task_vars=None):
- ''' handler for package operations '''
+ """ handler for package operations """
self._supports_check_mode = True
self._supports_async = True
diff --git a/lib/ansible/plugins/action/pause.py b/lib/ansible/plugins/action/pause.py
index d603579fe1..4c0b40dcb7 100644
--- a/lib/ansible/plugins/action/pause.py
+++ b/lib/ansible/plugins/action/pause.py
@@ -28,12 +28,12 @@ display = Display()
class ActionModule(ActionBase):
- ''' pauses execution for a length or time, or until input is received '''
+ """ pauses execution for a length or time, or until input is received """
BYPASS_HOST_LOOP = True
def run(self, tmp=None, task_vars=None):
- ''' run the pause action module '''
+ """ run the pause action module """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/script.py b/lib/ansible/plugins/action/script.py
index 7830416334..c22a66cada 100644
--- a/lib/ansible/plugins/action/script.py
+++ b/lib/ansible/plugins/action/script.py
@@ -35,7 +35,7 @@ class ActionModule(ActionBase):
windows_absolute_path_detection = re.compile(r'^(?:[a-zA-Z]\:)?(\\|\/)')
def run(self, tmp=None, task_vars=None):
- ''' handler for file transfer operations '''
+ """ handler for file transfer operations """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/service.py b/lib/ansible/plugins/action/service.py
index 90b0780306..2b00d10b9d 100644
--- a/lib/ansible/plugins/action/service.py
+++ b/lib/ansible/plugins/action/service.py
@@ -35,7 +35,7 @@ class ActionModule(ActionBase):
BUILTIN_SVC_MGR_MODULES = set(['openwrt_init', 'service', 'systemd', 'sysvinit'])
def run(self, tmp=None, task_vars=None):
- ''' handler for package operations '''
+ """ handler for package operations """
self._supports_check_mode = True
self._supports_async = True
diff --git a/lib/ansible/plugins/action/template.py b/lib/ansible/plugins/action/template.py
index c1cb67302d..f83522dd70 100644
--- a/lib/ansible/plugins/action/template.py
+++ b/lib/ansible/plugins/action/template.py
@@ -34,7 +34,7 @@ class ActionModule(ActionBase):
DEFAULT_NEWLINE_SEQUENCE = "\n"
def run(self, tmp=None, task_vars=None):
- ''' handler for template operations '''
+ """ handler for template operations """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/unarchive.py b/lib/ansible/plugins/action/unarchive.py
index bcc152d44c..ece2597ada 100644
--- a/lib/ansible/plugins/action/unarchive.py
+++ b/lib/ansible/plugins/action/unarchive.py
@@ -30,7 +30,7 @@ class ActionModule(ActionBase):
TRANSFERS_FILES = True
def run(self, tmp=None, task_vars=None):
- ''' handler for unarchive operations '''
+ """ handler for unarchive operations """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/validate_argument_spec.py b/lib/ansible/plugins/action/validate_argument_spec.py
index 4d68067a34..7d2d860c23 100644
--- a/lib/ansible/plugins/action/validate_argument_spec.py
+++ b/lib/ansible/plugins/action/validate_argument_spec.py
@@ -10,13 +10,13 @@ from ansible.utils.vars import combine_vars
class ActionModule(ActionBase):
- ''' Validate an arg spec'''
+ """ Validate an arg spec"""
TRANSFERS_FILES = False
_requires_connection = False
def get_args_from_task_vars(self, argument_spec, task_vars):
- '''
+ """
Get any arguments that may come from `task_vars`.
Expand templated variables so we can validate the actual values.
@@ -25,7 +25,7 @@ class ActionModule(ActionBase):
:param task_vars: A dict of task variables.
:returns: A dict of values that can be validated against the arg spec.
- '''
+ """
args = {}
for argument_name, argument_attrs in argument_spec.items():
@@ -35,7 +35,7 @@ class ActionModule(ActionBase):
return args
def run(self, tmp=None, task_vars=None):
- '''
+ """
Validate an argument specification against a provided set of data.
The `validate_argument_spec` module expects to receive the arguments:
@@ -48,7 +48,7 @@ class ActionModule(ActionBase):
:param task_vars: A dict of task variables.
:return: An action result dict, including a 'argument_errors' key with a
list of validation errors found.
- '''
+ """
if task_vars is None:
task_vars = dict()
diff --git a/lib/ansible/plugins/action/wait_for_connection.py b/lib/ansible/plugins/action/wait_for_connection.py
index 9eb3fac975..9b0e3dd166 100644
--- a/lib/ansible/plugins/action/wait_for_connection.py
+++ b/lib/ansible/plugins/action/wait_for_connection.py
@@ -76,7 +76,7 @@ class ActionModule(ActionBase):
del tmp # tmp no longer has any effect
def ping_module_test(connect_timeout):
- ''' Test ping module, if available '''
+ """ Test ping module, if available """
display.vvv("wait_for_connection: attempting ping module test")
# re-run interpreter discovery if we ran it in the first iteration
if self._discovered_interpreter_key:
diff --git a/lib/ansible/plugins/become/__init__.py b/lib/ansible/plugins/become/__init__.py
index beb45b70e4..6f7a2b88ab 100644
--- a/lib/ansible/plugins/become/__init__.py
+++ b/lib/ansible/plugins/become/__init__.py
@@ -16,7 +16,7 @@ from ansible.plugins import AnsiblePlugin
def _gen_id(length=32):
- ''' return random string used to identify the current privilege escalation '''
+ """ return random string used to identify the current privilege escalation """
return ''.join(choice(ascii_lowercase) for x in range(length))
@@ -83,14 +83,14 @@ class BecomeBase(AnsiblePlugin):
return any(b_success in l.rstrip() for l in b_output.splitlines(True))
def check_password_prompt(self, b_output):
- ''' checks if the expected password prompt exists in b_output '''
+ """ checks if the expected password prompt exists in b_output """
if self.prompt:
b_prompt = to_bytes(self.prompt).strip()
return any(l.strip().startswith(b_prompt) for l in b_output.splitlines())
return False
def _check_password_error(self, b_out, msg):
- ''' returns True/False if domain specific i18n version of msg is found in b_out '''
+ """ returns True/False if domain specific i18n version of msg is found in b_out """
b_fail = to_bytes(dgettext(self.name, msg))
return b_fail and b_fail in b_out
diff --git a/lib/ansible/plugins/become/su.py b/lib/ansible/plugins/become/su.py
index ae2d39a521..b8a7f0be99 100644
--- a/lib/ansible/plugins/become/su.py
+++ b/lib/ansible/plugins/become/su.py
@@ -140,7 +140,7 @@ class BecomeModule(BecomeBase):
]
def check_password_prompt(self, b_output):
- ''' checks if the expected password prompt exists in b_output '''
+ """ checks if the expected password prompt exists in b_output """
prompts = self.get_option('prompt_l10n') or self.SU_PROMPT_LOCALIZATIONS
b_password_string = b"|".join((br'(\w+\'s )?' + to_bytes(p)) for p in prompts)
diff --git a/lib/ansible/plugins/cache/jsonfile.py b/lib/ansible/plugins/cache/jsonfile.py
index 69fd828a62..6184947b6c 100644
--- a/lib/ansible/plugins/cache/jsonfile.py
+++ b/lib/ansible/plugins/cache/jsonfile.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: jsonfile
short_description: JSON formatted files.
description:
@@ -38,7 +38,7 @@ DOCUMENTATION = '''
- key: fact_caching_timeout
section: defaults
type: integer
-'''
+"""
import codecs
import json
diff --git a/lib/ansible/plugins/cache/memory.py b/lib/ansible/plugins/cache/memory.py
index 59991ac7ab..780a643f15 100644
--- a/lib/ansible/plugins/cache/memory.py
+++ b/lib/ansible/plugins/cache/memory.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: memory
short_description: RAM backed, non persistent
description:
@@ -14,7 +14,7 @@ DOCUMENTATION = '''
- There are no options to configure.
version_added: historical
author: core team (@ansible-core)
-'''
+"""
from ansible.plugins.cache import BaseCacheModule
diff --git a/lib/ansible/plugins/callback/__init__.py b/lib/ansible/plugins/callback/__init__.py
index d73282304b..c88fbd5572 100644
--- a/lib/ansible/plugins/callback/__init__.py
+++ b/lib/ansible/plugins/callback/__init__.py
@@ -138,11 +138,11 @@ for data_type in _YAML_TEXT_TYPES:
class CallbackBase(AnsiblePlugin):
- '''
+ """
This is a base ansible callback class that does nothing. New callbacks should
use this class as a base and override any callback methods they wish to execute
custom actions.
- '''
+ """
def __init__(self, display=None, options=None):
if display:
@@ -175,9 +175,9 @@ class CallbackBase(AnsiblePlugin):
return self._plugin_options[k]
def set_options(self, task_keys=None, var_options=None, direct=None):
- ''' This is different than the normal plugin method as callbacks get called early and really don't accept keywords.
+ """ This is different than the normal plugin method as callbacks get called early and really don't accept keywords.
Also _options was already taken for CLI args and callbacks use _plugin_options instead.
- '''
+ """
# load from config
self._plugin_options = C.config.get_plugin_options(self.plugin_type, self._load_name, keys=task_keys, variables=var_options, direct=direct)
@@ -286,7 +286,7 @@ class CallbackBase(AnsiblePlugin):
)
def _handle_warnings(self, res):
- ''' display warnings, if enabled and any exist in the result '''
+ """ display warnings, if enabled and any exist in the result """
if C.ACTION_WARNINGS:
if 'warnings' in res and res['warnings']:
for warning in res['warnings']:
@@ -404,7 +404,7 @@ class CallbackBase(AnsiblePlugin):
return u''.join(ret)
def _get_item_label(self, result):
- ''' retrieves the value to be displayed as a label for an item entry from a result object'''
+ """ retrieves the value to be displayed as a label for an item entry from a result object"""
if result.get('_ansible_no_log', False):
item = "(censored due to no_log)"
else:
@@ -416,7 +416,7 @@ class CallbackBase(AnsiblePlugin):
del result._result['results']
def _clean_results(self, result, task_name):
- ''' removes data from results for display '''
+ """ removes data from results for display """
# mostly controls that debug only outputs what it was meant to
if task_name in C._ACTION_DEBUG:
diff --git a/lib/ansible/plugins/callback/default.py b/lib/ansible/plugins/callback/default.py
index 4a0bf0d05b..39bd5a45f3 100644
--- a/lib/ansible/plugins/callback/default.py
+++ b/lib/ansible/plugins/callback/default.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: default
type: stdout
short_description: default Ansible screen output
@@ -16,7 +16,7 @@ DOCUMENTATION = '''
- result_format_callback
requirements:
- set as stdout in configuration
-'''
+"""
from ansible import constants as C
@@ -29,10 +29,10 @@ from ansible.utils.fqcn import add_internal_fqcns
class CallbackModule(CallbackBase):
- '''
+ """
This is the default callback interface, which simply prints messages
to stdout when new callback events are received.
- '''
+ """
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
diff --git a/lib/ansible/plugins/callback/junit.py b/lib/ansible/plugins/callback/junit.py
index 73db9d55da..e164902474 100644
--- a/lib/ansible/plugins/callback/junit.py
+++ b/lib/ansible/plugins/callback/junit.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: junit
type: aggregate
short_description: write playbook output to a JUnit file.
@@ -80,7 +80,7 @@ DOCUMENTATION = '''
- name: JUNIT_TEST_CASE_PREFIX
requirements:
- enable in configuration
-'''
+"""
import os
import time
diff --git a/lib/ansible/plugins/callback/minimal.py b/lib/ansible/plugins/callback/minimal.py
index e316d8fdfd..181e90eba9 100644
--- a/lib/ansible/plugins/callback/minimal.py
+++ b/lib/ansible/plugins/callback/minimal.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: minimal
type: stdout
short_description: minimal Ansible screen output
@@ -13,7 +13,7 @@ DOCUMENTATION = '''
- This is the default output callback used by the ansible command (ad-hoc)
extends_documentation_fragment:
- result_format_callback
-'''
+"""
from ansible.plugins.callback import CallbackBase
from ansible import constants as C
@@ -21,17 +21,17 @@ from ansible import constants as C
class CallbackModule(CallbackBase):
- '''
+ """
This is the default callback interface, which simply prints messages
to stdout when new callback events are received.
- '''
+ """
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
CALLBACK_NAME = 'minimal'
def _command_generic_msg(self, host, result, caption):
- ''' output the result of a command run '''
+ """ output the result of a command run """
buf = "%s | %s | rc=%s >>\n" % (host, caption, result.get('rc', -1))
buf += result.get('stdout', '')
diff --git a/lib/ansible/plugins/callback/oneline.py b/lib/ansible/plugins/callback/oneline.py
index 3a5eb72fd8..4ac74d6162 100644
--- a/lib/ansible/plugins/callback/oneline.py
+++ b/lib/ansible/plugins/callback/oneline.py
@@ -4,14 +4,14 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: oneline
type: stdout
short_description: oneline Ansible screen output
version_added: historical
description:
- This is the output callback used by the C(-o)/C(--one-line) command line option.
-'''
+"""
from ansible.plugins.callback import CallbackBase
from ansible import constants as C
@@ -19,10 +19,10 @@ from ansible import constants as C
class CallbackModule(CallbackBase):
- '''
+ """
This is the default callback interface, which simply prints messages
to stdout when new callback events are received.
- '''
+ """
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'stdout'
diff --git a/lib/ansible/plugins/callback/tree.py b/lib/ansible/plugins/callback/tree.py
index b7f85f0edc..9618f8ec8c 100644
--- a/lib/ansible/plugins/callback/tree.py
+++ b/lib/ansible/plugins/callback/tree.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: tree
type: notification
requirements:
@@ -25,7 +25,7 @@ DOCUMENTATION = '''
description:
- "This callback is used by the Ansible (adhoc) command line option C(-t|--tree)."
- This produces a JSON dump of events in a directory, a file for each host, the directory used MUST be passed as a command line option.
-'''
+"""
import os
@@ -36,9 +36,9 @@ from ansible.utils.path import makedirs_safe, unfrackpath
class CallbackModule(CallbackBase):
- '''
+ """
This callback puts results into a host specific file in a directory in json format.
- '''
+ """
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
@@ -46,7 +46,7 @@ class CallbackModule(CallbackBase):
CALLBACK_NEEDS_ENABLED = True
def set_options(self, task_keys=None, var_options=None, direct=None):
- ''' override to set self.tree '''
+ """ override to set self.tree """
super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
@@ -57,7 +57,7 @@ class CallbackModule(CallbackBase):
self.tree = self.get_option('directory')
def write_tree_file(self, hostname, buf):
- ''' write something into treedir/hostname '''
+ """ write something into treedir/hostname """
buf = to_bytes(buf)
try:
diff --git a/lib/ansible/plugins/connection/__init__.py b/lib/ansible/plugins/connection/__init__.py
index e769770fe2..de4a79e981 100644
--- a/lib/ansible/plugins/connection/__init__.py
+++ b/lib/ansible/plugins/connection/__init__.py
@@ -47,9 +47,9 @@ def ensure_connect(
class ConnectionBase(AnsiblePlugin):
- '''
+ """
A base class for connections to contain common code.
- '''
+ """
has_pipelining = False
has_native_async = False # eg, winrm
@@ -119,12 +119,12 @@ class ConnectionBase(AnsiblePlugin):
@property
def connected(self) -> bool:
- '''Read-only property holding whether the connection to the remote host is active or closed.'''
+ """Read-only property holding whether the connection to the remote host is active or closed."""
return self._connected
@property
def socket_path(self) -> str | None:
- '''Read-only property holding the connection socket path for this remote host'''
+ """Read-only property holding the connection socket path for this remote host"""
return self._socket_path
@staticmethod
@@ -247,10 +247,10 @@ class ConnectionBase(AnsiblePlugin):
display.warning("Reset is not implemented for this connection")
def update_vars(self, variables: dict[str, t.Any]) -> None:
- '''
+ """
Adds 'magic' variables relating to connections to the variable dictionary provided.
In case users need to access from the play, this is a legacy from runner.
- '''
+ """
for varname in C.COMMON_CONNECTION_VARS:
value = None
if varname in variables:
@@ -356,9 +356,9 @@ class NetworkConnectionBase(ConnectionBase):
return self._local.fetch_file(in_path, out_path)
def reset(self) -> None:
- '''
+ """
Reset the connection
- '''
+ """
if self._socket_path:
self.queue_message('vvvv', 'resetting persistent connection for socket_path %s' % self._socket_path)
self.close()
@@ -390,14 +390,14 @@ class NetworkConnectionBase(ConnectionBase):
pass
def _update_connection_state(self) -> None:
- '''
+ """
Reconstruct the connection socket_path and check if it exists
If the socket path exists then the connection is active and set
both the _socket_path value to the path and the _connected value
to True. If the socket path doesn't exist, leave the socket path
value to None and the _connected value to False
- '''
+ """
ssh = connection_loader.get('ssh', class_only=True)
control_path = ssh._create_control_path(
self._play_context.remote_addr, self._play_context.port,
diff --git a/lib/ansible/plugins/connection/local.py b/lib/ansible/plugins/connection/local.py
index 464d8e8906..2fa8f491a0 100644
--- a/lib/ansible/plugins/connection/local.py
+++ b/lib/ansible/plugins/connection/local.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: local
short_description: execute on controller
description:
@@ -15,7 +15,7 @@ DOCUMENTATION = '''
- connection_pipelining
notes:
- The remote user is ignored, the user with which the ansible CLI was executed is used instead.
-'''
+"""
import fcntl
import getpass
@@ -38,7 +38,7 @@ display = Display()
class Connection(ConnectionBase):
- ''' Local based connections '''
+ """ Local based connections """
transport = 'local'
has_pipelining = True
@@ -54,7 +54,7 @@ class Connection(ConnectionBase):
self.default_user = ""
def _connect(self) -> Connection:
- ''' connect to the local host; nothing to do here '''
+ """ connect to the local host; nothing to do here """
# Because we haven't made any remote connection we're running as
# the local user, rather than as whatever is configured in remote_user.
@@ -66,7 +66,7 @@ class Connection(ConnectionBase):
return self
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]:
- ''' run a command on the local host '''
+ """ run a command on the local host """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
@@ -164,7 +164,7 @@ class Connection(ConnectionBase):
return (p.returncode, stdout, stderr)
def put_file(self, in_path: str, out_path: str) -> None:
- ''' transfer a file from local to local '''
+ """ transfer a file from local to local """
super(Connection, self).put_file(in_path, out_path)
@@ -182,7 +182,7 @@ class Connection(ConnectionBase):
raise AnsibleError("failed to transfer file to {0}: {1}".format(to_native(out_path), to_native(e)))
def fetch_file(self, in_path: str, out_path: str) -> None:
- ''' fetch a file from local to local -- for compatibility '''
+ """ fetch a file from local to local -- for compatibility """
super(Connection, self).fetch_file(in_path, out_path)
@@ -190,5 +190,5 @@ class Connection(ConnectionBase):
self.put_file(in_path, out_path)
def close(self) -> None:
- ''' terminate the connection; nothing to do here '''
+ """ terminate the connection; nothing to do here """
self._connected = False
diff --git a/lib/ansible/plugins/connection/paramiko_ssh.py b/lib/ansible/plugins/connection/paramiko_ssh.py
index 9ffeb317fc..239c1bdd5f 100644
--- a/lib/ansible/plugins/connection/paramiko_ssh.py
+++ b/lib/ansible/plugins/connection/paramiko_ssh.py
@@ -321,7 +321,7 @@ SFTP_CONNECTION_CACHE: dict[str, paramiko.sftp_client.SFTPClient] = {}
class Connection(ConnectionBase):
- ''' SSH based connections with Paramiko '''
+ """ SSH based connections with Paramiko """
transport = 'paramiko'
_log_channel: str | None = None
@@ -340,7 +340,7 @@ class Connection(ConnectionBase):
return self
def _set_log_channel(self, name: str) -> None:
- '''Mimic paramiko.SSHClient.set_log_channel'''
+ """Mimic paramiko.SSHClient.set_log_channel"""
self._log_channel = name
def _parse_proxy_command(self, port: int = 22) -> dict[str, t.Any]:
@@ -366,7 +366,7 @@ class Connection(ConnectionBase):
return sock_kwarg
def _connect_uncached(self) -> paramiko.SSHClient:
- ''' activates the connection object '''
+ """ activates the connection object """
if paramiko is None:
raise AnsibleError("paramiko is not installed: %s" % to_native(PARAMIKO_IMPORT_ERR))
@@ -461,7 +461,7 @@ class Connection(ConnectionBase):
return ssh
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]:
- ''' run a command on the remote host '''
+ """ run a command on the remote host """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
@@ -541,7 +541,7 @@ class Connection(ConnectionBase):
return (chan.recv_exit_status(), no_prompt_out + stdout, no_prompt_out + stderr)
def put_file(self, in_path: str, out_path: str) -> None:
- ''' transfer a file from local to remote '''
+ """ transfer a file from local to remote """
super(Connection, self).put_file(in_path, out_path)
@@ -570,7 +570,7 @@ class Connection(ConnectionBase):
return result
def fetch_file(self, in_path: str, out_path: str) -> None:
- ''' save a remote file to the specified path '''
+ """ save a remote file to the specified path """
super(Connection, self).fetch_file(in_path, out_path)
@@ -596,10 +596,10 @@ class Connection(ConnectionBase):
return False
def _save_ssh_host_keys(self, filename: str) -> None:
- '''
+ """
not using the paramiko save_ssh_host_keys function as we want to add new SSH keys at the bottom so folks
don't complain about it :)
- '''
+ """
if not self._any_keys_added():
return
@@ -632,7 +632,7 @@ class Connection(ConnectionBase):
self._connect()
def close(self) -> None:
- ''' terminate the connection '''
+ """ terminate the connection """
cache_key = self._cache_key()
SSH_CONNECTION_CACHE.pop(cache_key, None)
diff --git a/lib/ansible/plugins/connection/psrp.py b/lib/ansible/plugins/connection/psrp.py
index 44372bbee3..95348d6107 100644
--- a/lib/ansible/plugins/connection/psrp.py
+++ b/lib/ansible/plugins/connection/psrp.py
@@ -473,7 +473,7 @@ class Connection(ConnectionBase):
out_path = self._shell._unquote(out_path)
display.vvv("PUT %s TO %s" % (in_path, out_path), host=self._psrp_host)
- copy_script = '''begin {
+ copy_script = """begin {
$ErrorActionPreference = "Stop"
$WarningPreference = "Continue"
$path = $MyInvocation.UnboundArguments[0]
@@ -567,7 +567,7 @@ end {
$hash = [System.BitConverter]::ToString($algo.Hash).Replace('-', '').ToLowerInvariant()
Write-Output -InputObject "{`"sha1`":`"$hash`"}"
}
-'''
+"""
# Get the buffer size of each fragment to send, subtract 82 for the fragment, message, and other header info
# fields that PSRP adds. Adjust to size of the base64 encoded bytes length.
@@ -630,7 +630,7 @@ end {
buffer_size = max_b64_size - (max_b64_size % 1024)
# setup the file stream with read only mode
- setup_script = '''param([string]$Path)
+ setup_script = """param([string]$Path)
$ErrorActionPreference = "Stop"
if (Test-Path -LiteralPath $path -PathType Leaf) {
@@ -645,10 +645,10 @@ if (Test-Path -LiteralPath $path -PathType Leaf) {
} else {
Write-Error -Message "$path does not exist"
$host.SetShouldExit(1)
-}'''
+}"""
# read the file stream at the offset and return the b64 string
- read_script = '''param([int64]$Offset, [int]$BufferSize)
+ read_script = """param([int64]$Offset, [int]$BufferSize)
$ErrorActionPreference = "Stop"
$fs.Seek($Offset, [System.IO.SeekOrigin]::Begin) > $null
$buffer = New-Object -TypeName byte[] -ArgumentList $BufferSize
@@ -656,7 +656,7 @@ $read = $fs.Read($buffer, 0, $buffer.Length)
if ($read -gt 0) {
[System.Convert]::ToBase64String($buffer, 0, $read)
-}'''
+}"""
# need to run the setup script outside of the local scope so the
# file stream stays active between fetch operations
diff --git a/lib/ansible/plugins/connection/ssh.py b/lib/ansible/plugins/connection/ssh.py
index b5cda5a851..299039faa5 100644
--- a/lib/ansible/plugins/connection/ssh.py
+++ b/lib/ansible/plugins/connection/ssh.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: ssh
short_description: connect via SSH client binary
description:
@@ -363,7 +363,7 @@ DOCUMENTATION = '''
- {key: pkcs11_provider, section: ssh_connection}
vars:
- name: ansible_ssh_pkcs11_provider
-'''
+"""
import collections.abc as c
import errno
@@ -410,7 +410,7 @@ SSH_DEBUG = re.compile(r'^debug\d+: .*')
class AnsibleControlPersistBrokenPipeError(AnsibleError):
- ''' ControlPersist broken pipe '''
+ """ ControlPersist broken pipe """
pass
@@ -559,7 +559,7 @@ def _ssh_retry(
class Connection(ConnectionBase):
- ''' ssh based connections '''
+ """ ssh based connections """
transport = 'ssh'
has_pipelining = True
@@ -598,7 +598,7 @@ class Connection(ConnectionBase):
connection: ConnectionBase | None = None,
pid: int | None = None,
) -> str:
- '''Make a hash for the controlpath based on con attributes'''
+ """Make a hash for the controlpath based on con attributes"""
pstring = '%s-%s-%s' % (host, port, user)
if connection:
pstring += '-%s' % connection
@@ -630,12 +630,12 @@ class Connection(ConnectionBase):
@staticmethod
def _persistence_controls(b_command: list[bytes]) -> tuple[bool, bool]:
- '''
+ """
Takes a command array and scans it for ControlPersist and ControlPath
settings and returns two booleans indicating whether either was found.
This could be smarter, e.g. returning false if ControlPersist is 'no',
but for now we do it simple way.
- '''
+ """
controlpersist = False
controlpath = False
@@ -665,7 +665,7 @@ class Connection(ConnectionBase):
b_command += b_args
def _build_command(self, binary: str, subsystem: str, *other_args: bytes | str) -> list[bytes]:
- '''
+ """
Takes a executable (ssh, scp, sftp or wrapper) and optional extra arguments and returns the remote command
wrapped in local ssh shell commands and ready for execution.
@@ -673,7 +673,7 @@ class Connection(ConnectionBase):
:arg subsystem: type of executable provided, ssh/sftp/scp, needed because wrappers for ssh might have diff names.
:arg other_args: dict of, value pairs passed as arguments to the ssh binary
- '''
+ """
b_command = []
conn_password = self.get_option('password') or self._play_context.password
@@ -822,11 +822,11 @@ class Connection(ConnectionBase):
return b_command
def _send_initial_data(self, fh: io.IOBase, in_data: bytes, ssh_process: subprocess.Popen) -> None:
- '''
+ """
Writes initial data to the stdin filehandle of the subprocess and closes
it. (The handle must be closed; otherwise, for example, "sftp -b -" will
just hang forever waiting for more commands.)
- '''
+ """
display.debug(u'Sending initial data')
@@ -858,14 +858,14 @@ class Connection(ConnectionBase):
# This is separate from _run() because we need to do the same thing for stdout
# and stderr.
def _examine_output(self, source: str, state: str, b_chunk: bytes, sudoable: bool) -> tuple[bytes, bytes]:
- '''
+ """
Takes a string, extracts complete lines from it, tests to see if they
are a prompt, error message, etc., and sets appropriate flags in self.
Prompt and success lines are removed.
Returns the processed (i.e. possibly-edited) output and the unprocessed
remainder (to be processed with the next chunk) as strings.
- '''
+ """
output = []
for b_line in b_chunk.splitlines(True):
@@ -907,9 +907,9 @@ class Connection(ConnectionBase):
return b''.join(output), remainder
def _bare_run(self, cmd: list[bytes], in_data: bytes | None, sudoable: bool = True, checkrc: bool = True) -> tuple[int, bytes, bytes]:
- '''
+ """
Starts the command and communicates with it until it ends.
- '''
+ """
# We don't use _shell.quote as this is run on the controller and independent from the shell plugin chosen
display_cmd = u' '.join(shlex.quote(to_text(c)) for c in cmd)
@@ -1294,7 +1294,7 @@ class Connection(ConnectionBase):
# Main public methods
#
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]:
- ''' run a command on the remote host '''
+ """ run a command on the remote host """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
@@ -1335,7 +1335,7 @@ class Connection(ConnectionBase):
return (returncode, stdout, stderr)
def put_file(self, in_path: str, out_path: str) -> tuple[int, bytes, bytes]: # type: ignore[override] # Used by tests and would break API
- ''' transfer a file from local to remote '''
+ """ transfer a file from local to remote """
super(Connection, self).put_file(in_path, out_path)
@@ -1351,7 +1351,7 @@ class Connection(ConnectionBase):
return self._file_transport_command(in_path, out_path, 'put')
def fetch_file(self, in_path: str, out_path: str) -> tuple[int, bytes, bytes]: # type: ignore[override] # Used by tests and would break API
- ''' fetch a file from remote to local '''
+ """ fetch a file from remote to local """
super(Connection, self).fetch_file(in_path, out_path)
diff --git a/lib/ansible/plugins/connection/winrm.py b/lib/ansible/plugins/connection/winrm.py
index 1d50ad891d..354acce7fa 100644
--- a/lib/ansible/plugins/connection/winrm.py
+++ b/lib/ansible/plugins/connection/winrm.py
@@ -247,7 +247,7 @@ display = Display()
class Connection(ConnectionBase):
- '''WinRM connections over HTTP/HTTPS.'''
+ """WinRM connections over HTTP/HTTPS."""
transport = 'winrm'
module_implementation_preferences = ('.ps1', '.exe', '')
@@ -444,9 +444,9 @@ class Connection(ConnectionBase):
display.vvvvv("kinit succeeded for principal %s" % principal)
def _winrm_connect(self) -> winrm.Protocol:
- '''
+ """
Establish a WinRM connection over HTTP/HTTPS.
- '''
+ """
display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" %
(self._winrm_user, self._winrm_port, self._winrm_host), host=self._winrm_host)
@@ -806,7 +806,7 @@ class Connection(ConnectionBase):
if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')):
raise AnsibleFileNotFound('file or module does not exist: "%s"' % to_native(in_path))
- script_template = u'''
+ script_template = u"""
begin {{
$path = '{0}'
@@ -834,7 +834,7 @@ class Connection(ConnectionBase):
Write-Output "{{""sha1"":""$hash""}}"
}}
- '''
+ """
script = script_template.format(self._shell._escape(out_path))
cmd_parts = self._shell._encode_script(script, as_list=True, strict_mode=False, preserve_rc=False)
@@ -873,7 +873,7 @@ class Connection(ConnectionBase):
offset = 0
while True:
try:
- script = '''
+ script = """
$path = '%(path)s'
If (Test-Path -LiteralPath $path -PathType Leaf)
{
@@ -899,7 +899,7 @@ class Connection(ConnectionBase):
Write-Error "$path does not exist";
Exit 1;
}
- ''' % dict(buffer_size=buffer_size, path=self._shell._escape(in_path), offset=offset)
+ """ % dict(buffer_size=buffer_size, path=self._shell._escape(in_path), offset=offset)
display.vvvvv('WINRM FETCH "%s" to "%s" (offset=%d)' % (in_path, out_path, offset), host=self._winrm_host)
cmd_parts = self._shell._encode_script(script, as_list=True, preserve_rc=False)
status_code, b_stdout, b_stderr = self._winrm_exec(cmd_parts[0], cmd_parts[1:])
diff --git a/lib/ansible/plugins/doc_fragments/action_common_attributes.py b/lib/ansible/plugins/doc_fragments/action_common_attributes.py
index 688d675f39..6fac9eb480 100644
--- a/lib/ansible/plugins/doc_fragments/action_common_attributes.py
+++ b/lib/ansible/plugins/doc_fragments/action_common_attributes.py
@@ -7,7 +7,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard documentation fragment
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
attributes:
check_mode:
description: Can run in check_mode and return changed status prediction without modifying target, if not supported the action will be skipped.
@@ -16,17 +16,17 @@ attributes:
platform:
description: Target OS/families that can be operated against
support: N/A
-'''
+"""
- ACTIONGROUPS = r'''
+ ACTIONGROUPS = r"""
attributes:
action_group:
description: Action is part of action_group(s), for convenient setting of module_defaults.
support: N/A
membership: []
-'''
+"""
- CONN = r'''
+ CONN = r"""
attributes:
become:
description: Is usable alongside become keywords
@@ -34,23 +34,23 @@ attributes:
description: Uses the target's configured connection information to execute code on it
delegation:
description: Can be used in conjunction with delegate_to and related keywords
-'''
+"""
- FACTS = r'''
+ FACTS = r"""
attributes:
facts:
description: Action returns an C(ansible_facts) dictionary that will update existing host facts
-'''
+"""
- FILES = r'''
+ FILES = r"""
attributes:
safe_file_operations:
description: Uses Ansible's strict file operation functions to ensure proper permissions and avoid data corruption
vault:
description: Can automatically decrypt Ansible vaulted files
-'''
+"""
- FLOW = r'''
+ FLOW = r"""
attributes:
action:
description: Indicates this has a corresponding action plugin so some parts of the options can be executed on the controller
@@ -62,9 +62,9 @@ attributes:
throttle and other loop considerations
- Conditionals will work as if C(run_once) is being used, variables used will be from the first available host
- This action will not work normally outside of lockstep strategies
-'''
- RAW = r'''
+"""
+ RAW = r"""
attributes:
raw:
description: Indicates if an action takes a 'raw' or 'free form' string as an option and has it's own special parsing of it
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/action_core.py b/lib/ansible/plugins/doc_fragments/action_core.py
index 56214b72bd..9be51d7006 100644
--- a/lib/ansible/plugins/doc_fragments/action_core.py
+++ b/lib/ansible/plugins/doc_fragments/action_core.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# requires action_common
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
attributes:
async:
support: none
@@ -33,10 +33,10 @@ attributes:
tags:
description: Allows for the 'tags' keyword to control the selection of this action for execution
support: full
-'''
+"""
# also requires core above
- IMPORT = r'''
+ IMPORT = r"""
attributes:
action:
details: While this action executes locally on the controller it is not governed by an action plugin
@@ -59,9 +59,9 @@ attributes:
support: none
until:
support: none
-'''
+"""
# also requires core above
- INCLUDE = r'''
+ INCLUDE = r"""
attributes:
action:
details: While this action executes locally on the controller it is not governed by an action plugin
@@ -76,4 +76,4 @@ attributes:
tags:
details: Tags are interpreted by this action but are not automatically inherited by the include tasks, see C(apply)
support: partial
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/backup.py b/lib/ansible/plugins/doc_fragments/backup.py
index 037df249bb..7c58fba05d 100644
--- a/lib/ansible/plugins/doc_fragments/backup.py
+++ b/lib/ansible/plugins/doc_fragments/backup.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard documentation fragment
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
backup:
description:
@@ -16,4 +16,4 @@ options:
the original file back if you somehow clobbered it incorrectly.
type: bool
default: no
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/constructed.py b/lib/ansible/plugins/doc_fragments/constructed.py
index fbd4a3bd3d..00f8bae414 100644
--- a/lib/ansible/plugins/doc_fragments/constructed.py
+++ b/lib/ansible/plugins/doc_fragments/constructed.py
@@ -7,7 +7,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
strict:
description:
@@ -79,4 +79,4 @@ options:
type: boolean
default: True
version_added: '2.11'
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/decrypt.py b/lib/ansible/plugins/doc_fragments/decrypt.py
index c2da1cf383..11558762c6 100644
--- a/lib/ansible/plugins/doc_fragments/decrypt.py
+++ b/lib/ansible/plugins/doc_fragments/decrypt.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard files documentation fragment
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
decrypt:
description:
@@ -16,4 +16,4 @@ options:
type: bool
default: yes
version_added: '2.4'
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/default_callback.py b/lib/ansible/plugins/doc_fragments/default_callback.py
index cbd596b189..7c02c290b9 100644
--- a/lib/ansible/plugins/doc_fragments/default_callback.py
+++ b/lib/ansible/plugins/doc_fragments/default_callback.py
@@ -7,7 +7,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
display_skipped_hosts:
name: Show skipped hosts
@@ -89,4 +89,4 @@ class ModuleDocFragment(object):
- key: show_task_path_on_failure
section: defaults
version_added: '2.11'
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/files.py b/lib/ansible/plugins/doc_fragments/files.py
index abe4ed1165..3e3c32291d 100644
--- a/lib/ansible/plugins/doc_fragments/files.py
+++ b/lib/ansible/plugins/doc_fragments/files.py
@@ -11,7 +11,7 @@ class ModuleDocFragment(object):
# Note: mode is overridden by the copy and template modules so if you change the description
# here, you should also change it there.
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
mode:
description:
@@ -88,4 +88,4 @@ options:
type: str
aliases: [ attr ]
version_added: '2.3'
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/inventory_cache.py b/lib/ansible/plugins/doc_fragments/inventory_cache.py
index cfed4a6f2c..24123735be 100644
--- a/lib/ansible/plugins/doc_fragments/inventory_cache.py
+++ b/lib/ansible/plugins/doc_fragments/inventory_cache.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# inventory cache
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
cache:
description:
@@ -70,4 +70,4 @@ options:
key: fact_caching_prefix
- section: inventory
key: cache_prefix
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/result_format_callback.py b/lib/ansible/plugins/doc_fragments/result_format_callback.py
index 0b7e599dcf..88e37b8c34 100644
--- a/lib/ansible/plugins/doc_fragments/result_format_callback.py
+++ b/lib/ansible/plugins/doc_fragments/result_format_callback.py
@@ -7,7 +7,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
result_format:
name: Format of the task result
@@ -46,4 +46,4 @@ class ModuleDocFragment(object):
- key: callback_format_pretty
section: defaults
version_added: '2.13'
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/return_common.py b/lib/ansible/plugins/doc_fragments/return_common.py
index 232d93d33f..b8cc8bcdde 100644
--- a/lib/ansible/plugins/doc_fragments/return_common.py
+++ b/lib/ansible/plugins/doc_fragments/return_common.py
@@ -7,7 +7,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard documentation fragment
- RETURN = r'''
+ RETURN = r"""
changed:
description: Whether the module affected changes on the target.
returned: always
@@ -38,4 +38,4 @@ exception:
returned: on some errors
type: str
sample: Unknown error
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/template_common.py b/lib/ansible/plugins/doc_fragments/template_common.py
index 9795e43719..19fcccdae9 100644
--- a/lib/ansible/plugins/doc_fragments/template_common.py
+++ b/lib/ansible/plugins/doc_fragments/template_common.py
@@ -9,7 +9,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard template documentation fragment, use by template and win_template.
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
description:
- Templates are processed by the L(Jinja2 templating language,http://jinja.pocoo.org/docs/).
- Documentation on the template formatting can be found in the
@@ -117,4 +117,4 @@ notes:
This is the best way to prevent evaluation of things that look like, but should not be Jinja2.
- To find Byte Order Marks in files, use C(Format-Hex <file> -Count 16) on Windows, and use C(od -a -t x1 -N 16 <file>)
on Linux.
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/url.py b/lib/ansible/plugins/doc_fragments/url.py
index 7820e65d52..bddc33db98 100644
--- a/lib/ansible/plugins/doc_fragments/url.py
+++ b/lib/ansible/plugins/doc_fragments/url.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard files documentation fragment
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
url:
description:
@@ -71,4 +71,4 @@ options:
type: bool
default: no
version_added: '2.11'
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/url_windows.py b/lib/ansible/plugins/doc_fragments/url_windows.py
index 143b04597f..7500c65cf7 100644
--- a/lib/ansible/plugins/doc_fragments/url_windows.py
+++ b/lib/ansible/plugins/doc_fragments/url_windows.py
@@ -9,7 +9,7 @@ from __future__ import annotations
class ModuleDocFragment:
# Common options for Ansible.ModuleUtils.WebRequest
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
method:
description:
@@ -145,4 +145,4 @@ options:
type: bool
seealso:
- module: community.windows.win_inet_proxy
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/validate.py b/lib/ansible/plugins/doc_fragments/validate.py
index 105d305d88..a7b00b0391 100644
--- a/lib/ansible/plugins/doc_fragments/validate.py
+++ b/lib/ansible/plugins/doc_fragments/validate.py
@@ -7,7 +7,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
# Standard documentation fragment
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
validate:
description:
@@ -17,4 +17,4 @@ options:
- For an example on how to handle more complex validation than what this
option provides, see R(handling complex validation,complex_configuration_validation).
type: str
-'''
+"""
diff --git a/lib/ansible/plugins/doc_fragments/vars_plugin_staging.py b/lib/ansible/plugins/doc_fragments/vars_plugin_staging.py
index 698b7bea99..e2baddcd13 100644
--- a/lib/ansible/plugins/doc_fragments/vars_plugin_staging.py
+++ b/lib/ansible/plugins/doc_fragments/vars_plugin_staging.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
stage:
description:
@@ -20,4 +20,4 @@ options:
choices: ['all', 'task', 'inventory']
version_added: "2.10"
type: str
-'''
+"""
diff --git a/lib/ansible/plugins/filter/core.py b/lib/ansible/plugins/filter/core.py
index 79f78d728f..e0deea7e80 100644
--- a/lib/ansible/plugins/filter/core.py
+++ b/lib/ansible/plugins/filter/core.py
@@ -43,7 +43,7 @@ UUID_NAMESPACE_ANSIBLE = uuid.UUID('361E6D51-FAEC-444A-9079-341386DA8E2E')
def to_yaml(a, *args, **kw):
- '''Make verbose, human-readable yaml'''
+ """Make verbose, human-readable yaml"""
default_flow_style = kw.pop('default_flow_style', None)
try:
transformed = yaml.dump(a, Dumper=AnsibleDumper, allow_unicode=True, default_flow_style=default_flow_style, **kw)
@@ -53,7 +53,7 @@ def to_yaml(a, *args, **kw):
def to_nice_yaml(a, indent=4, *args, **kw):
- '''Make verbose, human-readable yaml'''
+ """Make verbose, human-readable yaml"""
try:
transformed = yaml.dump(a, Dumper=AnsibleDumper, indent=indent, allow_unicode=True, default_flow_style=False, **kw)
except Exception as e:
@@ -62,7 +62,7 @@ def to_nice_yaml(a, indent=4, *args, **kw):
def to_json(a, *args, **kw):
- ''' Convert the value to JSON '''
+ """ Convert the value to JSON """
# defaults for filters
if 'vault_to_text' not in kw:
@@ -74,14 +74,14 @@ def to_json(a, *args, **kw):
def to_nice_json(a, indent=4, sort_keys=True, *args, **kw):
- '''Make verbose, human-readable JSON'''
+ """Make verbose, human-readable JSON"""
# TODO separators can be potentially exposed to the user as well
kw.pop('separators', None)
return to_json(a, indent=indent, sort_keys=sort_keys, separators=(',', ': '), *args, **kw)
def to_bool(a):
- ''' return a bool for the arg '''
+ """ return a bool for the arg """
if a is None or isinstance(a, bool):
return a
if isinstance(a, string_types):
@@ -96,7 +96,7 @@ def to_datetime(string, format="%Y-%m-%d %H:%M:%S"):
def strftime(string_format, second=None, utc=False):
- ''' return a date string using string. See https://docs.python.org/3/library/time.html#time.strftime for format '''
+ """ return a date string using string. See https://docs.python.org/3/library/time.html#time.strftime for format """
if utc:
timefn = time.gmtime
else:
@@ -110,19 +110,19 @@ def strftime(string_format, second=None, utc=False):
def quote(a):
- ''' return its argument quoted for shell usage '''
+ """ return its argument quoted for shell usage """
if a is None:
a = u''
return shlex.quote(to_text(a))
def fileglob(pathname):
- ''' return list of matched regular files for glob '''
+ """ return list of matched regular files for glob """
return [g for g in glob.glob(pathname) if os.path.isfile(g)]
def regex_replace(value='', pattern='', replacement='', ignorecase=False, multiline=False, count=0, mandatory_count=0):
- ''' Perform a `re.sub` returning a string '''
+ """ Perform a `re.sub` returning a string """
value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr')
@@ -140,7 +140,7 @@ def regex_replace(value='', pattern='', replacement='', ignorecase=False, multil
def regex_findall(value, regex, multiline=False, ignorecase=False):
- ''' Perform re.findall and return the list of matches '''
+ """ Perform re.findall and return the list of matches """
value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr')
@@ -153,7 +153,7 @@ def regex_findall(value, regex, multiline=False, ignorecase=False):
def regex_search(value, regex, *args, **kwargs):
- ''' Perform re.search and return the list of matches or a backref '''
+ """ Perform re.search and return the list of matches or a backref """
value = to_text(value, errors='surrogate_or_strict', nonstring='simplerepr')
@@ -186,7 +186,7 @@ def regex_search(value, regex, *args, **kwargs):
def ternary(value, true_val, false_val, none_val=None):
- ''' value ? true_val : false_val '''
+ """ value ? true_val : false_val """
if value is None and none_val is not None:
return none_val
elif bool(value):
@@ -498,14 +498,14 @@ def flatten(mylist, levels=None, skip_nulls=True):
def subelements(obj, subelements, skip_missing=False):
- '''Accepts a dict or list of dicts, and a dotted accessor and produces a product
+ """Accepts a dict or list of dicts, and a dotted accessor and produces a product
of the element and the results of the dotted accessor
>>> obj = [{"name": "alice", "groups": ["wheel"], "authorized": ["/tmp/alice/onekey.pub"]}]
>>> subelements(obj, 'groups')
[({'name': 'alice', 'groups': ['wheel'], 'authorized': ['/tmp/alice/onekey.pub']}, 'wheel')]
- '''
+ """
if isinstance(obj, dict):
element_list = list(obj.values())
elif isinstance(obj, list):
@@ -544,8 +544,8 @@ def subelements(obj, subelements, skip_missing=False):
def dict_to_list_of_dict_key_value_elements(mydict, key_name='key', value_name='value'):
- ''' takes a dictionary and transforms it into a list of dictionaries,
- with each having a 'key' and 'value' keys that correspond to the keys and values of the original '''
+ """ takes a dictionary and transforms it into a list of dictionaries,
+ with each having a 'key' and 'value' keys that correspond to the keys and values of the original """
if not isinstance(mydict, Mapping):
raise AnsibleFilterTypeError("dict2items requires a dictionary, got %s instead." % type(mydict))
@@ -557,8 +557,8 @@ def dict_to_list_of_dict_key_value_elements(mydict, key_name='key', value_name='
def list_of_dict_key_value_elements_to_dict(mylist, key_name='key', value_name='value'):
- ''' takes a list of dicts with each having a 'key' and 'value' keys, and transforms the list into a dictionary,
- effectively as the reverse of dict2items '''
+ """ takes a list of dicts with each having a 'key' and 'value' keys, and transforms the list into a dictionary,
+ effectively as the reverse of dict2items """
if not is_sequence(mylist):
raise AnsibleFilterTypeError("items2dict requires a list, got %s instead." % type(mylist))
@@ -575,8 +575,8 @@ def list_of_dict_key_value_elements_to_dict(mylist, key_name='key', value_name='
def path_join(paths):
- ''' takes a sequence or a string, and return a concatenation
- of the different members '''
+ """ takes a sequence or a string, and return a concatenation
+ of the different members """
if isinstance(paths, string_types):
return os.path.join(paths)
if is_sequence(paths):
@@ -600,7 +600,7 @@ def commonpath(paths):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/lib/ansible/plugins/filter/encryption.py b/lib/ansible/plugins/filter/encryption.py
index c6863fd3ea..580e07bea2 100644
--- a/lib/ansible/plugins/filter/encryption.py
+++ b/lib/ansible/plugins/filter/encryption.py
@@ -83,7 +83,7 @@ def do_unvault(vault, secret, vault_id='filter_default', vaultid=None):
class FilterModule(object):
- ''' Ansible vault jinja2 filters '''
+ """ Ansible vault jinja2 filters """
def filters(self):
filters = {
diff --git a/lib/ansible/plugins/filter/mathstuff.py b/lib/ansible/plugins/filter/mathstuff.py
index 9772cb521a..d80eb3347c 100644
--- a/lib/ansible/plugins/filter/mathstuff.py
+++ b/lib/ansible/plugins/filter/mathstuff.py
@@ -145,7 +145,7 @@ def inversepower(x, base=2):
def human_readable(size, isbits=False, unit=None):
- ''' Return a human-readable string '''
+ """ Return a human-readable string """
try:
return formatters.bytes_to_human(size, isbits, unit)
except TypeError as e:
@@ -155,7 +155,7 @@ def human_readable(size, isbits=False, unit=None):
def human_to_bytes(size, default_unit=None, isbits=False):
- ''' Return bytes count from a human-readable string '''
+ """ Return bytes count from a human-readable string """
try:
return formatters.human_to_bytes(size, default_unit, isbits)
except TypeError as e:
@@ -215,7 +215,7 @@ def rekey_on_member(data, key, duplicates='error'):
class FilterModule(object):
- ''' Ansible math jinja2 filters '''
+ """ Ansible math jinja2 filters """
def filters(self):
filters = {
diff --git a/lib/ansible/plugins/filter/urls.py b/lib/ansible/plugins/filter/urls.py
index 1f9cde2511..c5f767bab5 100644
--- a/lib/ansible/plugins/filter/urls.py
+++ b/lib/ansible/plugins/filter/urls.py
@@ -11,7 +11,7 @@ from urllib.parse import unquote_plus
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/lib/ansible/plugins/filter/urlsplit.py b/lib/ansible/plugins/filter/urlsplit.py
index 8963659fcd..3b1d35f6b5 100644
--- a/lib/ansible/plugins/filter/urlsplit.py
+++ b/lib/ansible/plugins/filter/urlsplit.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
name: urlsplit
version_added: "2.4"
short_description: get components from URL
@@ -20,9 +20,9 @@ DOCUMENTATION = r'''
description: Specify a single component to return.
type: str
choices: ["fragment", "hostname", "netloc", "password", "path", "port", "query", "scheme", "username"]
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
parts: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit }}'
# =>
@@ -46,15 +46,15 @@ EXAMPLES = r'''
path: '{{ "http://user:password@www.acme.com:9000/dir/index.html?query=term#fragment" | urlsplit("path") }}'
# => '/dir/index.html'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
_value:
description:
- A dictionary with components as keyword and their value.
- If O(query) is provided, a string or integer will be returned instead, depending on O(query).
type: any
-'''
+"""
from urllib.parse import urlsplit
@@ -78,7 +78,7 @@ def split_url(value, query='', alias='urlsplit'):
# ---- Ansible filters ----
class FilterModule(object):
- ''' URI filter '''
+ """ URI filter """
def filters(self):
return {
diff --git a/lib/ansible/plugins/inventory/__init__.py b/lib/ansible/plugins/inventory/__init__.py
index f5bfed6fef..324234cb7e 100644
--- a/lib/ansible/plugins/inventory/__init__.py
+++ b/lib/ansible/plugins/inventory/__init__.py
@@ -45,17 +45,17 @@ def to_safe_group_name(name):
def detect_range(line=None):
- '''
+ """
A helper function that checks a given host line to see if it contains
a range pattern described in the docstring above.
Returns True if the given line contains a pattern, else False.
- '''
+ """
return '[' in line
def expand_hostname_range(line=None):
- '''
+ """
A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
@@ -65,7 +65,7 @@ def expand_hostname_range(line=None):
string splitting.
References: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html#hosts-and-groups
- '''
+ """
all_hosts = []
if line:
# A hostname such as db[1:6]-node is considered to consists
@@ -166,7 +166,7 @@ class BaseInventoryPlugin(AnsiblePlugin):
self._vars = {}
def parse(self, inventory, loader, path, cache=True):
- ''' Populates inventory from the given data. Raises an error on any parse failure
+ """ Populates inventory from the given data. Raises an error on any parse failure
:arg inventory: a copy of the previously accumulated inventory data,
to be updated with any new data this plugin provides.
The inventory can be empty if no other source/plugin ran successfully.
@@ -177,7 +177,7 @@ class BaseInventoryPlugin(AnsiblePlugin):
but it can also be a raw string for this plugin to consume
:arg cache: a boolean that indicates if the plugin should use the cache or not
you can ignore if this plugin does not implement caching.
- '''
+ """
self.loader = loader
self.inventory = inventory
@@ -185,12 +185,12 @@ class BaseInventoryPlugin(AnsiblePlugin):
self._vars = load_extra_vars(loader)
def verify_file(self, path):
- ''' Verify if file is usable by this plugin, base does minimal accessibility check
+ """ Verify if file is usable by this plugin, base does minimal accessibility check
:arg path: a string that was passed as an inventory source,
it normally is a path to a config file, but this is not a requirement,
it can also be parsed itself as the inventory data to process.
So only call this base class if you expect it to be a file.
- '''
+ """
valid = False
b_path = to_bytes(path, errors='surrogate_or_strict')
@@ -210,9 +210,9 @@ class BaseInventoryPlugin(AnsiblePlugin):
self.inventory.set_variable(host, k, variables[k])
def _read_config_data(self, path):
- ''' validate config and set options as appropriate
+ """ validate config and set options as appropriate
:arg path: path to common yaml format config file for this plugin
- '''
+ """
config = {}
try:
@@ -244,20 +244,20 @@ class BaseInventoryPlugin(AnsiblePlugin):
return config
def _consume_options(self, data):
- ''' update existing options from alternate configuration sources not normally used by Ansible.
+ """ update existing options from alternate configuration sources not normally used by Ansible.
Many API libraries already have existing configuration sources, this allows plugin author to leverage them.
:arg data: key/value pairs that correspond to configuration options for this plugin
- '''
+ """
for k in self._options:
if k in data:
self._options[k] = data.pop(k)
def _expand_hostpattern(self, hostpattern):
- '''
+ """
Takes a single host pattern and returns a list of hostnames and an
optional port number that applies to all of them.
- '''
+ """
# Can the given hostpattern be parsed as a host with an optional port
# specification?
@@ -307,7 +307,7 @@ class Cacheable(object):
return "{0}_{1}".format(self.NAME, self._get_cache_prefix(path))
def _get_cache_prefix(self, path):
- ''' create predictable unique prefix for plugin/inventory '''
+ """ create predictable unique prefix for plugin/inventory """
m = hashlib.sha1()
m.update(to_bytes(self.NAME, errors='surrogate_or_strict'))
@@ -332,7 +332,7 @@ class Cacheable(object):
class Constructable(object):
def _compose(self, template, variables, disable_lookups=True):
- ''' helper method for plugins to compose variables for Ansible based on jinja2 expression and inventory vars'''
+ """ helper method for plugins to compose variables for Ansible based on jinja2 expression and inventory vars"""
t = self.templar
try:
@@ -349,7 +349,7 @@ class Constructable(object):
disable_lookups=disable_lookups)
def _set_composite_vars(self, compose, variables, host, strict=False):
- ''' loops over compose entries to create vars for hosts '''
+ """ loops over compose entries to create vars for hosts """
if compose and isinstance(compose, dict):
for varname in compose:
try:
@@ -361,7 +361,7 @@ class Constructable(object):
self.inventory.set_variable(host, varname, composite)
def _add_host_to_composed_groups(self, groups, variables, host, strict=False, fetch_hostvars=True):
- ''' helper to create complex groups for plugins based on jinja2 conditionals, hosts that meet the conditional are added to group'''
+ """ helper to create complex groups for plugins based on jinja2 conditionals, hosts that meet the conditional are added to group"""
# process each 'group entry'
if groups and isinstance(groups, dict):
if fetch_hostvars:
@@ -384,7 +384,7 @@ class Constructable(object):
self.inventory.add_child(group_name, host)
def _add_host_to_keyed_groups(self, keys, variables, host, strict=False, fetch_hostvars=True):
- ''' helper to create groups for plugins based on variable values and add the corresponding hosts to it'''
+ """ helper to create groups for plugins based on variable values and add the corresponding hosts to it"""
if keys and isinstance(keys, list):
for keyed in keys:
if keyed and isinstance(keyed, dict):
diff --git a/lib/ansible/plugins/inventory/advanced_host_list.py b/lib/ansible/plugins/inventory/advanced_host_list.py
index 9ca45b6b74..7a9646ef9a 100644
--- a/lib/ansible/plugins/inventory/advanced_host_list.py
+++ b/lib/ansible/plugins/inventory/advanced_host_list.py
@@ -3,22 +3,22 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: advanced_host_list
version_added: "2.4"
short_description: Parses a 'host list' with ranges
description:
- Parses a host list string as a comma separated values of hosts and supports host ranges.
- This plugin only applies to inventory sources that are not paths and contain at least one comma.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# simple range
# ansible -i 'host[1:10],' -m ping
# still supports w/o ranges also
# ansible-playbook -i 'localhost,' play.yml
-'''
+"""
import os
@@ -40,7 +40,7 @@ class InventoryModule(BaseInventoryPlugin):
return valid
def parse(self, inventory, loader, host_list, cache=True):
- ''' parses the inventory file '''
+ """ parses the inventory file """
super(InventoryModule, self).parse(inventory, loader, host_list)
diff --git a/lib/ansible/plugins/inventory/auto.py b/lib/ansible/plugins/inventory/auto.py
index 9948385ab4..81f0352911 100644
--- a/lib/ansible/plugins/inventory/auto.py
+++ b/lib/ansible/plugins/inventory/auto.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: auto
author:
- Matt Davis (@nitzmahone)
@@ -14,12 +14,12 @@ DOCUMENTATION = '''
C(plugin) key at its root will automatically cause the named plugin to be loaded and executed with that
config. This effectively provides automatic enabling of all installed/accessible inventory plugins.
- To disable this behavior, remove C(auto) from the C(INVENTORY_ENABLED) config element.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# This plugin is not intended for direct use; it is a fallback mechanism for automatic enabling of
# all installed inventory plugins.
-'''
+"""
from ansible.errors import AnsibleParserError
from ansible.plugins.inventory import BaseInventoryPlugin
diff --git a/lib/ansible/plugins/inventory/constructed.py b/lib/ansible/plugins/inventory/constructed.py
index 98f6178594..ee2b9b4295 100644
--- a/lib/ansible/plugins/inventory/constructed.py
+++ b/lib/ansible/plugins/inventory/constructed.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: constructed
version_added: "2.4"
short_description: Uses Jinja2 to construct vars and groups based on existing inventory.
@@ -33,9 +33,9 @@ DOCUMENTATION = '''
version_added: '2.11'
extends_documentation_fragment:
- constructed
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# inventory.config file in YAML format
plugin: ansible.builtin.constructed
strict: False
@@ -77,7 +77,7 @@ EXAMPLES = r'''
# this creates a common parent group for all ec2 availability zones
- key: placement.availability_zone
parent_group: all_ec2_zones
-'''
+"""
import os
@@ -114,11 +114,11 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
return valid
def get_all_host_vars(self, host, loader, sources):
- ''' requires host object '''
+ """ requires host object """
return combine_vars(self.host_groupvars(host, loader, sources), self.host_vars(host, loader, sources))
def host_groupvars(self, host, loader, sources):
- ''' requires host object '''
+ """ requires host object """
gvars = get_group_vars(host.get_groups())
if self.get_option('use_vars_plugins'):
@@ -127,7 +127,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
return gvars
def host_vars(self, host, loader, sources):
- ''' requires host object '''
+ """ requires host object """
hvars = host.get_vars()
if self.get_option('use_vars_plugins'):
@@ -136,7 +136,7 @@ class InventoryModule(BaseInventoryPlugin, Constructable):
return hvars
def parse(self, inventory, loader, path, cache=False):
- ''' parses the inventory file '''
+ """ parses the inventory file """
super(InventoryModule, self).parse(inventory, loader, path, cache=cache)
diff --git a/lib/ansible/plugins/inventory/generator.py b/lib/ansible/plugins/inventory/generator.py
index ba697dfca6..49c8550403 100644
--- a/lib/ansible/plugins/inventory/generator.py
+++ b/lib/ansible/plugins/inventory/generator.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: generator
version_added: "2.6"
short_description: Uses Jinja2 to construct hosts and groups from patterns
@@ -32,9 +32,9 @@ DOCUMENTATION = '''
description:
- A dictionary of layers, with the key being the layer name, used as a variable name in the C(host)
C(name) and C(parents) keys. Each layer value is a list of possible values for that layer.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# inventory.config file in YAML format
# remember to enable this inventory plugin in the ansible.cfg before using
# View the output using `ansible-inventory -i inventory.config --list`
@@ -68,7 +68,7 @@ EXAMPLES = '''
application:
- web
- api
-'''
+"""
import os
@@ -118,7 +118,7 @@ class InventoryModule(BaseInventoryPlugin):
self.add_parents(inventory, groupname, parent.get('parents', []), template_vars)
def parse(self, inventory, loader, path, cache=False):
- ''' parses the inventory file '''
+ """ parses the inventory file """
super(InventoryModule, self).parse(inventory, loader, path, cache=cache)
diff --git a/lib/ansible/plugins/inventory/host_list.py b/lib/ansible/plugins/inventory/host_list.py
index c9ffcc8fd1..8cfe9e50aa 100644
--- a/lib/ansible/plugins/inventory/host_list.py
+++ b/lib/ansible/plugins/inventory/host_list.py
@@ -3,16 +3,16 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
name: host_list
version_added: "2.4"
short_description: Parses a 'host list' string
description:
- Parses a host list string as a comma separated values of hosts
- This plugin only applies to inventory strings that are not paths and contain a comma.
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# define 2 hosts in command line
# ansible -i '10.10.2.6, 10.10.2.4' -m ping all
@@ -21,7 +21,7 @@ EXAMPLES = r'''
# just use localhost
# ansible-playbook -i 'localhost,' play.yml -c local
-'''
+"""
import os
@@ -44,7 +44,7 @@ class InventoryModule(BaseInventoryPlugin):
return valid
def parse(self, inventory, loader, host_list, cache=True):
- ''' parses the inventory file '''
+ """ parses the inventory file """
super(InventoryModule, self).parse(inventory, loader, host_list)
diff --git a/lib/ansible/plugins/inventory/ini.py b/lib/ansible/plugins/inventory/ini.py
index e2efde10ab..cd961bcdb0 100644
--- a/lib/ansible/plugins/inventory/ini.py
+++ b/lib/ansible/plugins/inventory/ini.py
@@ -2,7 +2,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: ini
version_added: "2.4"
short_description: Uses an Ansible INI file as inventory source.
@@ -27,9 +27,9 @@ DOCUMENTATION = '''
- Enabled in configuration by default.
- Consider switching to YAML format for inventory sources to avoid confusion on the actual type of a variable.
The YAML inventory plugin processes variable values consistently and correctly.
-'''
+"""
-EXAMPLES = '''# fmt: ini
+EXAMPLES = """# fmt: ini
# Example 1
[web]
host1
@@ -70,7 +70,7 @@ host4
[g2]
host4 # same host as above, but member of 2 groups, will inherit vars from both
# inventory hostnames are unique
-'''
+"""
import ast
import re
@@ -140,10 +140,10 @@ class InventoryModule(BaseFileInventoryPlugin):
raise AnsibleError("%s:%d: " % (self._filename, self.lineno) + message)
def _parse(self, path, lines):
- '''
+ """
Populates self.groups from the given array of lines. Raises an error on
any parse failure.
- '''
+ """
self._compile_patterns()
@@ -255,10 +255,10 @@ class InventoryModule(BaseFileInventoryPlugin):
del pending[group]
def _parse_group_name(self, line):
- '''
+ """
Takes a single line and tries to parse it as a group name. Returns the
group name if successful, or raises an error.
- '''
+ """
m = self.patterns['groupname'].match(line)
if m:
@@ -267,10 +267,10 @@ class InventoryModule(BaseFileInventoryPlugin):
self._raise_error("Expected group name, got: %s" % (line))
def _parse_variable_definition(self, line):
- '''
+ """
Takes a string and tries to parse it as a variable definition. Returns
the key and value if successful, or raises an error.
- '''
+ """
# TODO: We parse variable assignments as a key (anything to the left of
# an '='"), an '=', and a value (anything left) and leave the value to
@@ -284,10 +284,10 @@ class InventoryModule(BaseFileInventoryPlugin):
self._raise_error("Expected key=value, got: %s" % (line))
def _parse_host_definition(self, line):
- '''
+ """
Takes a single line and tries to parse it as a host definition. Returns
a list of Hosts if successful, or raises an error.
- '''
+ """
# A host definition comprises (1) a non-whitespace hostname or range,
# optionally followed by (2) a series of key="some value" assignments.
@@ -317,9 +317,9 @@ class InventoryModule(BaseFileInventoryPlugin):
return hostnames, port, variables
def _expand_hostpattern(self, hostpattern):
- '''
+ """
do some extra checks over normal processing
- '''
+ """
# specification?
hostnames, port = super(InventoryModule, self)._expand_hostpattern(hostpattern)
@@ -336,10 +336,10 @@ class InventoryModule(BaseFileInventoryPlugin):
@staticmethod
def _parse_value(v):
- '''
+ """
Attempt to transform the string value from an ini file into a basic python object
(int, dict, list, unicode string, etc).
- '''
+ """
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
@@ -355,10 +355,10 @@ class InventoryModule(BaseFileInventoryPlugin):
return to_text(v, nonstring='passthru', errors='surrogate_or_strict')
def _compile_patterns(self):
- '''
+ """
Compiles the regular expressions required to parse the inventory and
stores them in self.patterns.
- '''
+ """
# Section names are square-bracketed expressions at the beginning of a
# line, comprising (1) a group name optionally followed by (2) a tag
@@ -370,14 +370,14 @@ class InventoryModule(BaseFileInventoryPlugin):
# [naughty:children] # only get coal in their stockings
self.patterns['section'] = re.compile(
- to_text(r'''^\[
+ to_text(r"""^\[
([^:\]\s]+) # group name (see groupname below)
(?::(\w+))? # optional : and tag name
\]
\s* # ignore trailing whitespace
(?:\#.*)? # and/or a comment till the
$ # end of the line
- ''', errors='surrogate_or_strict'), re.X
+ """, errors='surrogate_or_strict'), re.X
)
# FIXME: What are the real restrictions on group names, or rather, what
@@ -386,10 +386,10 @@ class InventoryModule(BaseFileInventoryPlugin):
# precise rules in order to support better diagnostics.
self.patterns['groupname'] = re.compile(
- to_text(r'''^
+ to_text(r"""^
([^:\]\s]+)
\s* # ignore trailing whitespace
(?:\#.*)? # and/or a comment till the
$ # end of the line
- ''', errors='surrogate_or_strict'), re.X
+ """, errors='surrogate_or_strict'), re.X
)
diff --git a/lib/ansible/plugins/inventory/script.py b/lib/ansible/plugins/inventory/script.py
index c40f39c73e..9c8ecf5454 100644
--- a/lib/ansible/plugins/inventory/script.py
+++ b/lib/ansible/plugins/inventory/script.py
@@ -168,7 +168,7 @@ display = Display()
class InventoryModule(BaseInventoryPlugin):
- ''' Host inventory parser for ansible using external inventory scripts. '''
+ """ Host inventory parser for ansible using external inventory scripts. """
NAME = 'script'
@@ -179,7 +179,7 @@ class InventoryModule(BaseInventoryPlugin):
self._hosts = set()
def verify_file(self, path):
- ''' Verify if file is usable by this plugin, base does minimal accessibility check '''
+ """ Verify if file is usable by this plugin, base does minimal accessibility check """
valid = super(InventoryModule, self).verify_file(path)
diff --git a/lib/ansible/plugins/inventory/toml.py b/lib/ansible/plugins/inventory/toml.py
index 39a3d5c9aa..ff33ccd319 100644
--- a/lib/ansible/plugins/inventory/toml.py
+++ b/lib/ansible/plugins/inventory/toml.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
name: toml
version_added: "2.8"
short_description: Uses a specific TOML file as an inventory source.
@@ -13,9 +13,9 @@ DOCUMENTATION = r'''
notes:
- >
Requires one of the following python libraries: 'toml', 'tomli', or 'tomllib'
-'''
+"""
-EXAMPLES = r'''# fmt: toml
+EXAMPLES = r"""# fmt: toml
# Example 1
[all.vars]
has_java = false
@@ -84,7 +84,7 @@ host4 = {}
[g2.hosts]
host4 = {}
-'''
+"""
import os
import typing as t
@@ -265,7 +265,7 @@ class InventoryModule(BaseFileInventoryPlugin):
)
def parse(self, inventory, loader, path, cache=True):
- ''' parses the inventory file '''
+ """ parses the inventory file """
if not HAS_TOMLLIB and not HAS_TOML:
# tomllib works here too, but we don't call it out in the error,
# since you either have it or not as part of cpython stdlib >= 3.11
diff --git a/lib/ansible/plugins/inventory/yaml.py b/lib/ansible/plugins/inventory/yaml.py
index 3625ed4253..1197be33ce 100644
--- a/lib/ansible/plugins/inventory/yaml.py
+++ b/lib/ansible/plugins/inventory/yaml.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: yaml
version_added: "2.4"
short_description: Uses a specific YAML file as an inventory source.
@@ -31,8 +31,8 @@ DOCUMENTATION = '''
- section: inventory_plugin_yaml
key: yaml_valid_extensions
-'''
-EXAMPLES = '''
+"""
+EXAMPLES = """
all: # keys must be unique, i.e. only one 'hosts' per group
hosts:
test1:
@@ -63,7 +63,7 @@ all: # keys must be unique, i.e. only one 'hosts' per group
test1 # same host as above, additional group membership
vars:
group_last_var: value
-'''
+"""
import os
@@ -95,7 +95,7 @@ class InventoryModule(BaseFileInventoryPlugin):
return valid
def parse(self, inventory, loader, path, cache=True):
- ''' parses the inventory file '''
+ """ parses the inventory file """
super(InventoryModule, self).parse(inventory, loader, path)
self.set_options()
@@ -170,9 +170,9 @@ class InventoryModule(BaseFileInventoryPlugin):
return group
def _parse_host(self, host_pattern):
- '''
+ """
Each host key can be a pattern, try to process it and add variables as needed
- '''
+ """
try:
(hostnames, port) = self._expand_hostpattern(host_pattern)
except TypeError:
diff --git a/lib/ansible/plugins/loader.py b/lib/ansible/plugins/loader.py
index 266b67d11b..c24d062823 100644
--- a/lib/ansible/plugins/loader.py
+++ b/lib/ansible/plugins/loader.py
@@ -57,7 +57,7 @@ def get_all_plugin_loaders():
def add_all_plugin_dirs(path):
- ''' add any existing plugin dirs in the path provided '''
+ """ add any existing plugin dirs in the path provided """
b_path = os.path.expanduser(to_bytes(path, errors='surrogate_or_strict'))
if os.path.isdir(b_path):
for name, obj in get_all_plugin_loaders():
@@ -198,12 +198,12 @@ class PluginLoadContext(object):
class PluginLoader:
- '''
+ """
PluginLoader loads plugins from the configured plugin directories.
It searches for plugins by iterating through the combined list of play basedirs, configured
paths, and the python path. The first match is used.
- '''
+ """
def __init__(self, class_name, package, config, subdir, aliases=None, required_base_class=None):
aliases = {} if aliases is None else aliases
@@ -266,9 +266,9 @@ class PluginLoader:
self._searched_paths = set()
def __setstate__(self, data):
- '''
+ """
Deserializer.
- '''
+ """
class_name = data.get('class_name')
package = data.get('package')
@@ -285,9 +285,9 @@ class PluginLoader:
self._searched_paths = data.get('_searched_paths', set())
def __getstate__(self):
- '''
+ """
Serializer.
- '''
+ """
return dict(
class_name=self.class_name,
@@ -303,7 +303,7 @@ class PluginLoader:
)
def format_paths(self, paths):
- ''' Returns a string suitable for printing of the search path '''
+ """ Returns a string suitable for printing of the search path """
# Uses a list to get the order right
ret = []
@@ -325,7 +325,7 @@ class PluginLoader:
return results
def _get_package_paths(self, subdirs=True):
- ''' Gets the path of a Python package '''
+ """ Gets the path of a Python package """
if not self.package:
return []
@@ -340,7 +340,7 @@ class PluginLoader:
return [self.package_path]
def _get_paths_with_context(self, subdirs=True):
- ''' Return a list of PluginPathContext objects to search for plugins in '''
+ """ Return a list of PluginPathContext objects to search for plugins in """
# FIXME: This is potentially buggy if subdirs is sometimes True and sometimes False.
# In current usage, everything calls this with subdirs=True except for module_utils_loader and ansible-doc
@@ -393,13 +393,13 @@ class PluginLoader:
return ret
def _get_paths(self, subdirs=True):
- ''' Return a list of paths to search for plugins in '''
+ """ Return a list of paths to search for plugins in """
paths_with_context = self._get_paths_with_context(subdirs=subdirs)
return [path_with_context.path for path_with_context in paths_with_context]
def _load_config_defs(self, name, module, path):
- ''' Reads plugin docs to find configuration setting definitions, to push to config manager for later use '''
+ """ Reads plugin docs to find configuration setting definitions, to push to config manager for later use """
# plugins w/o class name don't support config
if self.class_name:
@@ -422,7 +422,7 @@ class PluginLoader:
display.debug('Loaded config def from plugin (%s/%s)' % (type_name, name))
def add_directory(self, directory, with_subdir=False):
- ''' Adds an additional directory to the search path '''
+ """ Adds an additional directory to the search path """
directory = os.path.realpath(directory)
@@ -576,7 +576,7 @@ class PluginLoader:
'found fuzzy extension match for {0} in {1}'.format(full_name, acr.collection), action_plugin)
def find_plugin(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None):
- ''' Find a plugin named name '''
+ """ Find a plugin named name """
result = self.find_plugin_with_context(name, mod_type, ignore_deprecated, check_aliases, collection_list)
if result.resolved and result.plugin_resolved_path:
return result.plugin_resolved_path
@@ -584,7 +584,7 @@ class PluginLoader:
return None
def find_plugin_with_context(self, name, mod_type='', ignore_deprecated=False, check_aliases=False, collection_list=None):
- ''' Find a plugin named name, returning contextual info about the load, recursively resolving redirection '''
+ """ Find a plugin named name, returning contextual info about the load, recursively resolving redirection """
plugin_load_context = PluginLoadContext()
plugin_load_context.original_name = name
while True:
@@ -794,7 +794,7 @@ class PluginLoader:
return plugin_load_context.nope('{0} is not eligible for last-chance resolution'.format(name))
def has_plugin(self, name, collection_list=None):
- ''' Checks if a plugin named name exists '''
+ """ Checks if a plugin named name exists """
try:
return self.find_plugin(name, collection_list=collection_list) is not None
@@ -860,7 +860,7 @@ class PluginLoader:
return self.get_with_context(name, *args, **kwargs).object
def get_with_context(self, name, *args, **kwargs):
- ''' instantiates a plugin of the given name using arguments '''
+ """ instantiates a plugin of the given name using arguments """
found_in_cache = True
class_only = kwargs.pop('class_only', False)
@@ -938,7 +938,7 @@ class PluginLoader:
return get_with_context_result(obj, plugin_load_context)
def _display_plugin_load(self, class_name, name, searched_paths, path, found_in_cache=None, class_only=None):
- ''' formats data to display debug info for plugin loading, also avoids processing unless really needed '''
+ """ formats data to display debug info for plugin loading, also avoids processing unless really needed """
if C.DEFAULT_DEBUG:
msg = 'Loading %s \'%s\' from %s' % (class_name, os.path.basename(name), path)
@@ -951,7 +951,7 @@ class PluginLoader:
display.debug(msg)
def all(self, *args, **kwargs):
- '''
+ """
Iterate through all plugins of this type, in configured paths (no collections)
A plugin loader is initialized with a specific type. This function is an iterator returning
@@ -972,7 +972,7 @@ class PluginLoader:
want to manage their own deduplication of the plugins.
:*args: Any extra arguments are passed to each plugin when it is instantiated.
:**kwargs: Any extra keyword arguments are passed to each plugin when it is instantiated.
- '''
+ """
# TODO: Change the signature of this method to:
# def all(return_type='instance', args=None, kwargs=None):
# if args is None: args = []
diff --git a/lib/ansible/plugins/lookup/__init__.py b/lib/ansible/plugins/lookup/__init__.py
index bc15943ef5..373a386ddc 100644
--- a/lib/ansible/plugins/lookup/__init__.py
+++ b/lib/ansible/plugins/lookup/__init__.py
@@ -104,9 +104,9 @@ class LookupBase(AnsiblePlugin):
pass
def find_file_in_search_path(self, myvars, subdir, needle, ignore_missing=False):
- '''
+ """
Return a file (needle) in the task's expected search path.
- '''
+ """
if 'ansible_search_path' in myvars:
paths = myvars['ansible_search_path']
diff --git a/lib/ansible/plugins/lookup/ini.py b/lib/ansible/plugins/lookup/ini.py
index 9d5c289e1f..765c74cc4c 100644
--- a/lib/ansible/plugins/lookup/ini.py
+++ b/lib/ansible/plugins/lookup/ini.py
@@ -98,7 +98,7 @@ from ansible.plugins.lookup import LookupBase
def _parse_params(term, paramvals):
- '''Safely split parameter term to preserve spaces'''
+ """Safely split parameter term to preserve spaces"""
# TODO: deprecate this method
valid_keys = paramvals.keys()
diff --git a/lib/ansible/plugins/lookup/password.py b/lib/ansible/plugins/lookup/password.py
index 84894e21e9..bbecd3e5ae 100644
--- a/lib/ansible/plugins/lookup/password.py
+++ b/lib/ansible/plugins/lookup/password.py
@@ -160,7 +160,7 @@ def _read_password_file(b_path):
def _gen_candidate_chars(characters):
- '''Generate a string containing all valid chars as defined by ``characters``
+ """Generate a string containing all valid chars as defined by ``characters``
:arg characters: A list of character specs. The character specs are
shorthand names for sets of characters like 'digits', 'ascii_letters',
@@ -181,7 +181,7 @@ def _gen_candidate_chars(characters):
the question mark and pipe characters directly. Return will be the string::
u'0123456789?|'
- '''
+ """
chars = []
for chars_spec in characters:
# getattr from string expands things like "ascii_letters" and "digits"
@@ -192,11 +192,11 @@ def _gen_candidate_chars(characters):
def _parse_content(content):
- '''parse our password data format into password and salt
+ """parse our password data format into password and salt
:arg content: The data read from the file
:returns: password and salt
- '''
+ """
password = content
salt = None
ident = None
diff --git a/lib/ansible/plugins/shell/__init__.py b/lib/ansible/plugins/shell/__init__.py
index 1da3b1f6d1..884af0c5a1 100644
--- a/lib/ansible/plugins/shell/__init__.py
+++ b/lib/ansible/plugins/shell/__init__.py
@@ -164,7 +164,7 @@ class ShellBase(AnsiblePlugin):
return cmd
def expand_user(self, user_home_path, username=''):
- ''' Return a command to expand tildes in a path
+ """ Return a command to expand tildes in a path
It can be either "~" or "~username". We just ignore $HOME
We use the POSIX definition of a username:
@@ -172,7 +172,7 @@ class ShellBase(AnsiblePlugin):
http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap03.html#tag_03_276
Falls back to 'current working directory' as we assume 'home is where the remote user ends up'
- '''
+ """
# Check that the user_path to expand is safe
if user_home_path != '~':
diff --git a/lib/ansible/plugins/shell/cmd.py b/lib/ansible/plugins/shell/cmd.py
index db851df685..96740eabad 100644
--- a/lib/ansible/plugins/shell/cmd.py
+++ b/lib/ansible/plugins/shell/cmd.py
@@ -2,7 +2,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: cmd
version_added: '2.8'
short_description: Windows Command Prompt
@@ -10,7 +10,7 @@ description:
- Used with the 'ssh' connection plugin and no C(DefaultShell) has been set on the Windows host.
extends_documentation_fragment:
- shell_windows
-'''
+"""
import re
diff --git a/lib/ansible/plugins/shell/powershell.py b/lib/ansible/plugins/shell/powershell.py
index 22ba2ca537..a6e10b4a9f 100644
--- a/lib/ansible/plugins/shell/powershell.py
+++ b/lib/ansible/plugins/shell/powershell.py
@@ -284,7 +284,7 @@ class ShellModule(ShellBase):
return '& %s; exit $LASTEXITCODE' % cmd
def _unquote(self, value):
- '''Remove any matching quotes that wrap the given value.'''
+ """Remove any matching quotes that wrap the given value."""
value = to_text(value or '')
m = re.match(r'^\s*?\'(.*?)\'\s*?$', value)
if m:
@@ -295,13 +295,13 @@ class ShellModule(ShellBase):
return value
def _escape(self, value):
- '''Return value escaped for use in PowerShell single quotes.'''
+ """Return value escaped for use in PowerShell single quotes."""
# There are 5 chars that need to be escaped in a single quote.
# https://github.com/PowerShell/PowerShell/blob/b7cb335f03fe2992d0cbd61699de9d9aafa1d7c1/src/System.Management.Automation/engine/parser/CharTraits.cs#L265-L272
return re.compile(u"(['\u2018\u2019\u201a\u201b])").sub(u'\\1\\1', value)
def _encode_script(self, script, as_list=False, strict_mode=True, preserve_rc=True):
- '''Convert a PowerShell script to a single base64-encoded command.'''
+ """Convert a PowerShell script to a single base64-encoded command."""
script = to_text(script)
if script == u'-':
diff --git a/lib/ansible/plugins/shell/sh.py b/lib/ansible/plugins/shell/sh.py
index ef85596c26..fc143fd7aa 100644
--- a/lib/ansible/plugins/shell/sh.py
+++ b/lib/ansible/plugins/shell/sh.py
@@ -3,7 +3,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: sh
short_description: "POSIX shell (/bin/sh)"
version_added: historical
@@ -11,7 +11,7 @@ description:
- This shell plugin is the one you want to use on most Unix systems, it is the most compatible and widely installed shell.
extends_documentation_fragment:
- shell_common
-'''
+"""
from ansible.plugins.shell import ShellBase
diff --git a/lib/ansible/plugins/strategy/__init__.py b/lib/ansible/plugins/strategy/__init__.py
index c2a3e8a618..3eb5538b96 100644
--- a/lib/ansible/plugins/strategy/__init__.py
+++ b/lib/ansible/plugins/strategy/__init__.py
@@ -222,10 +222,10 @@ def debug_closure(func):
class StrategyBase:
- '''
+ """
This is the base class for strategy plugins, which contains some common
code useful to all strategies like running handlers, cleanup actions, etc.
- '''
+ """
# by default, strategies should support throttling but we allow individual
# strategies to disable this and either forego supporting it or managing
@@ -340,15 +340,15 @@ class StrategyBase:
return [host for host in self._hosts_cache if host in self._tqm._failed_hosts]
def add_tqm_variables(self, vars, play):
- '''
+ """
Base class method to add extra variables/information to the list of task
vars sent through the executor engine regarding the task queue manager state.
- '''
+ """
vars['ansible_current_hosts'] = self.get_hosts_remaining(play)
vars['ansible_failed_hosts'] = self.get_failed_hosts(play)
def _queue_task(self, host, task, task_vars, play_context):
- ''' handles queueing the task up to be sent to a worker '''
+ """ handles queueing the task up to be sent to a worker """
display.debug("entering _queue_task() for %s/%s" % (host.name, task.action))
@@ -559,10 +559,10 @@ class StrategyBase:
@debug_closure
def _process_pending_results(self, iterator, one_pass=False, max_passes=None):
- '''
+ """
Reads results off the final queue and takes appropriate action
based on the result (executing callbacks, updating state, etc.).
- '''
+ """
ret_results = []
cur_pass = 0
while True:
@@ -797,10 +797,10 @@ class StrategyBase:
return ret_results
def _wait_on_pending_results(self, iterator):
- '''
+ """
Wait for the shared counter to drop to zero, using a short sleep
between checks to ensure we don't spin lock
- '''
+ """
ret_results = []
@@ -820,9 +820,9 @@ class StrategyBase:
return ret_results
def _copy_included_file(self, included_file):
- '''
+ """
A proven safe and performant way to create a copy of an included file
- '''
+ """
ti_copy = included_file._task.copy(exclude_parent=True)
ti_copy._parent = included_file._task._parent
@@ -833,13 +833,13 @@ class StrategyBase:
return ti_copy
def _load_included_file(self, included_file, iterator, is_handler=False, handle_stats_and_callbacks=True):
- '''
+ """
Loads an included YAML file of tasks, applying the optional set of variables.
Raises AnsibleError exception in case of a failure during including a file,
in such case the caller is responsible for marking the host(s) as failed
using PlayIterator.mark_host_failed().
- '''
+ """
if handle_stats_and_callbacks:
display.deprecated(
"Reporting play recap stats and running callbacks functionality for "
@@ -1105,7 +1105,7 @@ class StrategyBase:
return play._get_cached_role(task._role)
def get_hosts_left(self, iterator):
- ''' returns list of available hosts for this iterator by filtering out unreachables '''
+ """ returns list of available hosts for this iterator by filtering out unreachables """
hosts_left = []
for host in self._hosts_cache:
@@ -1117,7 +1117,7 @@ class StrategyBase:
return hosts_left
def update_active_connections(self, results):
- ''' updates the current active persistent connections '''
+ """ updates the current active persistent connections """
for r in results:
if 'args' in r._task_fields:
socket_path = r._task_fields['args'].get('_ansible_socket')
diff --git a/lib/ansible/plugins/strategy/debug.py b/lib/ansible/plugins/strategy/debug.py
index 6ee294b4dd..6c1fd5a1f5 100644
--- a/lib/ansible/plugins/strategy/debug.py
+++ b/lib/ansible/plugins/strategy/debug.py
@@ -14,14 +14,14 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: debug
short_description: Executes tasks in interactive debug session.
description:
- Task execution is 'linear' but controlled by an interactive debug session.
version_added: "2.1"
author: Kishin Yagami (!UNKNOWN)
-'''
+"""
from ansible.plugins.strategy.linear import StrategyModule as LinearStrategyModule
diff --git a/lib/ansible/plugins/strategy/free.py b/lib/ansible/plugins/strategy/free.py
index 90840dab63..6fca97301b 100644
--- a/lib/ansible/plugins/strategy/free.py
+++ b/lib/ansible/plugins/strategy/free.py
@@ -16,7 +16,7 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: free
short_description: Executes tasks without waiting for all hosts
description:
@@ -27,7 +27,7 @@ DOCUMENTATION = '''
won't hold up the rest of the hosts and tasks.
version_added: "2.0"
author: Ansible Core Team
-'''
+"""
import time
@@ -54,7 +54,7 @@ class StrategyModule(StrategyBase):
self._host_pinned = False
def run(self, iterator, play_context):
- '''
+ """
The "free" strategy is a bit more complex, in that it allows tasks to
be sent to hosts as quickly as they can be processed. This means that
some hosts may finish very quickly if run tasks result in little or no
@@ -65,7 +65,7 @@ class StrategyModule(StrategyBase):
and starting the search from there as opposed to the top of the hosts
list again, which would end up favoring hosts near the beginning of the
list.
- '''
+ """
# the last host to be given a task
last_host = 0
diff --git a/lib/ansible/plugins/strategy/host_pinned.py b/lib/ansible/plugins/strategy/host_pinned.py
index f06550f9ff..aa25ff32b4 100644
--- a/lib/ansible/plugins/strategy/host_pinned.py
+++ b/lib/ansible/plugins/strategy/host_pinned.py
@@ -16,7 +16,7 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: host_pinned
short_description: Executes tasks on each host without interruption
description:
@@ -28,7 +28,7 @@ DOCUMENTATION = '''
Other than that, it behaves just like the "free" strategy.
version_added: "2.7"
author: Ansible Core Team
-'''
+"""
from ansible.plugins.strategy.free import StrategyModule as FreeStrategyModule
from ansible.utils.display import Display
diff --git a/lib/ansible/plugins/strategy/linear.py b/lib/ansible/plugins/strategy/linear.py
index c6815a38de..372a05f0e1 100644
--- a/lib/ansible/plugins/strategy/linear.py
+++ b/lib/ansible/plugins/strategy/linear.py
@@ -16,7 +16,7 @@
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: linear
short_description: Executes tasks in a linear fashion
description:
@@ -27,7 +27,7 @@ DOCUMENTATION = '''
notes:
- This was the default Ansible behaviour before 'strategy plugins' were introduced in 2.0.
author: Ansible Core Team
-'''
+"""
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleAssertionError, AnsibleParserError
@@ -45,11 +45,11 @@ display = Display()
class StrategyModule(StrategyBase):
def _get_next_task_lockstep(self, hosts, iterator):
- '''
+ """
Returns a list of (host, task) tuples, where the task may
be a noop task to keep the iterator in lock step across
all hosts.
- '''
+ """
state_task_per_host = {}
for host in hosts:
state, task = iterator.get_next_task_for_host(host, peek=True)
@@ -90,11 +90,11 @@ class StrategyModule(StrategyBase):
return host_tasks
def run(self, iterator, play_context):
- '''
+ """
The linear strategy is simple - get the next task and queue
it for all hosts, then wait for the queue to drain before
moving on to the next task
- '''
+ """
# iterate over each task, while there is one left to run
result = self._tqm.RUN_OK
diff --git a/lib/ansible/plugins/terminal/__init__.py b/lib/ansible/plugins/terminal/__init__.py
index fe7dc3103a..1db6aeb4fa 100644
--- a/lib/ansible/plugins/terminal/__init__.py
+++ b/lib/ansible/plugins/terminal/__init__.py
@@ -26,7 +26,7 @@ from ansible.errors import AnsibleConnectionFailure
class TerminalBase(ABC):
- '''
+ """
A base class for implementing cli connections
.. note:: Unlike most of Ansible, nearly all strings in
@@ -36,7 +36,7 @@ class TerminalBase(ABC):
:func:`~ansible.module_utils.common.text.converters.to_bytes` and
:func:`~ansible.module_utils.common.text.converters.to_text` to avoid unexpected
problems.
- '''
+ """
#: compiled bytes regular expressions as stdout
terminal_stdout_re = [] # type: list[re.Pattern]
@@ -64,11 +64,11 @@ class TerminalBase(ABC):
self._connection = connection
def _exec_cli_command(self, cmd, check_rc=True):
- '''
+ """
Executes the CLI command on the remote device and returns the output
:arg cmd: Byte string command to be executed
- '''
+ """
return self._connection.exec_command(cmd)
def _get_prompt(self):
diff --git a/lib/ansible/plugins/test/core.py b/lib/ansible/plugins/test/core.py
index ed357a4bba..95ac93c47a 100644
--- a/lib/ansible/plugins/test/core.py
+++ b/lib/ansible/plugins/test/core.py
@@ -41,38 +41,38 @@ display = Display()
def timedout(result):
- ''' Test if task result yields a time out'''
+ """ Test if task result yields a time out"""
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'timedout' test expects a dictionary")
return result.get('timedout', False) and result['timedout'].get('period', False)
def failed(result):
- ''' Test if task result yields failed '''
+ """ Test if task result yields failed """
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'failed' test expects a dictionary")
return result.get('failed', False)
def success(result):
- ''' Test if task result yields success '''
+ """ Test if task result yields success """
return not failed(result)
def unreachable(result):
- ''' Test if task result yields unreachable '''
+ """ Test if task result yields unreachable """
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'unreachable' test expects a dictionary")
return result.get('unreachable', False)
def reachable(result):
- ''' Test if task result yields reachable '''
+ """ Test if task result yields reachable """
return not unreachable(result)
def changed(result):
- ''' Test if task result yields changed '''
+ """ Test if task result yields changed """
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'changed' test expects a dictionary")
if 'changed' not in result:
@@ -92,14 +92,14 @@ def changed(result):
def skipped(result):
- ''' Test if task result yields skipped '''
+ """ Test if task result yields skipped """
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'skipped' test expects a dictionary")
return result.get('skipped', False)
def started(result):
- ''' Test if async task has started '''
+ """ Test if async task has started """
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'started' test expects a dictionary")
if 'started' in result:
@@ -113,7 +113,7 @@ def started(result):
def finished(result):
- ''' Test if async task has finished '''
+ """ Test if async task has finished """
if not isinstance(result, MutableMapping):
raise errors.AnsibleFilterError("The 'finished' test expects a dictionary")
if 'finished' in result:
@@ -127,10 +127,10 @@ def finished(result):
def regex(value='', pattern='', ignorecase=False, multiline=False, match_type='search'):
- ''' Expose `re` as a boolean filter using the `search` method by default.
+ """ Expose `re` as a boolean filter using the `search` method by default.
This is likely only useful for `search` and `match` which already
have their own filters.
- '''
+ """
# In addition to ensuring the correct type, to_text here will ensure
# _fail_with_undefined_error happens if the value is Undefined
value = to_text(value, errors='surrogate_or_strict')
@@ -164,17 +164,17 @@ def vaulted_file(value):
def match(value, pattern='', ignorecase=False, multiline=False):
- ''' Perform a `re.match` returning a boolean '''
+ """ Perform a `re.match` returning a boolean """
return regex(value, pattern, ignorecase, multiline, 'match')
def search(value, pattern='', ignorecase=False, multiline=False):
- ''' Perform a `re.search` returning a boolean '''
+ """ Perform a `re.search` returning a boolean """
return regex(value, pattern, ignorecase, multiline, 'search')
def version_compare(value, version, operator='eq', strict=None, version_type=None):
- ''' Perform a version comparison on a value '''
+ """ Perform a version comparison on a value """
op_map = {
'==': 'eq', '=': 'eq', 'eq': 'eq',
'<': 'lt', 'lt': 'lt',
@@ -258,7 +258,7 @@ def falsy(value, convert_bool=False):
class TestModule(object):
- ''' Ansible core jinja2 tests '''
+ """ Ansible core jinja2 tests """
def tests(self):
return {
diff --git a/lib/ansible/plugins/test/files.py b/lib/ansible/plugins/test/files.py
index fc142b72a6..7fcbb66a2d 100644
--- a/lib/ansible/plugins/test/files.py
+++ b/lib/ansible/plugins/test/files.py
@@ -21,7 +21,7 @@ from os.path import isdir, isfile, isabs, exists, lexists, islink, samefile, ism
class TestModule(object):
- ''' Ansible file jinja2 tests '''
+ """ Ansible file jinja2 tests """
def tests(self):
return {
diff --git a/lib/ansible/plugins/test/mathstuff.py b/lib/ansible/plugins/test/mathstuff.py
index 4bf33e8828..5ef5a8cf31 100644
--- a/lib/ansible/plugins/test/mathstuff.py
+++ b/lib/ansible/plugins/test/mathstuff.py
@@ -36,15 +36,15 @@ def isnotanumber(x):
def contains(seq, value):
- '''Opposite of the ``in`` test, allowing use as a test in filters like ``selectattr``
+ """Opposite of the ``in`` test, allowing use as a test in filters like ``selectattr``
.. versionadded:: 2.8
- '''
+ """
return value in seq
class TestModule:
- ''' Ansible math jinja2 tests '''
+ """ Ansible math jinja2 tests """
def tests(self):
return {
diff --git a/lib/ansible/plugins/test/uri.py b/lib/ansible/plugins/test/uri.py
index b9679d0c13..1eaaf80ac9 100644
--- a/lib/ansible/plugins/test/uri.py
+++ b/lib/ansible/plugins/test/uri.py
@@ -6,7 +6,7 @@ from urllib.parse import urlparse
def is_uri(value, schemes=None):
- ''' Will verify that the string passed is a valid 'URI', if given a list of valid schemes it will match those '''
+ """ Will verify that the string passed is a valid 'URI', if given a list of valid schemes it will match those """
try:
x = urlparse(value)
isit = all([x.scheme is not None, x.path is not None, not schemes or x.scheme in schemes])
@@ -16,7 +16,7 @@ def is_uri(value, schemes=None):
def is_url(value, schemes=None):
- ''' Will verify that the string passed is a valid 'URL' '''
+ """ Will verify that the string passed is a valid 'URL' """
isit = is_uri(value, schemes)
if isit:
@@ -33,7 +33,7 @@ def is_urn(value):
class TestModule(object):
- ''' Ansible URI jinja2 test '''
+ """ Ansible URI jinja2 test """
def tests(self):
return {
diff --git a/lib/ansible/plugins/vars/host_group_vars.py b/lib/ansible/plugins/vars/host_group_vars.py
index cd02cc52cb..cb5b4b0c2b 100644
--- a/lib/ansible/plugins/vars/host_group_vars.py
+++ b/lib/ansible/plugins/vars/host_group_vars.py
@@ -17,7 +17,7 @@
#############################################
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: host_group_vars
version_added: "2.4"
short_description: In charge of loading group_vars and host_vars
@@ -50,7 +50,7 @@ DOCUMENTATION = '''
elements: string
extends_documentation_fragment:
- vars_plugin_staging
-'''
+"""
import os
from ansible.errors import AnsibleParserError
@@ -79,7 +79,7 @@ class VarsModule(BaseVarsPlugin):
return data
def get_vars(self, loader, path, entities, cache=True):
- ''' parses the inventory file '''
+ """ parses the inventory file """
if not isinstance(entities, list):
entities = [entities]
diff --git a/lib/ansible/template/__init__.py b/lib/ansible/template/__init__.py
index e23b3c5f5c..a66b559dd7 100644
--- a/lib/ansible/template/__init__.py
+++ b/lib/ansible/template/__init__.py
@@ -243,11 +243,11 @@ def is_template(data, jinja_env):
def _count_newlines_from_end(in_str):
- '''
+ """
Counts the number of newlines at the end of a string. This is used during
the jinja2 templating to ensure the count matches the input, since some newlines
may be thrown away during the templating.
- '''
+ """
try:
i = len(in_str)
@@ -313,10 +313,10 @@ def _wrap_native_text(func):
class AnsibleUndefined(StrictUndefined):
- '''
+ """
A custom Undefined class, which returns further Undefined objects on access,
rather than throwing an exception.
- '''
+ """
def __getattr__(self, name):
if name == '__UNSAFE__':
# AnsibleUndefined should never be assumed to be unsafe
@@ -342,23 +342,23 @@ class AnsibleUndefined(StrictUndefined):
class AnsibleContext(Context):
- '''
+ """
A custom context, which intercepts resolve_or_missing() calls and sets a flag
internally if any variable lookup returns an AnsibleUnsafe value. This
flag is checked post-templating, and (when set) will result in the
final templated result being wrapped in AnsibleUnsafe.
- '''
+ """
def __init__(self, *args, **kwargs):
super(AnsibleContext, self).__init__(*args, **kwargs)
self.unsafe = False
def _is_unsafe(self, val):
- '''
+ """
Our helper function, which will also recursively check dict and
list entries due to the fact that they may be repr'd and contain
a key or value which contains jinja2 syntax and would otherwise
lose the AnsibleUnsafe value.
- '''
+ """
if isinstance(val, dict):
for key in val.keys():
if self._is_unsafe(val[key]):
@@ -415,12 +415,12 @@ class AnsibleContext(Context):
class JinjaPluginIntercept(MutableMapping):
- ''' Simulated dict class that loads Jinja2Plugins at request
+ """ Simulated dict class that loads Jinja2Plugins at request
otherwise all plugins would need to be loaded a priori.
NOTE: plugin_loader still loads all 'builtin/legacy' at
start so only collection plugins are really at request.
- '''
+ """
def __init__(self, delegatee, pluginloader, *args, **kwargs):
@@ -531,10 +531,10 @@ def _ansible_finalize(thing):
class AnsibleEnvironment(NativeEnvironment):
- '''
+ """
Our custom environment, which simply allows us to override the class-level
values for the Template and Context classes used by jinja2 internally.
- '''
+ """
context_class = AnsibleContext
template_class = AnsibleJ2Template
concat = staticmethod(ansible_eval_concat) # type: ignore[assignment]
@@ -560,9 +560,9 @@ class AnsibleNativeEnvironment(AnsibleEnvironment):
class Templar:
- '''
+ """
The main class for templating, with the main entry-point of template().
- '''
+ """
def __init__(self, loader, variables=None):
self._loader = loader
@@ -632,12 +632,12 @@ class Templar:
return new_templar
def _get_extensions(self):
- '''
+ """
Return jinja2 extensions to load.
If some extensions are set via jinja_extensions in ansible.cfg, we try
to load them with the jinja environment.
- '''
+ """
jinja_exts = []
if C.DEFAULT_JINJA2_EXTENSIONS:
@@ -653,12 +653,12 @@ class Templar:
@available_variables.setter
def available_variables(self, variables):
- '''
+ """
Sets the list of template variables this Templar instance will use
to template things, so we don't have to pass them around between
internal methods. We also clear the template cache here, as the variables
are being changed.
- '''
+ """
if not isinstance(variables, Mapping):
raise AnsibleAssertionError("the type of 'variables' should be a Mapping but was a %s" % (type(variables)))
@@ -696,11 +696,11 @@ class Templar:
def template(self, variable, convert_bare=False, preserve_trailing_newlines=True, escape_backslashes=True, fail_on_undefined=None, overrides=None,
convert_data=True, static_vars=None, cache=None, disable_lookups=False):
- '''
+ """
Templates (possibly recursively) any given data as input. If convert_bare is
set to True, the given data will be wrapped as a jinja2 variable ('{{foo}}')
before being sent through the template engine.
- '''
+ """
static_vars = [] if static_vars is None else static_vars
if cache is not None:
@@ -774,7 +774,7 @@ class Templar:
return variable
def is_template(self, data):
- '''lets us know if data has a template'''
+ """lets us know if data has a template"""
if isinstance(data, string_types):
return is_template(data, self.environment)
elif isinstance(data, (list, tuple)):
@@ -794,10 +794,10 @@ class Templar:
return is_possibly_template(data, env)
def _convert_bare_variable(self, variable):
- '''
+ """
Wraps a bare string, which may have an attribute portion (ie. foo.bar)
in jinja2 variable braces so that it is evaluated properly.
- '''
+ """
if isinstance(variable, string_types):
contains_filters = "|" in variable
@@ -813,7 +813,7 @@ class Templar:
raise AnsibleError("The lookup `%s` was found, however lookups were disabled from templating" % name)
def _now_datetime(self, utc=False, fmt=None):
- '''jinja2 global function to return current datetime, potentially formatted via strftime'''
+ """jinja2 global function to return current datetime, potentially formatted via strftime"""
if utc:
now = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
else:
@@ -825,7 +825,7 @@ class Templar:
return now
def _query_lookup(self, name, /, *args, **kwargs):
- ''' wrapper for lookup, force wantlist true'''
+ """ wrapper for lookup, force wantlist true"""
kwargs['wantlist'] = True
return self._lookup(name, *args, **kwargs)
diff --git a/lib/ansible/template/template.py b/lib/ansible/template/template.py
index 4919f364f1..1852255134 100644
--- a/lib/ansible/template/template.py
+++ b/lib/ansible/template/template.py
@@ -23,12 +23,12 @@ __all__ = ['AnsibleJ2Template']
class AnsibleJ2Template(NativeTemplate):
- '''
+ """
A helper class, which prevents Jinja2 from running AnsibleJ2Vars through dict().
Without this, {% include %} and similar will create new contexts unlike the special
one created in Templar.template. This ensures they are all alike, except for
potential locals.
- '''
+ """
def new_context(self, vars=None, shared=False, locals=None):
if vars is None:
diff --git a/lib/ansible/utils/display.py b/lib/ansible/utils/display.py
index e514155e16..a03a444ad6 100644
--- a/lib/ansible/utils/display.py
+++ b/lib/ansible/utils/display.py
@@ -535,7 +535,7 @@ class Display(metaclass=Singleton):
date: str | None = None,
collection_name: str | None = None,
) -> str:
- ''' used to print out a deprecation message.'''
+ """ used to print out a deprecation message."""
msg = msg.strip()
if msg and msg[-1] not in ['!', '?', '.']:
msg += '.'
@@ -614,9 +614,9 @@ class Display(metaclass=Singleton):
@_proxy
def banner(self, msg: str, color: str | None = None, cows: bool = True) -> None:
- '''
+ """
Prints a header-looking line with cowsay or stars with length depending on terminal width (3 minimum)
- '''
+ """
msg = to_text(msg)
if self.b_cowsay and cows:
diff --git a/lib/ansible/utils/encrypt.py b/lib/ansible/utils/encrypt.py
index 3a279b7cc0..289288803c 100644
--- a/lib/ansible/utils/encrypt.py
+++ b/lib/ansible/utils/encrypt.py
@@ -37,12 +37,12 @@ DEFAULT_PASSWORD_LENGTH = 20
def random_password(length=DEFAULT_PASSWORD_LENGTH, chars=C.DEFAULT_PASSWORD_CHARS, seed=None):
- '''Return a random password string of length containing only chars
+ """Return a random password string of length containing only chars
:kwarg length: The number of characters in the new password. Defaults to 20.
:kwarg chars: The characters to choose from. The default is all ascii
letters, ascii digits, and these symbols ``.,:-_``
- '''
+ """
if not isinstance(chars, text_type):
raise AnsibleAssertionError('%s (%s) is not a text_type' % (chars, type(chars)))
diff --git a/lib/ansible/utils/fqcn.py b/lib/ansible/utils/fqcn.py
index 043d8a056e..bcd6f0b952 100644
--- a/lib/ansible/utils/fqcn.py
+++ b/lib/ansible/utils/fqcn.py
@@ -18,11 +18,11 @@ from __future__ import annotations
def add_internal_fqcns(names):
- '''
+ """
Given a sequence of action/module names, returns a list of these names
with the same names with the prefixes `ansible.builtin.` and
`ansible.legacy.` added for all names that are not already FQCNs.
- '''
+ """
result = []
for name in names:
result.append(name)
diff --git a/lib/ansible/utils/hashing.py b/lib/ansible/utils/hashing.py
index e8faf25f76..81258f7685 100644
--- a/lib/ansible/utils/hashing.py
+++ b/lib/ansible/utils/hashing.py
@@ -32,7 +32,7 @@ from ansible.module_utils.common.text.converters import to_bytes
def secure_hash_s(data, hash_func=sha1):
- ''' Return a secure hash hex digest of data. '''
+ """ Return a secure hash hex digest of data. """
digest = hash_func()
data = to_bytes(data, errors='surrogate_or_strict')
@@ -41,7 +41,7 @@ def secure_hash_s(data, hash_func=sha1):
def secure_hash(filename, hash_func=sha1):
- ''' Return a secure hash hex digest of local file, None if file is not present or a directory. '''
+ """ Return a secure hash hex digest of local file, None if file is not present or a directory. """
if not os.path.exists(to_bytes(filename, errors='surrogate_or_strict')) or os.path.isdir(to_bytes(filename, errors='strict')):
return None
diff --git a/lib/ansible/utils/helpers.py b/lib/ansible/utils/helpers.py
index c9b5f16f29..97f34acd0e 100644
--- a/lib/ansible/utils/helpers.py
+++ b/lib/ansible/utils/helpers.py
@@ -21,10 +21,10 @@ from ansible.module_utils.six import string_types
def pct_to_int(value, num_items, min_value=1):
- '''
+ """
Converts a given value to a percentage if specified as "x%",
otherwise converts the given value to an integer.
- '''
+ """
if isinstance(value, string_types) and value.endswith('%'):
value_pct = int(value.replace("%", ""))
return int((value_pct / 100.0) * num_items) or min_value
diff --git a/lib/ansible/utils/lock.py b/lib/ansible/utils/lock.py
index 9f834da733..1931aca67f 100644
--- a/lib/ansible/utils/lock.py
+++ b/lib/ansible/utils/lock.py
@@ -7,7 +7,7 @@ from functools import wraps
def lock_decorator(attr='missing_lock_attr', lock=None):
- '''This decorator is a generic implementation that allows you
+ """This decorator is a generic implementation that allows you
to either use a pre-defined instance attribute as the location
of the lock, or to explicitly pass a lock object.
@@ -25,7 +25,7 @@ def lock_decorator(attr='missing_lock_attr', lock=None):
@lock_decorator(lock=threading.Lock())
def some_method(...):
- '''
+ """
def outer(func):
@wraps(func)
def inner(*args, **kwargs):
diff --git a/lib/ansible/utils/path.py b/lib/ansible/utils/path.py
index 2b25342ed4..202a4f4259 100644
--- a/lib/ansible/utils/path.py
+++ b/lib/ansible/utils/path.py
@@ -28,7 +28,7 @@ __all__ = ['unfrackpath', 'makedirs_safe']
def unfrackpath(path, follow=True, basedir=None):
- '''
+ """
Returns a path that is free of symlinks (if follow=True), environment variables, relative path traversals and symbols (~)
:arg path: A byte or text string representing a path to be canonicalized
@@ -44,7 +44,7 @@ def unfrackpath(path, follow=True, basedir=None):
example::
'$HOME/../../var/mail' becomes '/var/spool/mail'
- '''
+ """
b_basedir = to_bytes(basedir, errors='surrogate_or_strict', nonstring='passthru')
@@ -65,7 +65,7 @@ def unfrackpath(path, follow=True, basedir=None):
def makedirs_safe(path, mode=None):
- '''
+ """
A *potentially insecure* way to ensure the existence of a directory chain. The "safe" in this function's name
refers only to its ability to ignore `EEXIST` in the case of multiple callers operating on the same part of
the directory chain. This function is not safe to use under world-writable locations when the first level of the
@@ -77,7 +77,7 @@ def makedirs_safe(path, mode=None):
:kwarg mode: If given, the mode to set the directory to
:raises AnsibleError: If the directory cannot be created and does not already exist.
:raises UnicodeDecodeError: if the path is not decodable in the utf-8 encoding.
- '''
+ """
rpath = unfrackpath(path)
b_rpath = to_bytes(rpath)
diff --git a/lib/ansible/utils/plugin_docs.py b/lib/ansible/utils/plugin_docs.py
index c5089aa4b0..db638e6d00 100644
--- a/lib/ansible/utils/plugin_docs.py
+++ b/lib/ansible/utils/plugin_docs.py
@@ -292,7 +292,7 @@ def _find_adjacent(path, plugin, extensions):
def find_plugin_docfile(plugin, plugin_type, loader):
- ''' if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding 'sidecar' file for docs '''
+ """ if the plugin lives in a non-python file (eg, win_X.ps1), require the corresponding 'sidecar' file for docs """
context = loader.find_plugin_with_context(plugin, ignore_deprecated=False, check_aliases=True)
if (not context or not context.resolved) and plugin_type in ('filter', 'test'):
diff --git a/lib/ansible/utils/version.py b/lib/ansible/utils/version.py
index 19930d498b..adb47721c1 100644
--- a/lib/ansible/utils/version.py
+++ b/lib/ansible/utils/version.py
@@ -11,7 +11,7 @@ from ansible.module_utils.compat.version import LooseVersion, Version
# Regular expression taken from
# https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
SEMVER_RE = re.compile(
- r'''
+ r"""
^
(?P<major>0|[1-9]\d*)
\.
@@ -30,7 +30,7 @@ SEMVER_RE = re.compile(
(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)
)?
$
- ''',
+ """,
flags=re.X
)
diff --git a/lib/ansible/vars/clean.py b/lib/ansible/vars/clean.py
index 559242e0f8..83b840b549 100644
--- a/lib/ansible/vars/clean.py
+++ b/lib/ansible/vars/clean.py
@@ -94,9 +94,9 @@ def strip_internal_keys(dirty, exceptions=None):
def remove_internal_keys(data):
- '''
+ """
More nuanced version of strip_internal_keys
- '''
+ """
for key in list(data.keys()):
if (key.startswith('_ansible_') and key != '_ansible_parsed') or key in C.INTERNAL_RESULT_KEYS:
display.warning("Removed unexpected internal key in module return: %s = %s" % (key, data[key]))
@@ -114,7 +114,7 @@ def remove_internal_keys(data):
def clean_facts(facts):
- ''' remove facts that can override internal keys or otherwise deemed unsafe '''
+ """ remove facts that can override internal keys or otherwise deemed unsafe """
data = module_response_deepcopy(facts)
remove_keys = set()
@@ -157,7 +157,7 @@ def clean_facts(facts):
def namespace_facts(facts):
- ''' return all facts inside 'ansible_facts' w/o an ansible_ prefix '''
+ """ return all facts inside 'ansible_facts' w/o an ansible_ prefix """
deprefixed = {}
for k in facts:
if k.startswith('ansible_') and k not in ('ansible_local',):
diff --git a/lib/ansible/vars/hostvars.py b/lib/ansible/vars/hostvars.py
index 6f8491dcca..5da42a1e7f 100644
--- a/lib/ansible/vars/hostvars.py
+++ b/lib/ansible/vars/hostvars.py
@@ -29,7 +29,7 @@ __all__ = ['HostVars', 'HostVarsVars']
# Note -- this is a Mapping, not a MutableMapping
class HostVars(Mapping):
- ''' A special view of vars_cache that adds values from the inventory when needed. '''
+ """ A special view of vars_cache that adds values from the inventory when needed. """
def __init__(self, inventory, variable_manager, loader):
self._inventory = inventory
@@ -49,10 +49,10 @@ class HostVars(Mapping):
return self._inventory.get_host(host_name)
def raw_get(self, host_name):
- '''
+ """
Similar to __getitem__, however the returned data is not run through
the templating engine to expand variables in the hostvars.
- '''
+ """
host = self._find_host(host_name)
if host is None:
return AnsibleUndefined(name="hostvars['%s']" % host_name)
@@ -138,8 +138,8 @@ class HostVarsVars(Mapping):
return repr(self._templar.template(self._vars, fail_on_undefined=False, static_vars=C.INTERNAL_STATIC_VARS))
def __getstate__(self):
- ''' override serialization here to avoid
- pickle issues with templar and Jinja native'''
+ """ override serialization here to avoid
+ pickle issues with templar and Jinja native"""
state = self.__dict__.copy()
state.pop('_templar', None)
return state
diff --git a/lib/ansible/vars/manager.py b/lib/ansible/vars/manager.py
index 708cda7fd6..3d8ffe9fa1 100644
--- a/lib/ansible/vars/manager.py
+++ b/lib/ansible/vars/manager.py
@@ -44,11 +44,11 @@ display = Display()
def preprocess_vars(a):
- '''
+ """
Ensures that vars contained in the parameter passed in are
returned as a list of dictionaries, to ensure for instance
that vars loaded from a file conform to an expected state.
- '''
+ """
if a is None:
return None
@@ -137,7 +137,7 @@ class VariableManager:
def get_vars(self, play=None, host=None, task=None, include_hostvars=True, include_delegate_to=False, use_cache=True,
_hosts=None, _hosts_all=None, stage='task'):
- '''
+ """
Returns the variables, with optional "context" given via the parameters
for the play, host, and task (which could possibly result in different
sets of variables being returned due to the additional context).
@@ -158,7 +158,7 @@ class VariableManager:
``_hosts`` and ``_hosts_all`` should be considered private args, with only internal trusted callers relying
on the functionality they provide. These arguments may be removed at a later date without a deprecation
period and without warning.
- '''
+ """
if include_delegate_to:
display.deprecated(
"`VariableManager.get_vars`'s argument `include_delegate_to` has no longer any effect.",
@@ -180,11 +180,11 @@ class VariableManager:
_vars_sources = {}
def _combine_and_track(data, new_data, source):
- '''
+ """
Wrapper function to update var sources dict and call combine_vars()
See notes in the VarsWithSources docstring for caveats and limitations of the source tracking
- '''
+ """
if new_data == {}:
return data
@@ -247,11 +247,11 @@ class VariableManager:
# internal functions that actually do the work
def _plugins_inventory(entities):
- ''' merges all entities by inventory source '''
+ """ merges all entities by inventory source """
return get_vars_from_inventory_sources(self._loader, self._inventory._sources, entities, stage)
def _plugins_play(entities):
- ''' merges all entities adjacent to play '''
+ """ merges all entities adjacent to play """
data = {}
for path in basedirs:
data = _combine_and_track(data, get_vars_from_path(self._loader, path, entities, stage), "path '%s'" % path)
@@ -268,22 +268,22 @@ class VariableManager:
return _plugins_play([all_group])
def groups_inventory():
- ''' gets group vars from inventory '''
+ """ gets group vars from inventory """
return get_group_vars(host_groups)
def groups_plugins_inventory():
- ''' gets plugin sources from inventory for groups '''
+ """ gets plugin sources from inventory for groups """
return _plugins_inventory(host_groups)
def groups_plugins_play():
- ''' gets plugin sources from play for groups '''
+ """ gets plugin sources from play for groups """
return _plugins_play(host_groups)
def plugins_by_groups():
- '''
+ """
merges all plugin sources by group,
This should be used instead, NOT in combination with the other groups_plugins* functions
- '''
+ """
data = {}
for group in host_groups:
data[group] = _combine_and_track(data[group], _plugins_inventory(group), "inventory group_vars for '%s'" % group)
@@ -436,10 +436,10 @@ class VariableManager:
return all_vars
def _get_magic_variables(self, play, host, task, include_hostvars, _hosts=None, _hosts_all=None):
- '''
+ """
Returns a dictionary of so-called "magic" variables in Ansible,
which are special variables we set internally for use.
- '''
+ """
variables = {}
variables['playbook_dir'] = os.path.abspath(self._loader.get_basedir())
@@ -547,15 +547,15 @@ class VariableManager:
return delegated_vars, delegated_host_name
def clear_facts(self, hostname):
- '''
+ """
Clears the facts for a host
- '''
+ """
self._fact_cache.pop(hostname, None)
def set_host_facts(self, host, facts):
- '''
+ """
Sets or updates the given facts for a host in the fact cache.
- '''
+ """
if not isinstance(facts, Mapping):
raise AnsibleAssertionError("the type of 'facts' to set for host_facts should be a Mapping but is a %s" % type(facts))
@@ -576,9 +576,9 @@ class VariableManager:
self._fact_cache[host] = host_cache
def set_nonpersistent_facts(self, host, facts):
- '''
+ """
Sets or updates the given facts for a host in the fact cache.
- '''
+ """
if not isinstance(facts, Mapping):
raise AnsibleAssertionError("the type of 'facts' to set for nonpersistent_facts should be a Mapping but is a %s" % type(facts))
@@ -589,9 +589,9 @@ class VariableManager:
self._nonpersistent_fact_cache[host] = facts
def set_host_variable(self, host, varname, value):
- '''
+ """
Sets a value in the vars_cache for a host.
- '''
+ """
if host not in self._vars_cache:
self._vars_cache[host] = dict()
if varname in self._vars_cache[host] and isinstance(self._vars_cache[host][varname], MutableMapping) and isinstance(value, MutableMapping):
@@ -601,21 +601,21 @@ class VariableManager:
class VarsWithSources(MutableMapping):
- '''
+ """
Dict-like class for vars that also provides source information for each var
This class can only store the source for top-level vars. It does no tracking
on its own, just shows a debug message with the information that it is provided
when a particular var is accessed.
- '''
+ """
def __init__(self, *args, **kwargs):
- ''' Dict-compatible constructor '''
+ """ Dict-compatible constructor """
self.data = dict(*args, **kwargs)
self.sources = {}
@classmethod
def new_vars_with_sources(cls, data, sources):
- ''' Alternate constructor method to instantiate class with sources '''
+ """ Alternate constructor method to instantiate class with sources """
v = cls(data)
v.sources = sources
return v
diff --git a/lib/ansible/vars/reserved.py b/lib/ansible/vars/reserved.py
index aece04d652..fe0cfa2da4 100644
--- a/lib/ansible/vars/reserved.py
+++ b/lib/ansible/vars/reserved.py
@@ -27,7 +27,7 @@ display = Display()
def get_reserved_names(include_private=True):
- ''' this function returns the list of reserved names associated with play objects'''
+ """ this function returns the list of reserved names associated with play objects"""
public = set()
private = set()
@@ -62,7 +62,7 @@ def get_reserved_names(include_private=True):
def warn_if_reserved(myvars, additional=None):
- ''' this function warns if any variable passed conflicts with internally reserved names '''
+ """ this function warns if any variable passed conflicts with internally reserved names """
if additional is None:
reserved = _RESERVED_NAMES
diff --git a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py
index a6203b91cb..90f6f49a11 100644
--- a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py
+++ b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: notjsonfile
broken:
short_description: JSON formatted files.
@@ -56,7 +56,7 @@ DOCUMENTATION = '''
type: integer
extends_documentation_fragment:
- testns.testcol2.plugin
-'''
+"""
from ansible.plugins.cache import BaseFileCacheModule
diff --git a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py
index eb5f5f35bc..1deea1d426 100644
--- a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py
+++ b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
inventory: statichost
broken:
short_description: Add a single host
@@ -17,7 +17,7 @@ DOCUMENTATION = '''
hostname:
description: Toggle display of stderr even when script was successful
required: True
-'''
+"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
diff --git a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py
index b017112b3b..e6ee7fd3a3 100644
--- a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py
+++ b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: randommodule
short_description: A random module
@@ -47,12 +47,12 @@ options:
version: '2.0.0'
extends_documentation_fragment:
- testns.testcol2.module
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
+RETURN = """
z_last:
description: A last result.
broken:
@@ -77,7 +77,7 @@ a_first:
description: A first result.
type: str
returned: success
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py
index 61de5f434b..0bef3e8b69 100644
--- a/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py
+++ b/test/integration/targets/ansible-doc/broken-docs/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
vars: noop_vars_plugin
broken:
short_description: Do NOT load host and group vars
@@ -17,7 +17,7 @@ DOCUMENTATION = '''
- name: ANSIBLE_VARS_PLUGIN_STAGE
extends_documentation_fragment:
- testns.testcol2.deprecation
-'''
+"""
from ansible.plugins.vars import BaseVarsPlugin
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py
index 32abc43aa7..21ec0bed85 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/cache/notjsonfile.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: notjsonfile
short_description: JSON formatted files.
description:
@@ -55,7 +55,7 @@ DOCUMENTATION = '''
type: integer
extends_documentation_fragment:
- testns.testcol2.plugin
-'''
+"""
from ansible.plugins.cache import BaseFileCacheModule
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/filter_subdir/in_subdir.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/filter_subdir/in_subdir.py
index d912c028ec..3d5826a324 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/filter_subdir/in_subdir.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/filter_subdir/in_subdir.py
@@ -12,7 +12,7 @@ def nochange(a):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/grouped.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/grouped.py
index 47ac9c4466..e80a0b482a 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/grouped.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/filter/grouped.py
@@ -16,7 +16,7 @@ def meaningoflife(a):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py
index 60c60f92af..d440cb50b7 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/inventory/statichost.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
inventory: statichost
short_description: Add a single host
description: Add a single host
@@ -16,7 +16,7 @@ DOCUMENTATION = '''
hostname:
description: Toggle display of stderr even when script was successful
required: True
-'''
+"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/database/database_type/subdir_module.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/database/database_type/subdir_module.py
index a7bcf5055a..d10d5c5dea 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/database/database_type/subdir_module.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/database/database_type/subdir_module.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: subdir_module
short_description: A module in multiple subdirectories
@@ -12,13 +12,13 @@ author:
- Ansible Core Team
version_added: 1.0.0
options: {}
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py
index 81e8fb86e6..fdd5dcacfc 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/modules/randommodule.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: randommodule
short_description: A random module
@@ -73,12 +73,12 @@ notes:
This is just another line in the second paragraph.
Eventually this will break into a new line,
depending with which line width this is rendered.
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = r'''
+RETURN = r"""
z_last:
description: A last result.
type: str
@@ -103,7 +103,7 @@ a_first:
description: A first result. Use RV(a_first=foo\(bar\\baz\)bam).
type: str
returned: success
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/test/test_test.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/test/test_test.py
index 160256c7b2..b8d3550ff7 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/test/test_test.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/test/test_test.py
@@ -6,7 +6,7 @@ def yolo(value):
class TestModule(object):
- ''' Ansible core jinja2 tests '''
+ """ Ansible core jinja2 tests """
def tests(self):
return {
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py
index 93c076b5d3..48403275bb 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol/plugins/vars/noop_vars_plugin.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
vars: noop_vars_plugin
short_description: Do NOT load host and group vars
description: don't test loading host and group vars from a collection
@@ -16,7 +16,7 @@ DOCUMENTATION = '''
- name: ANSIBLE_VARS_PLUGIN_STAGE
extends_documentation_fragment:
- testns.testcol2.deprecation
-'''
+"""
from ansible.plugins.vars import BaseVarsPlugin
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/deprecation.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/deprecation.py
index fdb85abf4c..aa4ebf80e9 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/deprecation.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/deprecation.py
@@ -6,10 +6,10 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options: {}
deprecated:
alternative: Use some other module
why: Test deprecation
removed_in: '3.0.0'
-'''
+"""
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/module.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/module.py
index 5fbc352943..f576e9301e 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/module.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/module.py
@@ -6,7 +6,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
testcol2option:
description:
@@ -17,4 +17,4 @@ options:
description:
- Another option taken from testcol2
type: str
-'''
+"""
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/plugin.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/plugin.py
index eddd61e210..6bf324fe5b 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/plugin.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/plugin.py
@@ -6,7 +6,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
testcol2option:
description:
@@ -43,4 +43,4 @@ options:
alternative: none
why: Test option deprecation
version: '2.0.0'
-'''
+"""
diff --git a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/version_added.py b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/version_added.py
index d901404839..1cbd2f4634 100644
--- a/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/version_added.py
+++ b/test/integration/targets/ansible-doc/collections/ansible_collections/testns/testcol2/plugins/doc_fragments/version_added.py
@@ -6,7 +6,7 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options: {}
version_added: 1.0.0
-'''
+"""
diff --git a/test/integration/targets/ansible-doc/filter_plugins/other.py b/test/integration/targets/ansible-doc/filter_plugins/other.py
index 3392dd5b47..cea7c9740a 100644
--- a/test/integration/targets/ansible-doc/filter_plugins/other.py
+++ b/test/integration/targets/ansible-doc/filter_plugins/other.py
@@ -12,7 +12,7 @@ def donothing(a):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/test/integration/targets/ansible-doc/library/double_doc.py b/test/integration/targets/ansible-doc/library/double_doc.py
index 80bd3dda3f..71d95af3a0 100644
--- a/test/integration/targets/ansible-doc/library/double_doc.py
+++ b/test/integration/targets/ansible-doc/library/double_doc.py
@@ -2,11 +2,11 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
name: double_doc
description:
- module also uses 'DOCUMENTATION' in class
-'''
+"""
class Foo:
diff --git a/test/integration/targets/ansible-doc/library/test_docs.py b/test/integration/targets/ansible-doc/library/test_docs.py
index ba7817d8a2..84ced6a8cc 100644
--- a/test/integration/targets/ansible-doc/library/test_docs.py
+++ b/test/integration/targets/ansible-doc/library/test_docs.py
@@ -6,7 +6,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs
short_description: Test module
@@ -14,13 +14,13 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_missing_description.py b/test/integration/targets/ansible-doc/library/test_docs_missing_description.py
index 40f39ef583..f6d371cc3e 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_missing_description.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_missing_description.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_returns
short_description: Test module
@@ -13,13 +13,13 @@ author:
options:
test:
type: str
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_no_metadata.py b/test/integration/targets/ansible-doc/library/test_docs_no_metadata.py
index b4344e99fa..827a1b2f43 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_no_metadata.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_no_metadata.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_no_metadata
short_description: Test module
@@ -10,13 +10,13 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_no_status.py b/test/integration/targets/ansible-doc/library/test_docs_no_status.py
index f870e666d4..0b3f0dc2b5 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_no_status.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_no_status.py
@@ -5,7 +5,7 @@ from __future__ import annotations
ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_no_status
short_description: Test module
@@ -13,13 +13,13 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_non_iterable_status.py b/test/integration/targets/ansible-doc/library/test_docs_non_iterable_status.py
index 6e78ea7c54..5c5128b74a 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_non_iterable_status.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_non_iterable_status.py
@@ -6,7 +6,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': 1,
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_non_iterable_status
short_description: Test module
@@ -14,13 +14,13 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_removed_precedence.py b/test/integration/targets/ansible-doc/library/test_docs_removed_precedence.py
index fdba64e5ad..8817c1204d 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_removed_precedence.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_removed_precedence.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_removed_precedence
short_description: Test module
@@ -15,13 +15,13 @@ deprecated:
why: Updated module released with more functionality
removed_at_date: '2022-06-01'
removed_in: '2.14'
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_removed_status.py b/test/integration/targets/ansible-doc/library/test_docs_removed_status.py
index 18f32a2b50..d894a4a030 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_removed_status.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_removed_status.py
@@ -6,7 +6,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['removed'],
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_removed_status
short_description: Test module
@@ -14,13 +14,13 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_returns.py b/test/integration/targets/ansible-doc/library/test_docs_returns.py
index d21abf3efc..f1079ae7b3 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_returns.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_returns.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_returns
short_description: Test module
@@ -10,12 +10,12 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
+RETURN = """
z_last:
description: A last result.
type: str
@@ -37,7 +37,7 @@ a_first:
description: A first result.
type: str
returned: success
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_returns_broken.py b/test/integration/targets/ansible-doc/library/test_docs_returns_broken.py
index 0c3119bc25..f7ce2dd2ec 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_returns_broken.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_returns_broken.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_returns_broken
short_description: Test module
@@ -10,18 +10,18 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
+RETURN = """
test:
description: A test return value.
type: str
broken_key: [
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_suboptions.py b/test/integration/targets/ansible-doc/library/test_docs_suboptions.py
index 7f93e22d46..b25643a147 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_suboptions.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_suboptions.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_suboptions
short_description: Test module
@@ -31,13 +31,13 @@ options:
a_first:
description: The first suboption.
type: str
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/library/test_docs_yaml_anchors.py b/test/integration/targets/ansible-doc/library/test_docs_yaml_anchors.py
index 419f350433..3e8fbb06ab 100644
--- a/test/integration/targets/ansible-doc/library/test_docs_yaml_anchors.py
+++ b/test/integration/targets/ansible-doc/library/test_docs_yaml_anchors.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: test_docs_yaml_anchors
short_description: Test module with YAML anchors in docs
@@ -37,13 +37,13 @@ options:
type: list
elements: dict
suboptions: *sub_anchor
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-doc/lookup_plugins/_deprecated_with_docs.py b/test/integration/targets/ansible-doc/lookup_plugins/_deprecated_with_docs.py
index 449f392254..55b50b0572 100644
--- a/test/integration/targets/ansible-doc/lookup_plugins/_deprecated_with_docs.py
+++ b/test/integration/targets/ansible-doc/lookup_plugins/_deprecated_with_docs.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: deprecated_with_docs
short_description: test lookup
description: test lookup
@@ -16,10 +16,10 @@ DOCUMENTATION = '''
removed_in: "2.16"
removed_from_collection: "ansible.legacy"
options: {}
-'''
+"""
-EXAMPLE = '''
-'''
+EXAMPLE = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
diff --git a/test/integration/targets/ansible-galaxy-collection/files/test_module.py b/test/integration/targets/ansible-galaxy-collection/files/test_module.py
index d4bb3c3c66..0fae1fd4c8 100644
--- a/test/integration/targets/ansible-galaxy-collection/files/test_module.py
+++ b/test/integration/targets/ansible-galaxy-collection/files/test_module.py
@@ -7,7 +7,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -32,9 +32,9 @@ seealso:
author:
- Ansible Core Team
- Michael DeHaan
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
@@ -44,15 +44,15 @@ EXAMPLES = '''
- name: Induce an exception to see what happens
ping:
data: crash
-'''
+"""
-RETURN = '''
+RETURN = """
ping:
description: value provided with the data parameter
returned: success
type: str
sample: pong
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-galaxy-collection/library/reset_pulp.py b/test/integration/targets/ansible-galaxy-collection/library/reset_pulp.py
index 90397a55a9..72fa7706cc 100644
--- a/test/integration/targets/ansible-galaxy-collection/library/reset_pulp.py
+++ b/test/integration/targets/ansible-galaxy-collection/library/reset_pulp.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: reset_pulp
short_description: Resets pulp back to the initial state
@@ -48,9 +48,9 @@ options:
elements: str
author:
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: reset pulp content
reset_pulp:
pulp_api: http://galaxy:24817
@@ -61,11 +61,11 @@ EXAMPLES = '''
namespaces:
- namespace1
- namespace2
-'''
+"""
-RETURN = '''
+RETURN = """
#
-'''
+"""
import json
diff --git a/test/integration/targets/ansible-galaxy-collection/library/setup_collections.py b/test/integration/targets/ansible-galaxy-collection/library/setup_collections.py
index b7d262aced..9efd7bbef6 100644
--- a/test/integration/targets/ansible-galaxy-collection/library/setup_collections.py
+++ b/test/integration/targets/ansible-galaxy-collection/library/setup_collections.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {
'supported_by': 'community'
}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: setup_collections
short_description: Set up test collections based on the input
@@ -57,9 +57,9 @@ options:
default: '{}'
author:
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Build test collections
setup_collections:
path: ~/ansible/collections/ansible_collections
@@ -70,11 +70,11 @@ EXAMPLES = '''
- namespace: namespace1
name: name1
version: 0.0.2
-'''
+"""
-RETURN = '''
+RETURN = """
#
-'''
+"""
import datetime
import os
diff --git a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/doc_fragments/ps_util.py b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/doc_fragments/ps_util.py
index c8e8b70903..aa82b7fbf7 100644
--- a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/doc_fragments/ps_util.py
+++ b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/doc_fragments/ps_util.py
@@ -8,7 +8,7 @@ from __future__ import annotations
class ModuleDocFragment:
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
option1:
description:
@@ -17,4 +17,4 @@ options:
aliases:
- alias1
type: str
-'''
+"""
diff --git a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/hello.py b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/hello.py
index a685933096..664ae43bb6 100644
--- a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/hello.py
+++ b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/hello.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: hello
short_description: Hello test module
description: Hello test module.
@@ -13,13 +13,13 @@ options:
type: str
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- minimal:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
from ..module_utils.my_util import hello
diff --git a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.py b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.py
index ed49f4ea81..15d9f2af0e 100644
--- a/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.py
+++ b/test/integration/targets/ansible-test-docker/ansible_collections/ns/col/plugins/modules/win_util_args.py
@@ -9,7 +9,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_util_args
short_description: Short description
@@ -26,14 +26,14 @@ extends_documentation_fragment:
author:
- Ansible Test (@ansible)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- win_util_args:
option1: test
my_opt: test
-'''
+"""
-RETURN = r'''
+RETURN = r"""
#
-'''
+"""
diff --git a/test/integration/targets/ansible-test-integration/ansible_collections/ns/col/plugins/modules/hello.py b/test/integration/targets/ansible-test-integration/ansible_collections/ns/col/plugins/modules/hello.py
index 06ff6d4bc6..862c855e36 100644
--- a/test/integration/targets/ansible-test-integration/ansible_collections/ns/col/plugins/modules/hello.py
+++ b/test/integration/targets/ansible-test-integration/ansible_collections/ns/col/plugins/modules/hello.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: hello
short_description: Hello test module
description: Hello test module.
@@ -13,13 +13,13 @@ options:
type: str
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- hello:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
from ..module_utils.my_util import hello
diff --git a/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/_module3.py b/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/_module3.py
index 41784aeee0..9eae686e53 100644
--- a/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/_module3.py
+++ b/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/_module3.py
@@ -3,19 +3,19 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: _module3
short_description: Another test module
description: This is a test module that has not been deprecated.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- minimal:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/a/b/module2.py b/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/a/b/module2.py
index 500beaa873..3c00538e0c 100644
--- a/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/a/b/module2.py
+++ b/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/a/b/module2.py
@@ -3,20 +3,20 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: module2
short_description: Hello test module
description: Hello test module.
options: {}
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- minimal:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/module1.py b/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/module1.py
index 45e3977438..e3f8a89c71 100644
--- a/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/module1.py
+++ b/test/integration/targets/ansible-test-sanity-ansible-doc/ansible_collections/ns/col/plugins/modules/module1.py
@@ -3,20 +3,20 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: module1
short_description: Hello test module
description: Hello test module.
options: {}
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- minimal:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor1.py b/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor1.py
index 3cf63c0a65..9adcca7e95 100644
--- a/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor1.py
+++ b/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor1.py
@@ -2,16 +2,16 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: vendor1
short_description: lookup
description: Lookup.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = '''#'''
+EXAMPLES = """#"""
+RETURN = """#"""
from ansible.plugins.lookup import LookupBase
# noinspection PyUnresolvedReferences
diff --git a/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor2.py b/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor2.py
index d22f7184bd..576576fd94 100644
--- a/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor2.py
+++ b/test/integration/targets/ansible-test-sanity-import/ansible_collections/ns/col/plugins/lookup/vendor2.py
@@ -2,16 +2,16 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: vendor2
short_description: lookup
description: Lookup.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = '''#'''
+EXAMPLES = """#"""
+RETURN = """#"""
from ansible.plugins.lookup import LookupBase
# noinspection PyUnresolvedReferences
diff --git a/test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py b/test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py
index 1066e64917..4fd6ae4041 100644
--- a/test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py
+++ b/test/integration/targets/ansible-test-sanity-pylint/ansible_collections/ns/col/plugins/lookup/deprecated.py
@@ -2,16 +2,16 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: deprecated
short_description: lookup
description: Lookup.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = '''#'''
+EXAMPLES = """#"""
+RETURN = """#"""
from ansible.plugins.lookup import LookupBase
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/_not_deprecated.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/_not_deprecated.py
index 4b4b09134e..85f6ec387d 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/_not_deprecated.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/_not_deprecated.py
@@ -3,16 +3,16 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: _not_deprecated
short_description: This module is not deprecated
description: Its name has a leading underscore, but it is not deprecated.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_1.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_1.py
index 7f53b26bea..2fdf6d5315 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_1.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_1.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_1
short_description: Test for check mode attribute 1
description: Test for check mode attribute 1.
@@ -19,10 +19,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_2.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_2.py
index 263e5b8238..940b9252b2 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_2.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_2.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_2
short_description: Test for check mode attribute 2
description: Test for check mode attribute 2.
@@ -20,10 +20,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_3.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_3.py
index a2bf699568..f9628c8534 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_3.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_3.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_3
short_description: Test for check mode attribute 3
description: Test for check mode attribute 3.
@@ -19,10 +19,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_4.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_4.py
index 0d442e8729..32a8bb76e0 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_4.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_4.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_4
short_description: Test for check mode attribute 4
description: Test for check mode attribute 4.
@@ -19,10 +19,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_5.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_5.py
index 86bc94f71f..27286358bf 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_5.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_5.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_5
short_description: Test for check mode attribute 5
description: Test for check mode attribute 5.
@@ -19,10 +19,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_6.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_6.py
index 966d62cc4f..a83a9b6609 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_6.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_6.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_6
short_description: Test for check mode attribute 6
description: Test for check mode attribute 6.
@@ -20,10 +20,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_7.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_7.py
index 0b77937f2b..a67cefd17c 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_7.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/check_mode_attribute_7.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: check_mode_attribute_7
short_description: Test for check mode attribute 7
description: Test for check mode attribute 7.
@@ -19,10 +19,10 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/import_order.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/import_order.py
index 84c2ed9ba4..dc3b981439 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/import_order.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/import_order.py
@@ -6,16 +6,16 @@ from __future__ import annotations
from ansible.module_utils.basic import AnsibleModule
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: import_order
short_description: Import order test module
description: Import order test module.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
if __name__ == '__main__':
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_extra_key.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_extra_key.py
index 04807a1ee1..86057c92ae 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_extra_key.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_extra_key.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: invalid_argument_spec_extra_key
short_description: Invalid argument spec extra key schema test module
description: Invalid argument spec extra key schema test module
@@ -13,10 +13,10 @@ options:
foo:
description: foo
type: str
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_incorrect_context.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_incorrect_context.py
index 6e3d244134..1377ced9df 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_incorrect_context.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_argument_spec_incorrect_context.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: invalid_argument_spec_incorrect_context
short_description: Invalid argument spec incorrect context schema test module
description: Invalid argument spec incorrect context schema test module
@@ -13,10 +13,10 @@ options:
foo:
description: foo
type: str
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_yaml_syntax.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_yaml_syntax.py
index 7931798945..a669419c0e 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_yaml_syntax.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/invalid_yaml_syntax.py
@@ -3,17 +3,17 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
- key: "value"wrong
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- key: "value"wrong
-'''
+"""
-RETURN = '''
+RETURN = """
- key: "value"wrong
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/no_callable.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/no_callable.py
index 7004c70845..ac7aeea64e 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/no_callable.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/no_callable.py
@@ -3,16 +3,16 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: no_callable
short_description: No callale test module
description: No callable test module.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/option_name_casing.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/option_name_casing.py
index 7ffd75bb7c..933c68f1f4 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/option_name_casing.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/option_name_casing.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: option_name_casing
short_description: Option names equal up to casing
description: Option names equal up to casing.
@@ -28,10 +28,10 @@ options:
aliases:
- baR
type: str
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/semantic_markup.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/semantic_markup.py
index 86eca45f4e..dfefee33a3 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/semantic_markup.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/semantic_markup.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: semantic_markup
short_description: Test semantic markup
description:
@@ -91,17 +91,17 @@ options:
- O(bar=bam).
- O(foo.bar=1).
type: str
-'''
+"""
-EXAMPLES = '''#'''
+EXAMPLES = """#"""
-RETURN = r'''
+RETURN = r"""
bar:
description: Bar.
type: int
returned: success
sample: 5
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/valid_argument_spec_context.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/valid_argument_spec_context.py
index 2aa67abd19..7882c105f8 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/valid_argument_spec_context.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/valid_argument_spec_context.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: valid_argument_spec_context
short_description: Valid argument spec context schema test module
description: Valid argument spec context schema test module
@@ -13,10 +13,10 @@ options:
foo:
description: foo
type: str
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/wrong_aliases.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/wrong_aliases.py
index f5918659df..5fae338c48 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/wrong_aliases.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/col/plugins/modules/wrong_aliases.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: wrong_aliases
short_description: Aliases that are attached to the wrong option in documentation
description: Aliases that are attached to the wrong option in documentation.
@@ -18,10 +18,10 @@ options:
bar:
description: Bar.
type: str
-'''
+"""
-EXAMPLES = '''#'''
-RETURN = ''''''
+EXAMPLES = """#"""
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/ps_only/plugins/modules/validate.py b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/ps_only/plugins/modules/validate.py
index ee1fb13840..801a0b0c0c 100644
--- a/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/ps_only/plugins/modules/validate.py
+++ b/test/integration/targets/ansible-test-sanity-validate-modules/ansible_collections/ns/ps_only/plugins/modules/validate.py
@@ -1,14 +1,14 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: validate
short_description: validate
description: validate
author: "validate (@validate)"
-'''
+"""
-EXAMPLES = r'''
-'''
+EXAMPLES = r"""
+"""
-RETURN = r'''
-'''
+RETURN = r"""
+"""
diff --git a/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/bad.py b/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/bad.py
index 617353b20e..8854e2fef7 100644
--- a/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/bad.py
+++ b/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/bad.py
@@ -2,20 +2,20 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: bad
short_description: Bad lookup
description: A bad lookup.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- debug:
msg: "{{ lookup('ns.col.bad') }}"
-'''
+"""
-RETURN = ''' # '''
+RETURN = """ # """
from ansible.plugins.lookup import LookupBase
from ansible import constants # pylint: disable=unused-import
diff --git a/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/world.py b/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/world.py
index 093447d906..343843fdc4 100644
--- a/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/world.py
+++ b/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/lookup/world.py
@@ -2,20 +2,20 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: world
short_description: World lookup
description: A world lookup.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- debug:
msg: "{{ lookup('ns.col.world') }}"
-'''
+"""
-RETURN = ''' # '''
+RETURN = """ # """
from ansible.plugins.lookup import LookupBase
from ansible import constants # pylint: disable=unused-import
diff --git a/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/modules/bad.py b/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/modules/bad.py
index 72d859adf1..6efe7d469d 100644
--- a/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/modules/bad.py
+++ b/test/integration/targets/ansible-test-sanity/ansible_collections/ns/col/plugins/modules/bad.py
@@ -3,19 +3,19 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: bad
short_description: Bad test module
description: Bad test module.
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- bad:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
from ansible import constants # intentionally trigger pylint ansible-bad-module-import error # pylint: disable=unused-import
diff --git a/test/integration/targets/ansible-test-units/ansible_collections/ns/col/plugins/modules/hello.py b/test/integration/targets/ansible-test-units/ansible_collections/ns/col/plugins/modules/hello.py
index 06ff6d4bc6..862c855e36 100644
--- a/test/integration/targets/ansible-test-units/ansible_collections/ns/col/plugins/modules/hello.py
+++ b/test/integration/targets/ansible-test-units/ansible_collections/ns/col/plugins/modules/hello.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
module: hello
short_description: Hello test module
description: Hello test module.
@@ -13,13 +13,13 @@ options:
type: str
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- hello:
-'''
+"""
-RETURN = ''''''
+RETURN = """"""
from ansible.module_utils.basic import AnsibleModule
from ..module_utils.my_util import hello
diff --git a/test/integration/targets/callback_results/callback_plugins/track_connections.py b/test/integration/targets/callback_results/callback_plugins/track_connections.py
index ba161a7802..de033762f1 100644
--- a/test/integration/targets/callback_results/callback_plugins/track_connections.py
+++ b/test/integration/targets/callback_results/callback_plugins/track_connections.py
@@ -3,13 +3,13 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: track_connections
short_description: Track connection plugins used for hosts
description:
- Track connection plugins used for hosts
type: aggregate
-'''
+"""
import json
from collections import defaultdict
diff --git a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/callback/usercallback.py b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/callback/usercallback.py
index 3eb9764a85..3800dc8f7b 100644
--- a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/callback/usercallback.py
+++ b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/callback/usercallback.py
@@ -2,13 +2,13 @@ from __future__ import annotations
from ansible.plugins.callback import CallbackBase
-DOCUMENTATION = '''
+DOCUMENTATION = """
callback: usercallback
callback_type: notification
short_description: does stuff
description:
- does some stuff
-'''
+"""
class CallbackModule(CallbackBase):
diff --git a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/doc_fragments/frag.py b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/doc_fragments/frag.py
index 8fbcb360ce..067c67e202 100644
--- a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/doc_fragments/frag.py
+++ b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/doc_fragments/frag.py
@@ -2,16 +2,16 @@ from __future__ import annotations
class ModuleDocFragment(object):
- DOCUMENTATION = r'''
+ DOCUMENTATION = r"""
options:
normal_doc_frag:
description:
- an option
-'''
+"""
- OTHER_DOCUMENTATION = r'''
+ OTHER_DOCUMENTATION = r"""
options:
other_doc_frag:
description:
- another option
-'''
+"""
diff --git a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule.py b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule.py
index 6ec24b4e95..d6fde64f11 100644
--- a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule.py
+++ b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule.py
@@ -3,13 +3,13 @@ from __future__ import annotations
import json
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: testmodule
description: for testing
extends_documentation_fragment:
- testns.testcoll.frag
- testns.testcoll.frag.other_documentation
-'''
+"""
def main():
diff --git a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule_bad_docfrags.py b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule_bad_docfrags.py
index d39efc8d22..2534b5b403 100644
--- a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule_bad_docfrags.py
+++ b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/modules/testmodule_bad_docfrags.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import json
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
module: testmodule
description: for testing
extends_documentation_fragment:
@@ -13,7 +13,7 @@ extends_documentation_fragment:
- testns.boguscoll.frag
- testns.testcoll.bogusfrag
- testns.testcoll.frag.bogusvar
-'''
+"""
def main():
diff --git a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/vars/custom_vars.py b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/vars/custom_vars.py
index e1997ae74e..49f876247f 100644
--- a/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/vars/custom_vars.py
+++ b/test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/vars/custom_vars.py
@@ -17,7 +17,7 @@
#############################################
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
vars: custom_vars
version_added: "2.10"
short_description: load host and group vars
@@ -31,7 +31,7 @@ DOCUMENTATION = '''
section: custom_vars
env:
- name: ANSIBLE_VARS_PLUGIN_STAGE
-'''
+"""
from ansible.plugins.vars import BaseVarsPlugin
diff --git a/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/action/action1.py b/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/action/action1.py
index 43f8ec3293..93ff9b450c 100644
--- a/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/action/action1.py
+++ b/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/action/action1.py
@@ -6,7 +6,7 @@ from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
- ''' handler for file transfer operations '''
+ """ handler for file transfer operations """
if task_vars is None:
task_vars = dict()
diff --git a/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/modules/action1.py b/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/modules/action1.py
index 03b165169b..8cfc159cf4 100644
--- a/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/modules/action1.py
+++ b/test/integration/targets/collections/collections/ansible_collections/me/mycoll1/plugins/modules/action1.py
@@ -6,7 +6,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: action1
short_description: Action Test module
@@ -14,10 +14,10 @@ description:
- Action Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
diff --git a/test/integration/targets/collections/collections/ansible_collections/me/mycoll2/plugins/modules/module1.py b/test/integration/targets/collections/collections/ansible_collections/me/mycoll2/plugins/modules/module1.py
index b0d3f6da3c..0aaccde10e 100644
--- a/test/integration/targets/collections/collections/ansible_collections/me/mycoll2/plugins/modules/module1.py
+++ b/test/integration/targets/collections/collections/ansible_collections/me/mycoll2/plugins/modules/module1.py
@@ -6,7 +6,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: module1
short_description: module1 Test module
@@ -14,13 +14,13 @@ description:
- module1 Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/cache/custom_jsonfile.py b/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/cache/custom_jsonfile.py
index 393a43f81b..5373ad34c2 100644
--- a/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/cache/custom_jsonfile.py
+++ b/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/cache/custom_jsonfile.py
@@ -4,7 +4,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: jsonfile
short_description: JSON formatted files.
description:
@@ -37,7 +37,7 @@ DOCUMENTATION = '''
- key: fact_caching_timeout
section: defaults
type: integer
-'''
+"""
import codecs
import json
diff --git a/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/inventory/statichost.py b/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/inventory/statichost.py
index b2405e322e..aa0d179e49 100644
--- a/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/inventory/statichost.py
+++ b/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/inventory/statichost.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
inventory: statichost
short_description: Add a single host
description: Add a single host
@@ -16,7 +16,7 @@ DOCUMENTATION = '''
hostname:
description: Toggle display of stderr even when script was successful
required: True
-'''
+"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
@@ -32,7 +32,7 @@ class InventoryModule(BaseInventoryPlugin, Cacheable):
self._hosts = set()
def verify_file(self, path):
- ''' Verify if file is usable by this plugin, base does minimal accessibility check '''
+ """ Verify if file is usable by this plugin, base does minimal accessibility check """
if not path.endswith('.statichost.yml') and not path.endswith('.statichost.yaml'):
return False
diff --git a/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/vars/custom_adj_vars.py b/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/vars/custom_adj_vars.py
index b98fe7bba2..0b51e731a2 100644
--- a/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/vars/custom_adj_vars.py
+++ b/test/integration/targets/collections/collections/ansible_collections/testns/content_adj/plugins/vars/custom_adj_vars.py
@@ -17,7 +17,7 @@
#############################################
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
vars: custom_adj_vars
version_added: "2.10"
short_description: load host and group vars
@@ -32,7 +32,7 @@ DOCUMENTATION = '''
section: custom_adj_vars
env:
- name: ANSIBLE_VARS_PLUGIN_STAGE
-'''
+"""
from ansible.plugins.vars import BaseVarsPlugin
diff --git a/test/integration/targets/collections/custom_vars_plugins/v1_vars_plugin.py b/test/integration/targets/collections/custom_vars_plugins/v1_vars_plugin.py
index ce79baa7f2..5511912722 100644
--- a/test/integration/targets/collections/custom_vars_plugins/v1_vars_plugin.py
+++ b/test/integration/targets/collections/custom_vars_plugins/v1_vars_plugin.py
@@ -17,14 +17,14 @@
#############################################
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
vars: v1_vars_plugin
version_added: "2.10"
short_description: load host and group vars
description:
- Third-party vars plugin to test loading host and group vars without enabling and without a plugin-specific stage option
options:
-'''
+"""
from ansible.plugins.vars import BaseVarsPlugin
diff --git a/test/integration/targets/collections/custom_vars_plugins/v2_vars_plugin.py b/test/integration/targets/collections/custom_vars_plugins/v2_vars_plugin.py
index a6894ac912..1b2cb008a2 100644
--- a/test/integration/targets/collections/custom_vars_plugins/v2_vars_plugin.py
+++ b/test/integration/targets/collections/custom_vars_plugins/v2_vars_plugin.py
@@ -17,7 +17,7 @@
#############################################
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
vars: v2_vars_plugin
version_added: "2.10"
short_description: load host and group vars
@@ -32,7 +32,7 @@ DOCUMENTATION = '''
section: other_vars_plugin
env:
- name: ANSIBLE_VARS_PLUGIN_STAGE
-'''
+"""
from ansible.plugins.vars import BaseVarsPlugin
diff --git a/test/integration/targets/collections/test_task_resolved_plugin/callback_plugins/display_resolved_action.py b/test/integration/targets/collections/test_task_resolved_plugin/callback_plugins/display_resolved_action.py
index ba71668426..5100ae29f3 100644
--- a/test/integration/targets/collections/test_task_resolved_plugin/callback_plugins/display_resolved_action.py
+++ b/test/integration/targets/collections/test_task_resolved_plugin/callback_plugins/display_resolved_action.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: display_resolved_action
type: aggregate
short_description: Displays the requested and resolved actions at the end of a playbook.
@@ -11,7 +11,7 @@ DOCUMENTATION = '''
- Displays the requested and resolved actions in the format "requested == resolved".
requirements:
- Enable in configuration.
-'''
+"""
from ansible.plugins.callback import CallbackBase
diff --git a/test/integration/targets/collections/test_task_resolved_plugin/collections/ansible_collections/test_ns/test_coll/plugins/modules/collection_module.py b/test/integration/targets/collections/test_task_resolved_plugin/collections/ansible_collections/test_ns/test_coll/plugins/modules/collection_module.py
index ddfa9097f7..d5b09a78df 100644
--- a/test/integration/targets/collections/test_task_resolved_plugin/collections/ansible_collections/test_ns/test_coll/plugins/modules/collection_module.py
+++ b/test/integration/targets/collections/test_task_resolved_plugin/collections/ansible_collections/test_ns/test_coll/plugins/modules/collection_module.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: collection_module
short_description: A module to test a task's resolved action name.
@@ -14,7 +14,7 @@ options: {}
author: Ansible Core Team
notes:
- Supports C(check_mode).
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/collections/test_task_resolved_plugin/library/legacy_module.py b/test/integration/targets/collections/test_task_resolved_plugin/library/legacy_module.py
index 98fccbbdf4..2c4e55f82c 100644
--- a/test/integration/targets/collections/test_task_resolved_plugin/library/legacy_module.py
+++ b/test/integration/targets/collections/test_task_resolved_plugin/library/legacy_module.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: legacy_module
short_description: A module to test a task's resolved action name.
@@ -14,7 +14,7 @@ options: {}
author: Ansible Core Team
notes:
- Supports C(check_mode).
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/collections/testcoll2/plugins/modules/testmodule2.py b/test/integration/targets/collections/testcoll2/plugins/modules/testmodule2.py
index f8db43ec1b..bfe1310d9b 100644
--- a/test/integration/targets/collections/testcoll2/plugins/modules/testmodule2.py
+++ b/test/integration/targets/collections/testcoll2/plugins/modules/testmodule2.py
@@ -5,7 +5,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: testmodule2
short_description: Test module
@@ -13,13 +13,13 @@ description:
- Test module
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
import json
diff --git a/test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py b/test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py
index 20a309fa35..902ad5240f 100644
--- a/test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py
+++ b/test/integration/targets/connection_remote_is_local/connection_plugins/remote_is_local.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: remote_is_local
short_description: remote is local
description:
@@ -14,7 +14,7 @@ DOCUMENTATION = '''
- 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
diff --git a/test/integration/targets/delegate_to/connection_plugins/fakelocal.py b/test/integration/targets/delegate_to/connection_plugins/fakelocal.py
index e0ecdfde5f..6696ac7417 100644
--- a/test/integration/targets/delegate_to/connection_plugins/fakelocal.py
+++ b/test/integration/targets/delegate_to/connection_plugins/fakelocal.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
connection: fakelocal
short_description: dont execute anything
description:
@@ -22,7 +22,7 @@ DOCUMENTATION = '''
key: remote_user
vars:
- name: ansible_user
-'''
+"""
from ansible.errors import AnsibleConnectionFailure
from ansible.plugins.connection import ConnectionBase
@@ -32,7 +32,7 @@ display = Display()
class Connection(ConnectionBase):
- ''' Local based connections '''
+ """ Local based connections """
transport = 'fakelocal'
has_pipelining = True
@@ -43,7 +43,7 @@ class Connection(ConnectionBase):
self.cwd = None
def _connect(self):
- ''' verify '''
+ """ verify """
if self.get_option('remote_user') == 'invaliduser' and self.get_option('password') == 'badpassword':
raise AnsibleConnectionFailure('Got invaliduser and badpassword')
@@ -54,22 +54,22 @@ class Connection(ConnectionBase):
return self
def exec_command(self, cmd, in_data=None, sudoable=True):
- ''' run a command on the local host '''
+ """ run a command on the local host """
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
return 0, '{"msg": "ALL IS GOOD"}', ''
def put_file(self, in_path, out_path):
- ''' transfer a file from local to local '''
+ """ transfer a file from local to local """
super(Connection, self).put_file(in_path, out_path)
def fetch_file(self, in_path, out_path):
- ''' fetch a file from local to local -- for compatibility '''
+ """ fetch a file from local to local -- for compatibility """
super(Connection, self).fetch_file(in_path, out_path)
def close(self):
- ''' terminate the connection; nothing to do here '''
+ """ terminate the connection; nothing to do here """
self._connected = False
diff --git a/test/integration/targets/deprecations/cache_plugins/notjsonfile.py b/test/integration/targets/deprecations/cache_plugins/notjsonfile.py
index dfa20158f7..800fe3bb36 100644
--- a/test/integration/targets/deprecations/cache_plugins/notjsonfile.py
+++ b/test/integration/targets/deprecations/cache_plugins/notjsonfile.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: notjsonfile
short_description: NotJSON cache plugin
description: This cache uses is NOT JSON
@@ -66,7 +66,7 @@ DOCUMENTATION = '''
version: '2.0.0'
env:
- name: ANSIBLE_NOTJSON_CACHE_PLUGIN_REMOVEME
-'''
+"""
from ansible.plugins.cache import BaseFileCacheModule
diff --git a/test/integration/targets/deprecations/library/removeoption.py b/test/integration/targets/deprecations/library/removeoption.py
index 9f08792fcd..0fca3435a8 100644
--- a/test/integration/targets/deprecations/library/removeoption.py
+++ b/test/integration/targets/deprecations/library/removeoption.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: removeoption
short_description: noop
@@ -42,17 +42,17 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: useless
remove_option:
one: true
two: /etc/file.conf
-'''
+"""
-RETURN = r'''
-'''
+RETURN = r"""
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/deprecations/library/willremove.py b/test/integration/targets/deprecations/library/willremove.py
index 0c5810d850..87e9176840 100644
--- a/test/integration/targets/deprecations/library/willremove.py
+++ b/test/integration/targets/deprecations/library/willremove.py
@@ -5,7 +5,7 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: willremove
version_added: histerical
@@ -43,17 +43,17 @@ attributes:
support: none
platform:
platforms: all
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: useless
willremove:
one: true
two: /etc/file.conf
-'''
+"""
-RETURN = r'''
-'''
+RETURN = r"""
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/dict_transformations/library/convert_camelCase.py b/test/integration/targets/dict_transformations/library/convert_camelCase.py
index 0bc267cb68..7767fa7d8e 100644
--- a/test/integration/targets/dict_transformations/library/convert_camelCase.py
+++ b/test/integration/targets/dict_transformations/library/convert_camelCase.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: convert_camelCase
short_description: test converting data to camelCase
@@ -20,7 +20,7 @@ options:
description: Whether to capitalize the first character
default: False
type: bool
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/dict_transformations/library/convert_snake_case.py b/test/integration/targets/dict_transformations/library/convert_snake_case.py
index b645eb7aa7..9b927be3b3 100644
--- a/test/integration/targets/dict_transformations/library/convert_snake_case.py
+++ b/test/integration/targets/dict_transformations/library/convert_snake_case.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: convert_snake_case
short_description: test converting data to snake_case
@@ -25,7 +25,7 @@ options:
description: list of top level keys that should not have their contents converted
type: list
default: []
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/gathering_facts/cache_plugins/none.py b/test/integration/targets/gathering_facts/cache_plugins/none.py
index 715f7aec23..0150eb4b64 100644
--- a/test/integration/targets/gathering_facts/cache_plugins/none.py
+++ b/test/integration/targets/gathering_facts/cache_plugins/none.py
@@ -7,14 +7,14 @@ from __future__ import annotations
from ansible.plugins.cache import BaseCacheModule
-DOCUMENTATION = '''
+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):
diff --git a/test/integration/targets/inventory/inventory_plugins/constructed_with_hostvars.py b/test/integration/targets/inventory/inventory_plugins/constructed_with_hostvars.py
index 8e179eb44c..b8f5333413 100644
--- a/test/integration/targets/inventory/inventory_plugins/constructed_with_hostvars.py
+++ b/test/integration/targets/inventory/inventory_plugins/constructed_with_hostvars.py
@@ -3,14 +3,14 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: constructed_with_hostvars
options:
plugin:
description: the load name of the plugin
extends_documentation_fragment:
- constructed
-'''
+"""
from ansible.errors import AnsibleParserError
from ansible.module_utils.common.text.converters import to_native
diff --git a/test/integration/targets/inventory_cache/plugins/inventory/cache_host.py b/test/integration/targets/inventory_cache/plugins/inventory/cache_host.py
index 6c93f03d45..8283d3b788 100644
--- a/test/integration/targets/inventory_cache/plugins/inventory/cache_host.py
+++ b/test/integration/targets/inventory_cache/plugins/inventory/cache_host.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
inventory: cache_host
short_description: add a host to inventory and cache it
description: add a host to inventory and cache it
@@ -13,7 +13,7 @@ DOCUMENTATION = '''
plugin:
required: true
description: name of the plugin (cache_host)
-'''
+"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
import random
diff --git a/test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py b/test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py
index 04afd0e953..66714eab54 100644
--- a/test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py
+++ b/test/integration/targets/inventory_cache/plugins/inventory/exercise_cache.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
inventory: exercise_cache
short_description: run tests against the specified cache plugin
description:
@@ -23,7 +23,7 @@ DOCUMENTATION = '''
env: []
cli: []
default: 0 # never expire
-'''
+"""
from ansible.errors import AnsibleError
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
diff --git a/test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py b/test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py
index ca2ac250c7..9fb555e7ed 100644
--- a/test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py
+++ b/test/integration/targets/loop-connection/collections/ansible_collections/ns/name/plugins/connection/dummy.py
@@ -1,13 +1,13 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: dummy
short_description: Used for loop-connection tests
description:
- See above
author: ansible (@core)
-'''
+"""
from ansible.errors import AnsibleError
from ansible.plugins.connection import ConnectionBase
diff --git a/test/integration/targets/module_defaults/action_plugins/debug.py b/test/integration/targets/module_defaults/action_plugins/debug.py
index 63c0779b13..942aa6dab2 100644
--- a/test/integration/targets/module_defaults/action_plugins/debug.py
+++ b/test/integration/targets/module_defaults/action_plugins/debug.py
@@ -24,7 +24,7 @@ from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
- ''' Print statements during execution '''
+ """ Print statements during execution """
TRANSFERS_FILES = False
_VALID_ARGS = frozenset(('msg', 'var', 'verbosity'))
diff --git a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/eosfacts.py b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/eosfacts.py
index 546205b1c9..632f3bb529 100644
--- a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/eosfacts.py
+++ b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/eosfacts.py
@@ -6,16 +6,16 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: eosfacts
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
-'''
+"""
-EXAMPLES = r'''
-'''
+EXAMPLES = r"""
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ios_facts.py b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ios_facts.py
index 2e230ec533..4d587c59a9 100644
--- a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ios_facts.py
+++ b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ios_facts.py
@@ -6,16 +6,16 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: ios_facts
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
-'''
+"""
-EXAMPLES = r'''
-'''
+EXAMPLES = r"""
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/metadata.py b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/metadata.py
index 439b415578..81a7f626b8 100644
--- a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/metadata.py
+++ b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/metadata.py
@@ -6,7 +6,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: metadata
version_added: 2.12
@@ -19,13 +19,13 @@ options:
type: str
author:
- Ansible Core Team
-'''
+"""
-EXAMPLES = '''
-'''
+EXAMPLES = """
+"""
-RETURN = '''
-'''
+RETURN = """
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/module.py b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/module.py
index f7a1932d7c..710cd23672 100644
--- a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/module.py
+++ b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/module.py
@@ -6,16 +6,16 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: module
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
-'''
+"""
-EXAMPLES = r'''
-'''
+EXAMPLES = r"""
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ping.py b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ping.py
index b54b701d57..33c282b888 100644
--- a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ping.py
+++ b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/ping.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -35,9 +35,9 @@ author:
- Michael DeHaan
notes:
- Supports C(check_mode).
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
@@ -47,15 +47,15 @@ EXAMPLES = '''
- name: Induce an exception to see what happens
ansible.builtin.ping:
data: crash
-'''
+"""
-RETURN = '''
+RETURN = """
ping:
description: Value provided with the data parameter.
returned: success
type: str
sample: pong
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/vyosfacts.py b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/vyosfacts.py
index 7af1c6bdc0..dc3528ed8c 100644
--- a/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/vyosfacts.py
+++ b/test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/modules/vyosfacts.py
@@ -6,16 +6,16 @@
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: vyosfacts
short_description: module to test module_defaults
description: module to test module_defaults
version_added: '2.13'
-'''
+"""
-EXAMPLES = r'''
-'''
+EXAMPLES = r"""
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_defaults/library/legacy_ping.py b/test/integration/targets/module_defaults/library/legacy_ping.py
index b54b701d57..33c282b888 100644
--- a/test/integration/targets/module_defaults/library/legacy_ping.py
+++ b/test/integration/targets/module_defaults/library/legacy_ping.py
@@ -8,7 +8,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -35,9 +35,9 @@ author:
- Michael DeHaan
notes:
- Supports C(check_mode).
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
# ansible webservers -m ping
@@ -47,15 +47,15 @@ EXAMPLES = '''
- name: Induce an exception to see what happens
ansible.builtin.ping:
data: crash
-'''
+"""
-RETURN = '''
+RETURN = """
ping:
description: Value provided with the data parameter.
returned: success
type: str
sample: pong
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_precedence/lib_with_extension/ping.py b/test/integration/targets/module_precedence/lib_with_extension/ping.py
index ab4a9893d6..f31eb79b12 100644
--- a/test/integration/targets/module_precedence/lib_with_extension/ping.py
+++ b/test/integration/targets/module_precedence/lib_with_extension/ping.py
@@ -26,7 +26,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -40,12 +40,12 @@ options: {}
author:
- "Ansible Core Team"
- "Michael DeHaan"
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
ansible webservers -m ping
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_precedence/multiple_roles/bar/library/ping.py b/test/integration/targets/module_precedence/multiple_roles/bar/library/ping.py
index 88fc595d27..a61c8d947b 100644
--- a/test/integration/targets/module_precedence/multiple_roles/bar/library/ping.py
+++ b/test/integration/targets/module_precedence/multiple_roles/bar/library/ping.py
@@ -26,7 +26,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -40,12 +40,12 @@ options: {}
author:
- "Ansible Core Team"
- "Michael DeHaan"
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
ansible webservers -m ping
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_precedence/multiple_roles/foo/library/ping.py b/test/integration/targets/module_precedence/multiple_roles/foo/library/ping.py
index 72c3cb8bc0..68c33d055a 100644
--- a/test/integration/targets/module_precedence/multiple_roles/foo/library/ping.py
+++ b/test/integration/targets/module_precedence/multiple_roles/foo/library/ping.py
@@ -26,7 +26,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -40,12 +40,12 @@ options: {}
author:
- "Ansible Core Team"
- "Michael DeHaan"
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
ansible webservers -m ping
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_precedence/roles_with_extension/foo/library/ping.py b/test/integration/targets/module_precedence/roles_with_extension/foo/library/ping.py
index 72c3cb8bc0..68c33d055a 100644
--- a/test/integration/targets/module_precedence/roles_with_extension/foo/library/ping.py
+++ b/test/integration/targets/module_precedence/roles_with_extension/foo/library/ping.py
@@ -26,7 +26,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'core'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: ping
version_added: historical
@@ -40,12 +40,12 @@ options: {}
author:
- "Ansible Core Team"
- "Michael DeHaan"
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Test we can logon to 'webservers' and execute python with json lib.
ansible webservers -m ping
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
diff --git a/test/integration/targets/module_utils/callback/pure_json.py b/test/integration/targets/module_utils/callback/pure_json.py
index 7a9b800688..b60c1b77ec 100644
--- a/test/integration/targets/module_utils/callback/pure_json.py
+++ b/test/integration/targets/module_utils/callback/pure_json.py
@@ -3,11 +3,11 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: pure_json
type: stdout
short_description: only outputs the module results as json
-'''
+"""
import json
diff --git a/test/integration/targets/module_utils_ansible_release/library/ansible_release.py b/test/integration/targets/module_utils_ansible_release/library/ansible_release.py
index 8e15b856d4..7e43bde493 100644
--- a/test/integration/targets/module_utils_ansible_release/library/ansible_release.py
+++ b/test/integration/targets/module_utils_ansible_release/library/ansible_release.py
@@ -4,22 +4,22 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = r'''
+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'''
+EXAMPLES = r"""
#
-'''
+"""
-RETURN = r'''
+RETURN = r"""
#
-'''
+"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ansible_release import __version__, __author__, __codename__
diff --git a/test/integration/targets/module_utils_urls/library/test_peercert.py b/test/integration/targets/module_utils_urls/library/test_peercert.py
index 7bac222288..cc835c11cd 100644
--- a/test/integration/targets/module_utils_urls/library/test_peercert.py
+++ b/test/integration/targets/module_utils_urls/library/test_peercert.py
@@ -4,7 +4,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: test_perrcert
short_description: Test getting the peer certificate of a HTTP response
@@ -16,15 +16,15 @@ options:
type: str
author:
- Ansible Project
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
#
-'''
+"""
-RETURN = r'''
+RETURN = r"""
#
-'''
+"""
import base64
diff --git a/test/integration/targets/old_style_cache_plugins/plugins/cache/configurable_redis.py b/test/integration/targets/old_style_cache_plugins/plugins/cache/configurable_redis.py
index 805cdbafe8..631201ebaa 100644
--- a/test/integration/targets/old_style_cache_plugins/plugins/cache/configurable_redis.py
+++ b/test/integration/targets/old_style_cache_plugins/plugins/cache/configurable_redis.py
@@ -3,7 +3,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: configurable_redis
short_description: Use Redis DB for cache
description:
@@ -38,7 +38,7 @@ DOCUMENTATION = '''
- key: fact_caching_timeout
section: defaults
type: integer
-'''
+"""
import time
import json
diff --git a/test/integration/targets/old_style_cache_plugins/plugins/cache/legacy_redis.py b/test/integration/targets/old_style_cache_plugins/plugins/cache/legacy_redis.py
index 98bd188c24..773d32977e 100644
--- a/test/integration/targets/old_style_cache_plugins/plugins/cache/legacy_redis.py
+++ b/test/integration/targets/old_style_cache_plugins/plugins/cache/legacy_redis.py
@@ -3,7 +3,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: redis
short_description: Use Redis DB for cache
description:
@@ -37,7 +37,7 @@ DOCUMENTATION = '''
- key: fact_caching_timeout
section: defaults
type: integer
-'''
+"""
import time
import json
diff --git a/test/integration/targets/old_style_cache_plugins/plugins/inventory/test.py b/test/integration/targets/old_style_cache_plugins/plugins/inventory/test.py
index 6dd450f2dd..f1edd60e60 100644
--- a/test/integration/targets/old_style_cache_plugins/plugins/inventory/test.py
+++ b/test/integration/targets/old_style_cache_plugins/plugins/inventory/test.py
@@ -3,13 +3,13 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: test
plugin_type: inventory
short_description: test inventory source
extends_documentation_fragment:
- inventory_cache
-'''
+"""
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable
diff --git a/test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py b/test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py
index 771b418c92..449231f803 100644
--- a/test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py
+++ b/test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py
@@ -7,7 +7,7 @@ from __future__ import annotations
from ansible.plugins.cache import BaseCacheModule
-DOCUMENTATION = '''
+DOCUMENTATION = """
cache: none
short_description: write-only cache (no cache)
description:
@@ -24,7 +24,7 @@ DOCUMENTATION = '''
- key: fact_caching_timeout
section: defaults
type: integer
-'''
+"""
class CacheModule(BaseCacheModule):
diff --git a/test/integration/targets/plugin_config_for_inventory/test_inventory.py b/test/integration/targets/plugin_config_for_inventory/test_inventory.py
index ad39efc335..6d34ee566c 100644
--- a/test/integration/targets/plugin_config_for_inventory/test_inventory.py
+++ b/test/integration/targets/plugin_config_for_inventory/test_inventory.py
@@ -1,7 +1,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
name: test_inventory
plugin_type: inventory
authors:
@@ -42,15 +42,15 @@ DOCUMENTATION = '''
type: str
default: prefix_
required: False
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
# Example command line: ansible-inventory --list -i test_inventory.yml
plugin: test_inventory
departments:
- paris
-'''
+"""
from ansible.plugins.inventory import BaseInventoryPlugin
diff --git a/test/integration/targets/plugin_loader/file_collision/roles/r1/filter_plugins/custom.py b/test/integration/targets/plugin_loader/file_collision/roles/r1/filter_plugins/custom.py
index 7adbf7dced..858033c085 100644
--- a/test/integration/targets/plugin_loader/file_collision/roles/r1/filter_plugins/custom.py
+++ b/test/integration/targets/plugin_loader/file_collision/roles/r1/filter_plugins/custom.py
@@ -6,7 +6,7 @@ def do_nothing(myval):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/test/integration/targets/plugin_loader/file_collision/roles/r2/filter_plugins/custom.py b/test/integration/targets/plugin_loader/file_collision/roles/r2/filter_plugins/custom.py
index 8a7a4f5270..fa2d0e3efa 100644
--- a/test/integration/targets/plugin_loader/file_collision/roles/r2/filter_plugins/custom.py
+++ b/test/integration/targets/plugin_loader/file_collision/roles/r2/filter_plugins/custom.py
@@ -6,7 +6,7 @@ def do_nothing(myval):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/test/integration/targets/plugin_loader/override/filter_plugins/core.py b/test/integration/targets/plugin_loader/override/filter_plugins/core.py
index 89246377cb..415e8a9ff1 100644
--- a/test/integration/targets/plugin_loader/override/filter_plugins/core.py
+++ b/test/integration/targets/plugin_loader/override/filter_plugins/core.py
@@ -6,7 +6,7 @@ def do_flag(myval):
class FilterModule(object):
- ''' Ansible core jinja2 filters '''
+ """ Ansible core jinja2 filters """
def filters(self):
return {
diff --git a/test/integration/targets/prepare_http_tests/library/httptester_kinit.py b/test/integration/targets/prepare_http_tests/library/httptester_kinit.py
index a84e3fb443..db3ef6b1a7 100644
--- a/test/integration/targets/prepare_http_tests/library/httptester_kinit.py
+++ b/test/integration/targets/prepare_http_tests/library/httptester_kinit.py
@@ -4,7 +4,7 @@
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import annotations
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: httptester_kinit
short_description: Get Kerberos ticket
@@ -20,15 +20,15 @@ options:
type: str
author:
- Ansible Project
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
#
-'''
+"""
-RETURN = r'''
+RETURN = r"""
#
-'''
+"""
import contextlib
import errno
diff --git a/test/integration/targets/rel_plugin_loading/subdir/inventory_plugins/notyaml.py b/test/integration/targets/rel_plugin_loading/subdir/inventory_plugins/notyaml.py
index e93b500c28..c068681292 100644
--- a/test/integration/targets/rel_plugin_loading/subdir/inventory_plugins/notyaml.py
+++ b/test/integration/targets/rel_plugin_loading/subdir/inventory_plugins/notyaml.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
inventory: yaml
version_added: "2.4"
short_description: Uses a specific YAML file as an inventory source.
@@ -30,8 +30,8 @@ DOCUMENTATION = '''
- section: inventory_plugin_yaml
key: yaml_valid_extensions
-'''
-EXAMPLES = '''
+"""
+EXAMPLES = """
all: # keys must be unique, i.e. only one 'hosts' per group
hosts:
test1:
@@ -55,7 +55,7 @@ all: # keys must be unique, i.e. only one 'hosts' per group
test1 # same host as above, additional group membership
vars:
group_last_var: value
-'''
+"""
import os
@@ -87,7 +87,7 @@ class InventoryModule(BaseFileInventoryPlugin):
return valid
def parse(self, inventory, loader, path, cache=True):
- ''' parses the inventory file '''
+ """ parses the inventory file """
super(InventoryModule, self).parse(inventory, loader, path)
self.set_options()
@@ -160,9 +160,9 @@ class InventoryModule(BaseFileInventoryPlugin):
self.display.warning("Skipping '%s' as this is not a valid group definition" % group)
def _parse_host(self, host_pattern):
- '''
+ """
Each host key can be a pattern, try to process it and add variables as needed
- '''
+ """
(hostnames, port) = self._expand_hostpattern(host_pattern)
return hostnames, port
diff --git a/test/integration/targets/shell/connection_plugins/test_connection_default.py b/test/integration/targets/shell/connection_plugins/test_connection_default.py
index 5ff494c812..db23b8a142 100644
--- a/test/integration/targets/shell/connection_plugins/test_connection_default.py
+++ b/test/integration/targets/shell/connection_plugins/test_connection_default.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
connection: test_connection_default
short_description: test connection plugin used in tests
description:
@@ -11,13 +11,13 @@ description:
author: ansible (@core)
version_added: historical
options:
-'''
+"""
from ansible.plugins.connection import ConnectionBase
class Connection(ConnectionBase):
- ''' test connection '''
+ """ test connection """
transport = 'test_connection_default'
diff --git a/test/integration/targets/shell/connection_plugins/test_connection_override.py b/test/integration/targets/shell/connection_plugins/test_connection_override.py
index b962dfa75f..776185489c 100644
--- a/test/integration/targets/shell/connection_plugins/test_connection_override.py
+++ b/test/integration/targets/shell/connection_plugins/test_connection_override.py
@@ -3,7 +3,7 @@
from __future__ import annotations
-DOCUMENTATION = '''
+DOCUMENTATION = """
connection: test_connection_override
short_description: test connection plugin used in tests
description:
@@ -11,13 +11,13 @@ description:
author: ansible (@core)
version_added: historical
options:
-'''
+"""
from ansible.plugins.connection import ConnectionBase
class Connection(ConnectionBase):
- ''' test connection '''
+ """ test connection """
transport = 'test_connection_override'
diff --git a/test/integration/targets/var_precedence/ansible-var-precedence-check.py b/test/integration/targets/var_precedence/ansible-var-precedence-check.py
index 6511169014..e75bcdd315 100755
--- a/test/integration/targets/var_precedence/ansible-var-precedence-check.py
+++ b/test/integration/targets/var_precedence/ansible-var-precedence-check.py
@@ -373,12 +373,12 @@ class VarTestMaker(object):
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"'
diff --git a/test/integration/targets/windows-minimal/library/win_ping.py b/test/integration/targets/windows-minimal/library/win_ping.py
index 6d35f37994..8784bc9c07 100644
--- a/test/integration/targets/windows-minimal/library/win_ping.py
+++ b/test/integration/targets/windows-minimal/library/win_ping.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_ping
version_added: "1.7"
@@ -32,9 +32,9 @@ seealso:
- module: ping
author:
- Chris Church (@cchurch)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Test connectivity to a windows host
# ansible winserver -m win_ping
@@ -44,12 +44,12 @@ EXAMPLES = r'''
- name: Induce an exception to see what happens
win_ping:
data: crash
-'''
+"""
-RETURN = r'''
+RETURN = r"""
ping:
description: Value provided with the data parameter.
returned: success
type: str
sample: pong
-'''
+"""
diff --git a/test/support/integration/plugins/modules/pkgng.py b/test/support/integration/plugins/modules/pkgng.py
index 85c563664b..f6cbd6be40 100644
--- a/test/support/integration/plugins/modules/pkgng.py
+++ b/test/support/integration/plugins/modules/pkgng.py
@@ -17,7 +17,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'community'}
-DOCUMENTATION = '''
+DOCUMENTATION = """
---
module: pkgng
short_description: Package manager for FreeBSD >= 9.0
@@ -88,9 +88,9 @@ notes:
- When using pkgsite, be careful that already in cache packages won't be downloaded again.
- When used with a `loop:` each package will be processed individually,
it is much more efficient to pass the list directly to the `name` option.
-'''
+"""
-EXAMPLES = '''
+EXAMPLES = """
- name: Install package foo
pkgng:
name: foo
@@ -111,7 +111,7 @@ EXAMPLES = '''
pkgng:
name: baz
state: latest
-'''
+"""
import re
diff --git a/test/support/windows-integration/collections/ansible_collections/ansible/windows/plugins/modules/win_uri.py b/test/support/windows-integration/collections/ansible_collections/ansible/windows/plugins/modules/win_uri.py
index 3b1094eacf..9b9d857889 100644
--- a/test/support/windows-integration/collections/ansible_collections/ansible/windows/plugins/modules/win_uri.py
+++ b/test/support/windows-integration/collections/ansible_collections/ansible/windows/plugins/modules/win_uri.py
@@ -5,7 +5,7 @@
# Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_uri
short_description: Interacts with webservices
@@ -88,9 +88,9 @@ seealso:
author:
- Corwin Brown (@blakfeld)
- Dag Wieers (@dagwieers)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Perform a GET and Store Output
ansible.windows.win_uri:
url: http://example.com/endpoint
@@ -114,9 +114,9 @@ EXAMPLES = r'''
url: http://www.somesite.com/
method: POST
body: "{ 'some': 'json' }"
-'''
+"""
-RETURN = r'''
+RETURN = r"""
elapsed:
description: The number of seconds that elapsed while performing the download.
returned: always
@@ -152,4 +152,4 @@ json:
returned: success and Content-Type is "application/json" or "application/javascript" and return_content is True
type: dict
sample: {"this-is-dependent": "on the actual return content"}
-'''
+"""
diff --git a/test/support/windows-integration/plugins/action/win_copy.py b/test/support/windows-integration/plugins/action/win_copy.py
index f68b2ab670..02702c51fe 100644
--- a/test/support/windows-integration/plugins/action/win_copy.py
+++ b/test/support/windows-integration/plugins/action/win_copy.py
@@ -217,7 +217,7 @@ class ActionModule(ActionBase):
WIN_PATH_SEPARATOR = "\\"
def _create_content_tempfile(self, content):
- ''' Create a tempfile containing defined content '''
+ """ Create a tempfile containing defined content """
fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
@@ -328,7 +328,7 @@ class ActionModule(ActionBase):
return module_return
def run(self, tmp=None, task_vars=None):
- ''' handler for file transfer operations '''
+ """ handler for file transfer operations """
if task_vars is None:
task_vars = dict()
diff --git a/test/support/windows-integration/plugins/modules/win_acl.py b/test/support/windows-integration/plugins/modules/win_acl.py
index 14fbd82f3a..1d5feefce9 100644
--- a/test/support/windows-integration/plugins/modules/win_acl.py
+++ b/test/support/windows-integration/plugins/modules/win_acl.py
@@ -10,7 +10,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_acl
version_added: "2.0"
@@ -82,9 +82,9 @@ author:
- Phil Schwartz (@schwartzmx)
- Trond Hindenes (@trondhindenes)
- Hans-Joachim Kliemeck (@h0nIg)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Restrict write and execute access to User Fed-Phil
win_acl:
user: Fed-Phil
@@ -129,4 +129,4 @@ EXAMPLES = r'''
rights: Read,Write,Modify,FullControl,Delete
type: deny
state: present
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_certificate_store.py b/test/support/windows-integration/plugins/modules/win_certificate_store.py
index dc617e33fd..bfcea7ad40 100644
--- a/test/support/windows-integration/plugins/modules/win_certificate_store.py
+++ b/test/support/windows-integration/plugins/modules/win_certificate_store.py
@@ -8,7 +8,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_certificate_store
version_added: '2.5'
@@ -130,9 +130,9 @@ notes:
binding the certificate to the https endpoint.
author:
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Import a certificate
win_certificate_store:
path: C:\Temp\cert.pem
@@ -196,13 +196,13 @@ EXAMPLES = r'''
store_location: LocalMachine
key_storage: machine
state: present
-'''
+"""
-RETURN = r'''
+RETURN = r"""
thumbprints:
description: A list of certificate thumbprints that were touched by the
module.
returned: success
type: list
sample: ["BC05633694E675449136679A658281F17A191087"]
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_command.py b/test/support/windows-integration/plugins/modules/win_command.py
index 508419b28b..0c9158b1cd 100644
--- a/test/support/windows-integration/plugins/modules/win_command.py
+++ b/test/support/windows-integration/plugins/modules/win_command.py
@@ -8,7 +8,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_command
short_description: Executes a command on a remote Windows node
@@ -68,9 +68,9 @@ seealso:
- module: win_shell
author:
- Matt Davis (@nitzmahone)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Save the result of 'whoami' in 'whoami_out'
win_command: whoami
register: whoami_out
@@ -85,9 +85,9 @@ EXAMPLES = r'''
win_command: powershell.exe -
args:
stdin: Write-Host test
-'''
+"""
-RETURN = r'''
+RETURN = r"""
msg:
description: changed
returned: always
@@ -133,4 +133,4 @@ stdout_lines:
returned: always
type: list
sample: [u'Clustering node rabbit@slave1 with rabbit@master ...']
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_copy.py b/test/support/windows-integration/plugins/modules/win_copy.py
index bb8dbd61f2..f256f9220f 100644
--- a/test/support/windows-integration/plugins/modules/win_copy.py
+++ b/test/support/windows-integration/plugins/modules/win_copy.py
@@ -9,7 +9,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_copy
version_added: '1.9.2'
@@ -109,9 +109,9 @@ seealso:
author:
- Jon Hawkesworth (@jhawkesworth)
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Copy a single file
win_copy:
src: /srv/myfiles/foo.conf
@@ -166,9 +166,9 @@ EXAMPLES = r'''
# This ensures the become user will have permissions for the operation
# Make sure to specify a folder both the ansible_user and the become_user have access to (i.e not %TEMP% which is user specific and requires Admin)
ansible_remote_tmp: 'c:\tmp'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
backup_file:
description: Name of the backup file that was created.
returned: if backup=yes
@@ -204,4 +204,4 @@ original_basename:
returned: changed, src is a file
type: str
sample: foo.txt
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_file.py b/test/support/windows-integration/plugins/modules/win_file.py
index 28149579cd..7821b5a40c 100644
--- a/test/support/windows-integration/plugins/modules/win_file.py
+++ b/test/support/windows-integration/plugins/modules/win_file.py
@@ -8,7 +8,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_file
version_added: "1.9.2"
@@ -45,9 +45,9 @@ seealso:
- module: win_stat
author:
- Jon Hawkesworth (@jhawkesworth)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Touch a file (creates if not present, updates modification time if present)
win_file:
path: C:\Temp\foo.conf
@@ -67,4 +67,4 @@ EXAMPLES = r'''
win_file:
path: C:\Temp
state: absent
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_get_url.py b/test/support/windows-integration/plugins/modules/win_get_url.py
index ef5b5f970b..10de477cef 100644
--- a/test/support/windows-integration/plugins/modules/win_get_url.py
+++ b/test/support/windows-integration/plugins/modules/win_get_url.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_get_url
version_added: "1.7"
@@ -125,9 +125,9 @@ seealso:
author:
- Paul Durivage (@angstwad)
- Takeshi Kuramochi (@tksarah)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Download earthrise.jpg to specified path
win_get_url:
url: http://www.example.com/earthrise.jpg
@@ -169,9 +169,9 @@ EXAMPLES = r'''
checksum: a97e6837f60cec6da4491bab387296bbcd72bdba
checksum_algorithm: sha1
force: True
-'''
+"""
-RETURN = r'''
+RETURN = r"""
dest:
description: destination file/path
returned: always
@@ -212,4 +212,4 @@ status_code:
returned: always
type: int
sample: 200
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_lineinfile.py b/test/support/windows-integration/plugins/modules/win_lineinfile.py
index f4fb7f5afa..9dbc449290 100644
--- a/test/support/windows-integration/plugins/modules/win_lineinfile.py
+++ b/test/support/windows-integration/plugins/modules/win_lineinfile.py
@@ -7,7 +7,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_lineinfile
short_description: Ensure a particular line is in a file, or replace an existing line using a back-referenced regular expression
@@ -107,9 +107,9 @@ seealso:
- module: lineinfile
author:
- Brian Lloyd (@brianlloyd)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Before Ansible 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- name: Insert path without converting \r\n
win_lineinfile:
@@ -162,9 +162,9 @@ EXAMPLES = r'''
backrefs: yes
regex: '(^name=)'
line: '$1JohnDoe'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
backup:
description:
- Name of the backup file that was created.
@@ -177,4 +177,4 @@ backup_file:
returned: if backup=yes
type: str
sample: C:\Path\To\File.txt.11540.20150212-220915.bak
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_ping.py b/test/support/windows-integration/plugins/modules/win_ping.py
index 6d35f37994..8784bc9c07 100644
--- a/test/support/windows-integration/plugins/modules/win_ping.py
+++ b/test/support/windows-integration/plugins/modules/win_ping.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_ping
version_added: "1.7"
@@ -32,9 +32,9 @@ seealso:
- module: ping
author:
- Chris Church (@cchurch)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Test connectivity to a windows host
# ansible winserver -m win_ping
@@ -44,12 +44,12 @@ EXAMPLES = r'''
- name: Induce an exception to see what happens
win_ping:
data: crash
-'''
+"""
-RETURN = r'''
+RETURN = r"""
ping:
description: Value provided with the data parameter.
returned: success
type: str
sample: pong
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_reboot.py b/test/support/windows-integration/plugins/modules/win_reboot.py
index 1431804143..7f1645673e 100644
--- a/test/support/windows-integration/plugins/modules/win_reboot.py
+++ b/test/support/windows-integration/plugins/modules/win_reboot.py
@@ -7,7 +7,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_reboot
short_description: Reboot a windows machine
@@ -79,9 +79,9 @@ seealso:
- module: reboot
author:
- Matt Davis (@nitzmahone)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Reboot the machine with all defaults
win_reboot:
@@ -115,9 +115,9 @@ EXAMPLES = r'''
- name: Validate that the netlogon service has started, before running the next task
win_reboot:
test_command: 'exit (Get-Service -Name Netlogon).Status -ne "Running"'
-'''
+"""
-RETURN = r'''
+RETURN = r"""
rebooted:
description: True if the machine was rebooted.
returned: always
@@ -128,4 +128,4 @@ elapsed:
returned: always
type: float
sample: 23.2
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_regedit.py b/test/support/windows-integration/plugins/modules/win_regedit.py
index 2c0fff7124..ca4c146e4b 100644
--- a/test/support/windows-integration/plugins/modules/win_regedit.py
+++ b/test/support/windows-integration/plugins/modules/win_regedit.py
@@ -13,7 +13,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_regedit
version_added: '2.0'
@@ -99,9 +99,9 @@ author:
- Adam Keech (@smadam813)
- Josh Ludwig (@joshludwig)
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Create registry path MyCompany
win_regedit:
path: HKCU:\Software\MyCompany
@@ -194,9 +194,9 @@ EXAMPLES = r'''
type: str
state: present
hive: C:\Users\Default\NTUSER.dat
-'''
+"""
-RETURN = r'''
+RETURN = r"""
data_changed:
description: Whether this invocation changed the data in the registry value.
returned: success
@@ -207,4 +207,4 @@ data_type_changed:
returned: success
type: bool
sample: true
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_shell.py b/test/support/windows-integration/plugins/modules/win_shell.py
index ee2cd76240..461ccea3ae 100644
--- a/test/support/windows-integration/plugins/modules/win_shell.py
+++ b/test/support/windows-integration/plugins/modules/win_shell.py
@@ -8,7 +8,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_shell
short_description: Execute shell commands on target hosts
@@ -80,9 +80,9 @@ seealso:
- module: win_psexec
author:
- Matt Davis (@nitzmahone)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
# Execute a command in the remote shell; stdout goes to the specified
# file on the remote.
- win_shell: C:\somescript.ps1 >> C:\somelog.txt
@@ -116,9 +116,9 @@ EXAMPLES = r'''
win_shell: '$string = [Console]::In.ReadToEnd(); Write-Output $string.Trim()'
args:
stdin: Input message
-'''
+"""
-RETURN = r'''
+RETURN = r"""
msg:
description: Changed.
returned: always
@@ -164,4 +164,4 @@ stdout_lines:
returned: always
type: list
sample: [u'Clustering node rabbit@slave1 with rabbit@master ...']
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_stat.py b/test/support/windows-integration/plugins/modules/win_stat.py
index 0676b5b235..acc5aaaf3b 100644
--- a/test/support/windows-integration/plugins/modules/win_stat.py
+++ b/test/support/windows-integration/plugins/modules/win_stat.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_stat
version_added: "1.7"
@@ -56,9 +56,9 @@ seealso:
- module: win_owner
author:
- Chris Church (@cchurch)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Obtain information about a file
win_stat:
path: C:\foo.ini
@@ -97,9 +97,9 @@ EXAMPLES = r'''
- debug:
var: sha256_checksum.stat.checksum
-'''
+"""
-RETURN = r'''
+RETURN = r"""
changed:
description: Whether anything was changed
returned: always
@@ -233,4 +233,4 @@ stat:
returned: success, path exists, file is not a link
type: int
sample: 1024
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_user.py b/test/support/windows-integration/plugins/modules/win_user.py
index 5fc0633d06..e7264c6543 100644
--- a/test/support/windows-integration/plugins/modules/win_user.py
+++ b/test/support/windows-integration/plugins/modules/win_user.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_user
version_added: "1.7"
@@ -113,9 +113,9 @@ seealso:
author:
- Paul Durivage (@angstwad)
- Chris Church (@cchurch)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Ensure user bob is present
win_user:
name: bob
@@ -128,9 +128,9 @@ EXAMPLES = r'''
win_user:
name: bob
state: absent
-'''
+"""
-RETURN = r'''
+RETURN = r"""
account_disabled:
description: Whether the user is disabled.
returned: user exists
@@ -191,4 +191,4 @@ user_cannot_change_password:
returned: user exists
type: bool
sample: false
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_user_right.py b/test/support/windows-integration/plugins/modules/win_user_right.py
index 5588208333..a0881d72d2 100644
--- a/test/support/windows-integration/plugins/modules/win_user_right.py
+++ b/test/support/windows-integration/plugins/modules/win_user_right.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_user_right
version_added: '2.4'
@@ -56,9 +56,9 @@ seealso:
- module: win_user
author:
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
---
- name: Replace the entries of Deny log on locally
win_user_right:
@@ -90,9 +90,9 @@ EXAMPLES = r'''
win_user_right:
name: SeDenyRemoteInteractiveLogonRight
users: []
-'''
+"""
-RETURN = r'''
+RETURN = r"""
added:
description: A list of accounts that were added to the right, this is empty
if no accounts were added.
@@ -105,4 +105,4 @@ removed:
returned: success
type: list
sample: ["SERVERNAME\\Administrator", "BUILTIN\\Administrators"]
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_wait_for.py b/test/support/windows-integration/plugins/modules/win_wait_for.py
index 85721e7d53..1a97a3bc47 100644
--- a/test/support/windows-integration/plugins/modules/win_wait_for.py
+++ b/test/support/windows-integration/plugins/modules/win_wait_for.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_wait_for
version_added: '2.4'
@@ -96,9 +96,9 @@ seealso:
- module: win_wait_for_process
author:
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Wait 300 seconds for port 8000 to become open on the host, don't start checking for 10 seconds
win_wait_for:
port: 8000
@@ -137,9 +137,9 @@ EXAMPLES = r'''
port: 1234
state: absent
sleep: 10
-'''
+"""
-RETURN = r'''
+RETURN = r"""
wait_attempts:
description: The number of attempts to poll the file or port before module
finishes.
@@ -152,4 +152,4 @@ elapsed:
returned: always
type: float
sample: 2.1406487
-'''
+"""
diff --git a/test/support/windows-integration/plugins/modules/win_whoami.py b/test/support/windows-integration/plugins/modules/win_whoami.py
index d647374b6c..5059c67bcf 100644
--- a/test/support/windows-integration/plugins/modules/win_whoami.py
+++ b/test/support/windows-integration/plugins/modules/win_whoami.py
@@ -11,7 +11,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
-DOCUMENTATION = r'''
+DOCUMENTATION = r"""
---
module: win_whoami
version_added: "2.5"
@@ -30,14 +30,14 @@ seealso:
- module: win_user_right
author:
- Jordan Borean (@jborean93)
-'''
+"""
-EXAMPLES = r'''
+EXAMPLES = r"""
- name: Get whoami information
win_whoami:
-'''
+"""
-RETURN = r'''
+RETURN = r"""
authentication_package:
description: The name of the authentication package used to authenticate the
user in the session.
@@ -200,4 +200,4 @@ token_type:
returned: success
type: str
sample: TokenPrimary
-'''
+"""
diff --git a/test/units/cli/test_galaxy.py b/test/units/cli/test_galaxy.py
index 9d6d32bb2a..84908b96f2 100644
--- a/test/units/cli/test_galaxy.py
+++ b/test/units/cli/test_galaxy.py
@@ -55,7 +55,7 @@ def reset_cli_args():
class TestGalaxy(unittest.TestCase):
@classmethod
def setUpClass(cls):
- '''creating prerequisites for installing a role; setUpClass occurs ONCE whereas setUp occurs with every method tested.'''
+ """creating prerequisites for installing a role; setUpClass occurs ONCE whereas setUp occurs with every method tested."""
# class data for easy viewing: role_dir, role_tar, role_name, role_req, role_path
cls.temp_dir = tempfile.mkdtemp(prefix='ansible-test_galaxy-')
@@ -84,14 +84,14 @@ class TestGalaxy(unittest.TestCase):
@classmethod
def makeTar(cls, output_file, source_dir):
- ''' used for making a tarfile from a role directory '''
+ """ used for making a tarfile from a role directory """
# adding directory into a tar file
with tarfile.open(output_file, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
@classmethod
def tearDownClass(cls):
- '''After tests are finished removes things created in setUpClass'''
+ """After tests are finished removes things created in setUpClass"""
# deleting the temp role directory
shutil.rmtree(cls.role_dir, ignore_errors=True)
with contextlib.suppress(FileNotFoundError):
@@ -131,7 +131,7 @@ class TestGalaxy(unittest.TestCase):
self.assertNotEqual(display_result.find('\n\tgalaxy_info:'), -1, 'Expected galaxy_info to be indented once')
def test_run(self):
- ''' verifies that the GalaxyCLI object's api is created and that execute() is called. '''
+ """ verifies that the GalaxyCLI object's api is created and that execute() is called. """
gc = GalaxyCLI(args=["ansible-galaxy", "install", "--ignore-errors", "imaginary_role"])
gc.parse()
with patch.object(ansible.cli.CLI, "run", return_value=None) as mock_run:
@@ -161,7 +161,7 @@ class TestGalaxy(unittest.TestCase):
self.assertTrue(removed_role)
def test_exit_without_ignore_without_flag(self):
- ''' tests that GalaxyCLI exits with the error specified if the --ignore-errors flag is not used '''
+ """ tests that GalaxyCLI exits with the error specified if the --ignore-errors flag is not used """
gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name"])
with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
# testing that error expected is raised
@@ -171,7 +171,7 @@ class TestGalaxy(unittest.TestCase):
assert "fake_role_name was NOT installed successfully" in mocked_display.mock_calls[1].args[0]
def test_exit_without_ignore_with_flag(self):
- ''' tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used '''
+ """ tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used """
# testing with --ignore-errors flag
gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors"])
with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display:
@@ -181,23 +181,23 @@ class TestGalaxy(unittest.TestCase):
assert "fake_role_name was NOT installed successfully" in mocked_display.mock_calls[1].args[0]
def test_parse_no_action(self):
- ''' testing the options parser when no action is given '''
+ """ testing the options parser when no action is given """
gc = GalaxyCLI(args=["ansible-galaxy", ""])
self.assertRaises(SystemExit, gc.parse)
def test_parse_invalid_action(self):
- ''' testing the options parser when an invalid action is given '''
+ """ testing the options parser when an invalid action is given """
gc = GalaxyCLI(args=["ansible-galaxy", "NOT_ACTION"])
self.assertRaises(SystemExit, gc.parse)
def test_parse_delete(self):
- ''' testing the options parser when the action 'delete' is given '''
+ """ testing the options parser when the action 'delete' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "delete", "foo", "bar"])
gc.parse()
self.assertEqual(context.CLIARGS['verbosity'], 0)
def test_parse_import(self):
- ''' testing the options parser when the action 'import' is given '''
+ """ testing the options parser when the action 'import' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "import", "foo", "bar"])
gc.parse()
assert context.CLIARGS['wait']
@@ -206,20 +206,20 @@ class TestGalaxy(unittest.TestCase):
assert context.CLIARGS['verbosity'] == 0
def test_parse_info(self):
- ''' testing the options parser when the action 'info' is given '''
+ """ testing the options parser when the action 'info' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "info", "foo", "bar"])
gc.parse()
assert not context.CLIARGS['offline']
def test_parse_init(self):
- ''' testing the options parser when the action 'init' is given '''
+ """ testing the options parser when the action 'init' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "init", "foo"])
gc.parse()
assert not context.CLIARGS['offline']
assert not context.CLIARGS['force']
def test_parse_install(self):
- ''' testing the options parser when the action 'install' is given '''
+ """ testing the options parser when the action 'install' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "install"])
gc.parse()
assert not context.CLIARGS['ignore_errors']
@@ -228,19 +228,19 @@ class TestGalaxy(unittest.TestCase):
assert not context.CLIARGS['force']
def test_parse_list(self):
- ''' testing the options parser when the action 'list' is given '''
+ """ testing the options parser when the action 'list' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "list"])
gc.parse()
self.assertEqual(context.CLIARGS['verbosity'], 0)
def test_parse_remove(self):
- ''' testing the options parser when the action 'remove' is given '''
+ """ testing the options parser when the action 'remove' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "remove", "foo"])
gc.parse()
self.assertEqual(context.CLIARGS['verbosity'], 0)
def test_parse_search(self):
- ''' testing the options parswer when the action 'search' is given '''
+ """ testing the options parswer when the action 'search' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "search"])
gc.parse()
assert context.CLIARGS['platforms'] is None
@@ -248,7 +248,7 @@ class TestGalaxy(unittest.TestCase):
assert context.CLIARGS['author'] is None
def test_parse_setup(self):
- ''' testing the options parser when the action 'setup' is given '''
+ """ testing the options parser when the action 'setup' is given """
gc = GalaxyCLI(args=["ansible-galaxy", "setup", "source", "github_user", "github_repo", "secret"])
gc.parse()
assert context.CLIARGS['verbosity'] == 0
@@ -568,7 +568,7 @@ def test_collection_skeleton(collection_skeleton):
@pytest.fixture()
def collection_artifact(collection_skeleton, tmp_path_factory):
- ''' Creates a collection artifact tarball that is ready to be published and installed '''
+ """ Creates a collection artifact tarball that is ready to be published and installed """
output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Output'))
# Create a file with +x in the collection so we can test the permissions
@@ -792,12 +792,12 @@ def test_collection_install_with_requirements_file(collection_install):
requirements_file = os.path.join(output_dir, 'requirements.yml')
with open(requirements_file, 'wb') as req_obj:
- req_obj.write(b'''---
+ req_obj.write(b"""---
collections:
- namespace.coll
- name: namespace2.coll
version: '>2.0.1'
-''')
+""")
galaxy_args = ['ansible-galaxy', 'collection', 'install', '--requirements-file', requirements_file,
'--collections-path', output_dir]
@@ -1085,11 +1085,11 @@ def test_parse_requirements_file_that_isnt_yaml(requirements_cli, requirements_f
requirements_cli._parse_requirements_file(requirements_file)
-@pytest.mark.parametrize('requirements_file', [('''
+@pytest.mark.parametrize('requirements_file', [("""
# Older role based requirements.yml
- galaxy.role
- anotherrole
-''')], indirect=True)
+""")], indirect=True)
def test_parse_requirements_in_older_format_illegal(requirements_cli, requirements_file):
expected = "Expecting requirements file to be a dict with the key 'collections' that contains a list of " \
"collections to install"
@@ -1098,10 +1098,10 @@ def test_parse_requirements_in_older_format_illegal(requirements_cli, requiremen
requirements_cli._parse_requirements_file(requirements_file, allow_old_format=False)
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- version: 1.0.0
-'''], indirect=True)
+"""], indirect=True)
def test_parse_requirements_without_mandatory_name_key(requirements_cli, requirements_file):
# Used to be "Collections requirement entry should contain the key name."
# Should we check that either source or name is provided before using the dep resolver?
@@ -1114,15 +1114,15 @@ def test_parse_requirements_without_mandatory_name_key(requirements_cli, require
requirements_cli._parse_requirements_file(requirements_file)
-@pytest.mark.parametrize('requirements_file', [('''
+@pytest.mark.parametrize('requirements_file', [("""
collections:
- namespace.collection1
- namespace.collection2
-'''), ('''
+"""), ("""
collections:
- name: namespace.collection1
- name: namespace.collection2
-''')], indirect=True)
+""")], indirect=True)
def test_parse_requirements(requirements_cli, requirements_file):
expected = {
'roles': [],
@@ -1134,12 +1134,12 @@ def test_parse_requirements(requirements_cli, requirements_file):
assert actual == expected
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- name: namespace.collection1
version: ">=1.0.0,<=2.0.0"
source: https://galaxy-dev.ansible.com
-- namespace.collection2'''], indirect=True)
+- namespace.collection2"""], indirect=True)
def test_parse_requirements_with_extra_info(requirements_cli, requirements_file):
actual = requirements_cli._parse_requirements_file(requirements_file)
actual['collections'] = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in actual.get('collections', [])]
@@ -1153,7 +1153,7 @@ def test_parse_requirements_with_extra_info(requirements_cli, requirements_file)
assert actual['collections'][1] == ('namespace.collection2', '*', None, 'galaxy')
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
roles:
- username.role_name
- src: username2.role_name2
@@ -1162,7 +1162,7 @@ roles:
collections:
- namespace.collection2
-'''], indirect=True)
+"""], indirect=True)
def test_parse_requirements_with_roles_and_collections(requirements_cli, requirements_file):
actual = requirements_cli._parse_requirements_file(requirements_file)
actual['collections'] = [('%s.%s' % (r.namespace, r.name), r.ver, r.src, r.type,) for r in actual.get('collections', [])]
@@ -1177,14 +1177,14 @@ def test_parse_requirements_with_roles_and_collections(requirements_cli, require
assert actual['collections'][0] == ('namespace.collection2', '*', None, 'galaxy')
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- name: namespace.collection
- name: namespace2.collection2
source: https://galaxy-dev.ansible.com/
- name: namespace3.collection3
source: server
-'''], indirect=True)
+"""], indirect=True)
def test_parse_requirements_with_collection_source(requirements_cli, requirements_file):
galaxy_api = GalaxyAPI(requirements_cli.api, 'server', 'https://config-server')
requirements_cli.api_servers.append(galaxy_api)
@@ -1205,10 +1205,10 @@ def test_parse_requirements_with_collection_source(requirements_cli, requirement
assert actual['collections'][2][2].api_server == 'https://config-server'
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
- username.included_role
- src: https://github.com/user/repo
-'''], indirect=True)
+"""], indirect=True)
def test_parse_requirements_roles_with_include(requirements_cli, requirements_file):
reqs = [
'ansible.role',
@@ -1228,10 +1228,10 @@ def test_parse_requirements_roles_with_include(requirements_cli, requirements_fi
assert actual['roles'][2].src == 'https://github.com/user/repo'
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
- username.role
- include: missing.yml
-'''], indirect=True)
+"""], indirect=True)
def test_parse_requirements_roles_with_include_missing(requirements_cli, requirements_file):
expected = "Failed to find include requirements file 'missing.yml' in '%s'" % to_native(requirements_file)
@@ -1239,12 +1239,12 @@ def test_parse_requirements_roles_with_include_missing(requirements_cli, require
requirements_cli._parse_requirements_file(requirements_file)
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- namespace.name
roles:
- namespace.name
-'''], indirect=True)
+"""], indirect=True)
def test_install_implicit_role_with_collections(requirements_file, monkeypatch):
mock_collection_install = MagicMock()
monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
@@ -1269,12 +1269,12 @@ def test_install_implicit_role_with_collections(requirements_file, monkeypatch):
assert not any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- namespace.name
roles:
- namespace.name
-'''], indirect=True)
+"""], indirect=True)
def test_install_explicit_role_with_collections(requirements_file, monkeypatch):
mock_collection_install = MagicMock()
monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
@@ -1296,12 +1296,12 @@ def test_install_explicit_role_with_collections(requirements_file, monkeypatch):
assert any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- namespace.name
roles:
- namespace.name
-'''], indirect=True)
+"""], indirect=True)
def test_install_role_with_collections_and_path(requirements_file, monkeypatch):
mock_collection_install = MagicMock()
monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
@@ -1323,12 +1323,12 @@ def test_install_role_with_collections_and_path(requirements_file, monkeypatch):
assert any(list('contains collections which will be ignored' in mock_call[1][0] for mock_call in mock_display.mock_calls))
-@pytest.mark.parametrize('requirements_file', ['''
+@pytest.mark.parametrize('requirements_file', ["""
collections:
- namespace.name
roles:
- namespace.name
-'''], indirect=True)
+"""], indirect=True)
def test_install_collection_with_roles(requirements_file, monkeypatch):
mock_collection_install = MagicMock()
monkeypatch.setattr(GalaxyCLI, '_execute_install_collection', mock_collection_install)
diff --git a/test/units/errors/test_errors.py b/test/units/errors/test_errors.py
index 94c905bcf7..9285f983bc 100644
--- a/test/units/errors/test_errors.py
+++ b/test/units/errors/test_errors.py
@@ -44,7 +44,7 @@ class TestErrors(unittest.TestCase):
@patch.object(AnsibleError, '_get_error_lines_from_file')
def test_error_with_kv(self, mock_method):
- ''' This tests a task with both YAML and k=v syntax
+ """ This tests a task with both YAML and k=v syntax
- lineinfile: line=foo path=bar
line: foo
@@ -52,7 +52,7 @@ class TestErrors(unittest.TestCase):
An accurate error message and position indicator are expected.
_get_error_lines_from_file() returns (target_line, prev_line)
- '''
+ """
self.obj.ansible_pos = ('foo.yml', 2, 1)
diff --git a/test/units/executor/module_common/test_modify_module.py b/test/units/executor/module_common/test_modify_module.py
index 0ea191826e..969246e5b1 100644
--- a/test/units/executor/module_common/test_modify_module.py
+++ b/test/units/executor/module_common/test_modify_module.py
@@ -9,10 +9,10 @@ import pytest
from ansible.executor.module_common import modify_module
-FAKE_OLD_MODULE = b'''#!/usr/bin/python
+FAKE_OLD_MODULE = b"""#!/usr/bin/python
import sys
print('{"result": "%s"}' % sys.executable)
-'''
+"""
@pytest.fixture
diff --git a/test/units/executor/test_playbook_executor.py b/test/units/executor/test_playbook_executor.py
index 62fa1a36e1..085d7fbf30 100644
--- a/test/units/executor/test_playbook_executor.py
+++ b/test/units/executor/test_playbook_executor.py
@@ -40,40 +40,40 @@ class TestPlaybookExecutor(unittest.TestCase):
def test_get_serialized_batches(self):
fake_loader = DictDataLoader({
- 'no_serial.yml': '''
+ 'no_serial.yml': """
- hosts: all
gather_facts: no
tasks:
- debug: var=inventory_hostname
- ''',
- 'serial_int.yml': '''
+ """,
+ 'serial_int.yml': """
- hosts: all
gather_facts: no
serial: 2
tasks:
- debug: var=inventory_hostname
- ''',
- 'serial_pct.yml': '''
+ """,
+ 'serial_pct.yml': """
- hosts: all
gather_facts: no
serial: 20%
tasks:
- debug: var=inventory_hostname
- ''',
- 'serial_list.yml': '''
+ """,
+ 'serial_list.yml': """
- hosts: all
gather_facts: no
serial: [1, 2, 3]
tasks:
- debug: var=inventory_hostname
- ''',
- 'serial_list_mixed.yml': '''
+ """,
+ 'serial_list_mixed.yml': """
- hosts: all
gather_facts: no
serial: [1, "20%", -1]
tasks:
- debug: var=inventory_hostname
- ''',
+ """,
})
mock_inventory = MagicMock()
diff --git a/test/units/galaxy/test_api.py b/test/units/galaxy/test_api.py
index 2ef1d07325..22d83e43b3 100644
--- a/test/units/galaxy/test_api.py
+++ b/test/units/galaxy/test_api.py
@@ -40,7 +40,7 @@ def reset_cli_args():
@pytest.fixture()
def collection_artifact(tmp_path_factory):
- ''' Creates a collection artifact tarball that is ready to be published '''
+ """ Creates a collection artifact tarball that is ready to be published """
output_dir = to_text(tmp_path_factory.mktemp('test-ÅÑŚÌβŁÈ Output'))
tar_path = os.path.join(output_dir, 'namespace-collection-v1.0.0.tar.gz')
diff --git a/test/units/galaxy/test_collection.py b/test/units/galaxy/test_collection.py
index 73e915dee6..0c00c1884b 100644
--- a/test/units/galaxy/test_collection.py
+++ b/test/units/galaxy/test_collection.py
@@ -64,7 +64,7 @@ def collection_input(tmp_path_factory, collection_path_suffix):
@pytest.fixture()
def collection_artifact(monkeypatch, tmp_path_factory):
- ''' Creates a temp collection artifact and mocked open_url instance for publishing tests '''
+ """ Creates a temp collection artifact and mocked open_url instance for publishing tests """
mock_open = MagicMock()
monkeypatch.setattr(collection.concrete_artifact_manager, 'open_url', mock_open)
@@ -97,7 +97,7 @@ def galaxy_yml_dir(request, tmp_path_factory):
@pytest.fixture()
def tmp_tarfile(tmp_path_factory, manifest_info):
- ''' Creates a temporary tar file for _extract_tar_file tests '''
+ """ Creates a temporary tar file for _extract_tar_file tests """
filename = u'ÅÑŚÌβŁÈ'
temp_dir = to_bytes(tmp_path_factory.mktemp('test-%s Collections' % to_native(filename)))
tar_file = os.path.join(temp_dir, to_bytes('%s.tar.gz' % filename))
diff --git a/test/units/inventory/test_group.py b/test/units/inventory/test_group.py
index 5a9d540d90..4d735a5bb5 100644
--- a/test/units/inventory/test_group.py
+++ b/test/units/inventory/test_group.py
@@ -142,10 +142,10 @@ class TestGroup(unittest.TestCase):
)
def test_ancestors_recursive_loop_safe(self):
- '''
+ """
The get_ancestors method may be referenced before circular parenting
checks, so the method is expected to be stable even with loops
- '''
+ """
A = Group('A')
B = Group('B')
A.parent_groups.append(B)
diff --git a/test/units/mock/vault_helper.py b/test/units/mock/vault_helper.py
index 1b40e381a1..c145413727 100644
--- a/test/units/mock/vault_helper.py
+++ b/test/units/mock/vault_helper.py
@@ -19,10 +19,10 @@ from ansible.parsing.vault import VaultSecret
class TextVaultSecret(VaultSecret):
- '''A secret piece of text. ie, a password. Tracks text encoding.
+ """A secret piece of text. ie, a password. Tracks text encoding.
The text encoding of the text may not be the default text encoding so
- we keep track of the encoding so we encode it to the same bytes.'''
+ we keep track of the encoding so we encode it to the same bytes."""
def __init__(self, text, encoding=None, errors=None, _bytes=None):
super(TextVaultSecret, self).__init__()
@@ -33,5 +33,5 @@ class TextVaultSecret(VaultSecret):
@property
def bytes(self):
- '''The text encoded with encoding, unless we specifically set _bytes.'''
+ """The text encoded with encoding, unless we specifically set _bytes."""
return self._bytes or to_bytes(self.text, encoding=self.encoding, errors=self.errors)
diff --git a/test/units/module_utils/basic/test_set_cwd.py b/test/units/module_utils/basic/test_set_cwd.py
index b060b50b1f..c32c777080 100644
--- a/test/units/module_utils/basic/test_set_cwd.py
+++ b/test/units/module_utils/basic/test_set_cwd.py
@@ -18,7 +18,7 @@ class TestAnsibleModuleSetCwd:
def test_set_cwd(self, monkeypatch):
- '''make sure /tmp is used'''
+ """make sure /tmp is used"""
def mock_getcwd():
return '/tmp'
@@ -40,7 +40,7 @@ class TestAnsibleModuleSetCwd:
def test_set_cwd_unreadable_use_self_tmpdir(self, monkeypatch):
- '''pwd is not readable, use instance's tmpdir property'''
+ """pwd is not readable, use instance's tmpdir property"""
def mock_getcwd():
return '/tmp'
@@ -77,7 +77,7 @@ class TestAnsibleModuleSetCwd:
def test_set_cwd_unreadable_use_home(self, monkeypatch):
- '''cwd and instance tmpdir are unreadable, use home'''
+ """cwd and instance tmpdir are unreadable, use home"""
def mock_getcwd():
return '/tmp'
@@ -114,7 +114,7 @@ class TestAnsibleModuleSetCwd:
def test_set_cwd_unreadable_use_gettempdir(self, monkeypatch):
- '''fallback to tempfile.gettempdir'''
+ """fallback to tempfile.gettempdir"""
thisdir = None
@@ -154,7 +154,7 @@ class TestAnsibleModuleSetCwd:
def test_set_cwd_unreadable_use_None(self, monkeypatch):
- '''all paths are unreable, should return None and not an exception'''
+ """all paths are unreable, should return None and not an exception"""
def mock_getcwd():
return '/tmp'
diff --git a/test/units/module_utils/common/test_dict_transformations.py b/test/units/module_utils/common/test_dict_transformations.py
index 7e7c0d3d5c..e1bf1e4f23 100644
--- a/test/units/module_utils/common/test_dict_transformations.py
+++ b/test/units/module_utils/common/test_dict_transformations.py
@@ -115,12 +115,12 @@ class TestCaseDictMerge:
class TestCaseAzureIncidental:
def test_dict_merge_invalid_dict(self):
- ''' if b is not a dict, return b '''
+ """ if b is not a dict, return b """
res = dict_merge({}, None)
assert res is None
def test_merge_sub_dicts(self):
- '''merge sub dicts '''
+ """merge sub dicts """
a = {'a': {'a1': 1}}
b = {'a': {'b1': 2}}
c = {'a': {'a1': 1, 'b1': 2}}
diff --git a/test/units/module_utils/common/validation/test_check_type_float.py b/test/units/module_utils/common/validation/test_check_type_float.py
index d7e12e1445..7d36903caa 100644
--- a/test/units/module_utils/common/validation/test_check_type_float.py
+++ b/test/units/module_utils/common/validation/test_check_type_float.py
@@ -13,7 +13,7 @@ from ansible.module_utils.common.validation import check_type_float
def test_check_type_float():
test_cases = (
('1.5', 1.5),
- ('''1.5''', 1.5),
+ ("""1.5""", 1.5),
(u'1.5', 1.5),
(1002, 1002.0),
(1.0, 1.0),
diff --git a/test/units/module_utils/facts/network/test_generic_bsd.py b/test/units/module_utils/facts/network/test_generic_bsd.py
index 3b26f0a0e1..66810cbe58 100644
--- a/test/units/module_utils/facts/network/test_generic_bsd.py
+++ b/test/units/module_utils/facts/network/test_generic_bsd.py
@@ -17,7 +17,7 @@ def mock_get_bin_path(command):
return cmds.get(command, None)
-NETBSD_IFCONFIG_A_OUT_7_1 = r'''
+NETBSD_IFCONFIG_A_OUT_7_1 = r"""
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 33624
inet 127.0.0.1 netmask 0xff000000
inet6 ::1 prefixlen 128
@@ -33,9 +33,9 @@ re0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
status: active
inet 192.168.122.205 netmask 0xffffff00 broadcast 192.168.122.255
inet6 fe80::5054:ff:fe63:55af%re0 prefixlen 64 scopeid 0x2
-'''
+"""
-NETBSD_IFCONFIG_A_OUT_POST_7_1 = r'''
+NETBSD_IFCONFIG_A_OUT_POST_7_1 = r"""
lo0: flags=0x8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 33624
inet 127.0.0.1/8 flags 0x0
inet6 ::1/128 flags 0x20<NODAD>
@@ -51,7 +51,7 @@ re0: flags=0x8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
status: active
inet 192.168.122.205/24 broadcast 192.168.122.255 flags 0x0
inet6 fe80::5054:ff:fe63:55af%re0/64 flags 0x0 scopeid 0x2
-'''
+"""
NETBSD_EXPECTED = {'all_ipv4_addresses': ['192.168.122.205'],
'all_ipv6_addresses': ['fe80::5054:ff:fe63:55af%re0'],
diff --git a/test/units/module_utils/facts/other/test_facter.py b/test/units/module_utils/facts/other/test_facter.py
index 62ff5196cc..69cce6a832 100644
--- a/test/units/module_utils/facts/other/test_facter.py
+++ b/test/units/module_utils/facts/other/test_facter.py
@@ -23,7 +23,7 @@ from .. base import BaseFactsTest
from ansible.module_utils.facts.other.facter import FacterFactCollector
-facter_json_output = '''
+facter_json_output = """
{
"operatingsystemmajrelease": "25",
"hardwareisa": "x86_64",
@@ -177,7 +177,7 @@ facter_json_output = '''
"uptime_hours": 432,
"kernelversion": "4.9.14"
}
-'''
+"""
class TestFacterCollector(BaseFactsTest):
diff --git a/test/units/module_utils/facts/other/test_ohai.py b/test/units/module_utils/facts/other/test_ohai.py
index f5084c5d45..d2bac55361 100644
--- a/test/units/module_utils/facts/other/test_ohai.py
+++ b/test/units/module_utils/facts/other/test_ohai.py
@@ -23,7 +23,7 @@ from .. base import BaseFactsTest
from ansible.module_utils.facts.other.ohai import OhaiFactCollector
-ohai_json_output = r'''
+ohai_json_output = r"""
{
"kernel": {
"name": "Linux",
@@ -6717,7 +6717,7 @@ ohai_json_output = r'''
"cloud_v2": null,
"cloud": null
}
-''' # noqa
+""" # noqa
class TestOhaiCollector(BaseFactsTest):
diff --git a/test/units/module_utils/facts/system/test_lsb.py b/test/units/module_utils/facts/system/test_lsb.py
index 385a754079..01da02cc66 100644
--- a/test/units/module_utils/facts/system/test_lsb.py
+++ b/test/units/module_utils/facts/system/test_lsb.py
@@ -24,25 +24,25 @@ from .. base import BaseFactsTest
from ansible.module_utils.facts.system.lsb import LSBFactCollector
-lsb_release_a_fedora_output = '''
+lsb_release_a_fedora_output = """
LSB Version: :core-4.1-amd64:core-4.1-noarch:cxx-4.1-amd64:cxx-4.1-noarch:desktop-4.1-amd64:desktop-4.1-noarch:languages-4.1-amd64:languages-4.1-noarch:printing-4.1-amd64:printing-4.1-noarch
Distributor ID: Fedora
Description: Fedora release 25 (Twenty Five)
Release: 25
Codename: TwentyFive
-''' # noqa
+""" # noqa
# FIXME: a
-etc_lsb_release_ubuntu14 = '''DISTRIB_ID=Ubuntu
+etc_lsb_release_ubuntu14 = """DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=trusty
DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS"
-'''
-etc_lsb_release_no_decimal = '''DISTRIB_ID=AwesomeOS
+"""
+etc_lsb_release_no_decimal = """DISTRIB_ID=AwesomeOS
DISTRIB_RELEASE=11
DISTRIB_CODENAME=stonehenge
DISTRIB_DESCRIPTION="AwesomeÖS 11"
-'''
+"""
class TestLSBFacts(BaseFactsTest):
diff --git a/test/units/module_utils/urls/test_gzip.py b/test/units/module_utils/urls/test_gzip.py
index 8d850f2dbe..fb6b9b3481 100644
--- a/test/units/module_utils/urls/test_gzip.py
+++ b/test/units/module_utils/urls/test_gzip.py
@@ -37,22 +37,22 @@ def urlopen_mock(mocker):
JSON_DATA = b'{"foo": "bar", "baz": "qux", "sandwich": "ham", "tech_level": "pickle", "pop": "corn", "ansible": "awesome"}'
-RESP = b'''HTTP/1.1 200 OK
+RESP = b"""HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Set-Cookie: foo
Set-Cookie: bar
Content-Length: 108
-%s''' % JSON_DATA
+%s""" % JSON_DATA
-GZIP_RESP = b'''HTTP/1.1 200 OK
+GZIP_RESP = b"""HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Set-Cookie: foo
Set-Cookie: bar
Content-Encoding: gzip
Content-Length: 100
-%s''' % compress(JSON_DATA)
+%s""" % compress(JSON_DATA)
def test_Request_open_gzip(urlopen_mock):
diff --git a/test/units/parsing/test_dataloader.py b/test/units/parsing/test_dataloader.py
index 05040c3bfa..c6e0f5f5f3 100644
--- a/test/units/parsing/test_dataloader.py
+++ b/test/units/parsing/test_dataloader.py
@@ -71,7 +71,7 @@ class TestDataLoader(unittest.TestCase):
@patch.object(DataLoader, '_get_file_contents')
def test_tab_error(self, mock_def, mock_get_error_lines):
mock_def.return_value = (u"""---\nhosts: localhost\nvars:\n foo: bar\n\tblip: baz""", True)
- mock_get_error_lines.return_value = ('''\tblip: baz''', '''..foo: bar''')
+ mock_get_error_lines.return_value = ("""\tblip: baz""", """..foo: bar""")
with self.assertRaises(AnsibleParserError) as cm:
self._loader.load_from_file('dummy_yaml_text.txt')
self.assertIn(yaml_strings.YAML_COMMON_LEADING_TAB_ERROR, str(cm.exception))
diff --git a/test/units/parsing/vault/test_vault.py b/test/units/parsing/vault/test_vault.py
index 3b84b475f4..3262cac9a9 100644
--- a/test/units/parsing/vault/test_vault.py
+++ b/test/units/parsing/vault/test_vault.py
@@ -63,12 +63,12 @@ class TestUnhexlify(unittest.TestCase):
class TestParseVaulttext(unittest.TestCase):
def test(self):
- vaulttext_envelope = u'''$ANSIBLE_VAULT;1.1;AES256
+ vaulttext_envelope = u"""$ANSIBLE_VAULT;1.1;AES256
33363965326261303234626463623963633531343539616138316433353830356566396130353436
3562643163366231316662386565383735653432386435610a306664636137376132643732393835
63383038383730306639353234326630666539346233376330303938323639306661313032396437
6233623062366136310a633866373936313238333730653739323461656662303864663666653563
-3138'''
+3138"""
b_vaulttext_envelope = to_bytes(vaulttext_envelope, errors='strict', encoding='utf-8')
b_vaulttext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext_envelope)
@@ -78,12 +78,12 @@ class TestParseVaulttext(unittest.TestCase):
self.assertIsInstance(res[2], bytes)
def test_non_hex(self):
- vaulttext_envelope = u'''$ANSIBLE_VAULT;1.1;AES256
+ vaulttext_envelope = u"""$ANSIBLE_VAULT;1.1;AES256
3336396J326261303234626463623963633531343539616138316433353830356566396130353436
3562643163366231316662386565383735653432386435610a306664636137376132643732393835
63383038383730306639353234326630666539346233376330303938323639306661313032396437
6233623062366136310a633866373936313238333730653739323461656662303864663666653563
-3138'''
+3138"""
b_vaulttext_envelope = to_bytes(vaulttext_envelope, errors='strict', encoding='utf-8')
b_vaulttext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext_envelope)
@@ -210,13 +210,13 @@ class TestFileVaultSecret(unittest.TestCase):
password = 'some password'
# 'some password' encrypted with 'test-ansible-password'
- password_file_content = '''$ANSIBLE_VAULT;1.1;AES256
+ password_file_content = """$ANSIBLE_VAULT;1.1;AES256
61393863643638653437313566313632306462383837303132346434616433313438353634613762
3334363431623364386164616163326537366333353663650a663634306232363432626162353665
39623061353266373631636331643761306665343731376633623439313138396330346237653930
6432643864346136640a653364386634666461306231353765636662316335613235383565306437
3737
-'''
+"""
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(to_bytes(password_file_content))
@@ -758,12 +758,12 @@ class TestVaultLib(unittest.TestCase):
def test_encrypt_decrypt_aes256_existing_vault(self):
self.v.cipher_name = u'AES256'
b_orig_plaintext = b"Setec Astronomy"
- vaulttext = u'''$ANSIBLE_VAULT;1.1;AES256
+ vaulttext = u"""$ANSIBLE_VAULT;1.1;AES256
33363965326261303234626463623963633531343539616138316433353830356566396130353436
3562643163366231316662386565383735653432386435610a306664636137376132643732393835
63383038383730306639353234326630666539346233376330303938323639306661313032396437
6233623062366136310a633866373936313238333730653739323461656662303864663666653563
-3138'''
+3138"""
b_plaintext = self.v.decrypt(vaulttext)
self.assertEqual(b_plaintext, b_plaintext, msg="decryption failed")
@@ -774,12 +774,12 @@ class TestVaultLib(unittest.TestCase):
def test_decrypt_and_get_vault_id(self):
b_expected_plaintext = to_bytes('foo bar\n')
- vaulttext = '''$ANSIBLE_VAULT;1.2;AES256;ansible_devel
+ vaulttext = """$ANSIBLE_VAULT;1.2;AES256;ansible_devel
65616435333934613466373335363332373764363365633035303466643439313864663837393234
3330656363343637313962633731333237313636633534630a386264363438363362326132363239
39363166646664346264383934393935653933316263333838386362633534326664646166663736
6462303664383765650a356637643633366663643566353036303162386237336233393065393164
-6264'''
+6264"""
vault_secrets = self._vault_secrets_from_password('ansible_devel', 'ansible')
v = vault.VaultLib(vault_secrets)
@@ -794,12 +794,12 @@ class TestVaultLib(unittest.TestCase):
def test_decrypt_non_default_1_2(self):
b_expected_plaintext = to_bytes('foo bar\n')
- vaulttext = '''$ANSIBLE_VAULT;1.2;AES256;ansible_devel
+ vaulttext = """$ANSIBLE_VAULT;1.2;AES256;ansible_devel
65616435333934613466373335363332373764363365633035303466643439313864663837393234
3330656363343637313962633731333237313636633534630a386264363438363362326132363239
39363166646664346264383934393935653933316263333838386362633534326664646166663736
6462303664383765650a356637643633366663643566353036303162386237336233393065393164
-6264'''
+6264"""
vault_secrets = self._vault_secrets_from_password('default', 'ansible')
v = vault.VaultLib(vault_secrets)
diff --git a/test/units/plugins/action/test_action.py b/test/units/plugins/action/test_action.py
index 7d9c2915dd..a525a88df9 100644
--- a/test/units/plugins/action/test_action.py
+++ b/test/units/plugins/action/test_action.py
@@ -359,9 +359,9 @@ class TestActionBase(unittest.TestCase):
execute=execute)
def get_shell_option_for_arg(args_kv, default):
- '''A helper for get_shell_option. Returns a function that, if
+ """A helper for get_shell_option. Returns a function that, if
called with ``option`` that exists in args_kv, will return the
- value, else will return ``default`` for every other given arg'''
+ value, else will return ``default`` for every other given arg"""
def _helper(option, *args, **kwargs):
return args_kv.get(option, default)
return _helper
@@ -855,10 +855,10 @@ class TestActionBaseParseReturnedData(unittest.TestCase):
def test_json_facts_add_host(self):
action_base = _action_base()
rc = 0
- stdout = '''{"ansible_facts": {"foo": "bar", "ansible_blip": "blip_value"},
+ stdout = """{"ansible_facts": {"foo": "bar", "ansible_blip": "blip_value"},
"add_host": {"host_vars": {"some_key": ["whatever the add_host object is"]}
}
- }\n'''
+ }\n"""
err = ''
returned_data = {'rc': rc,
diff --git a/test/units/plugins/callback/test_callback.py b/test/units/plugins/callback/test_callback.py
index dd83820e1b..f134cf6e46 100644
--- a/test/units/plugins/callback/test_callback.py
+++ b/test/units/plugins/callback/test_callback.py
@@ -230,7 +230,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': 'one\ntwo\nthree\n',
'after': 'one\nthree\nfour\n',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before: somefile.txt
+++ after: generated from template somefile.j2
@@ -1,3 +1,3 @@
@@ -239,7 +239,7 @@ class TestCallbackDiff(unittest.TestCase):
three
+four
- '''))
+ """))
def test_new_file(self):
self.assertMultiLineEqual(
@@ -249,7 +249,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': '',
'after': 'one\ntwo\nthree\n',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before: somefile.txt
+++ after: generated from template somefile.j2
@@ -0,0 +1,3 @@
@@ -257,7 +257,7 @@ class TestCallbackDiff(unittest.TestCase):
+two
+three
- '''))
+ """))
def test_clear_file(self):
self.assertMultiLineEqual(
@@ -267,7 +267,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': 'one\ntwo\nthree\n',
'after': '',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before: somefile.txt
+++ after: generated from template somefile.j2
@@ -1,3 +0,0 @@
@@ -275,7 +275,7 @@ class TestCallbackDiff(unittest.TestCase):
-two
-three
- '''))
+ """))
def test_no_trailing_newline_before(self):
self.assertMultiLineEqual(
@@ -285,7 +285,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': 'one\ntwo\nthree',
'after': 'one\ntwo\nthree\n',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before: somefile.txt
+++ after: generated from template somefile.j2
@@ -1,3 +1,3 @@
@@ -295,7 +295,7 @@ class TestCallbackDiff(unittest.TestCase):
\\ No newline at end of file
+three
- '''))
+ """))
def test_no_trailing_newline_after(self):
self.assertMultiLineEqual(
@@ -305,7 +305,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': 'one\ntwo\nthree\n',
'after': 'one\ntwo\nthree',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before: somefile.txt
+++ after: generated from template somefile.j2
@@ -1,3 +1,3 @@
@@ -315,7 +315,7 @@ class TestCallbackDiff(unittest.TestCase):
+three
\\ No newline at end of file
- '''))
+ """))
def test_no_trailing_newline_both(self):
self.assertMultiLineEqual(
@@ -335,7 +335,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': 'one\ntwo\nthree',
'after': 'one\nfive\nthree',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before: somefile.txt
+++ after: generated from template somefile.j2
@@ -1,3 +1,3 @@
@@ -345,7 +345,7 @@ class TestCallbackDiff(unittest.TestCase):
three
\\ No newline at end of file
- '''))
+ """))
def test_diff_dicts(self):
self.assertMultiLineEqual(
@@ -353,7 +353,7 @@ class TestCallbackDiff(unittest.TestCase):
'before': dict(one=1, two=2, three=3),
'after': dict(one=1, three=3, four=4),
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before
+++ after
@@ -1,5 +1,5 @@
@@ -365,7 +365,7 @@ class TestCallbackDiff(unittest.TestCase):
+ "three": 3
}
- '''))
+ """))
def test_diff_before_none(self):
self.assertMultiLineEqual(
@@ -373,13 +373,13 @@ class TestCallbackDiff(unittest.TestCase):
'before': None,
'after': 'one line\n',
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before
+++ after
@@ -0,0 +1 @@
+one line
- '''))
+ """))
def test_diff_after_none(self):
self.assertMultiLineEqual(
@@ -387,13 +387,13 @@ class TestCallbackDiff(unittest.TestCase):
'before': 'one line\n',
'after': None,
})),
- textwrap.dedent('''\
+ textwrap.dedent("""\
--- before
+++ after
@@ -1 +0,0 @@
-one line
- '''))
+ """))
class TestCallbackOnMethods(unittest.TestCase):
diff --git a/test/units/plugins/connection/test_connection.py b/test/units/plugins/connection/test_connection.py
index da140ea24e..8f1bd306eb 100644
--- a/test/units/plugins/connection/test_connection.py
+++ b/test/units/plugins/connection/test_connection.py
@@ -74,7 +74,7 @@ class TestConnectionBaseClass(unittest.TestCase):
b'BECOME-SUCCESS-ouzmdnewuhucvuaabtjmweasarviygqq\n'
)
- ssh_pipelining_vvvv = b'''
+ ssh_pipelining_vvvv = b"""
debug3: mux_master_read_cb: channel 1 packet type 0x10000002 len 251
debug2: process_mux_new_session: channel 1: request tty 0, X 1, agent 1, subsys 0, term "xterm-256color", cmd "/bin/sh -c 'sudo -H -S -p "[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: " -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-ouzmdnewuhucvuaabtjmweasarviygqq; /bin/true'"'"' && sleep 0'", env 0
debug3: process_mux_new_session: got fds stdin 9, stdout 10, stderr 11
@@ -85,9 +85,9 @@ debug2: channel 2: rcvd ext data 67
[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: debug2: channel 2: written 67 to efd 11
BECOME-SUCCESS-ouzmdnewuhucvuaabtjmweasarviygqq
debug3: receive packet: type 98
-''' # noqa
+""" # noqa
- ssh_nopipelining_vvvv = b'''
+ ssh_nopipelining_vvvv = b"""
debug3: mux_master_read_cb: channel 1 packet type 0x10000002 len 251
debug2: process_mux_new_session: channel 1: request tty 1, X 1, agent 1, subsys 0, term "xterm-256color", cmd "/bin/sh -c 'sudo -H -S -p "[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: " -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-ouzmdnewuhucvuaabtjmweasarviygqq; /bin/true'"'"' && sleep 0'", env 0
debug3: mux_client_request_session: session request sent
@@ -101,7 +101,7 @@ debug3: Received SSH2_MSG_IGNORE
BECOME-SUCCESS-ouzmdnewuhucvuaabtjmweasarviygqq
debug3: receive packet: type 98
-''' # noqa
+""" # noqa
ssh_novvvv = (
b'[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: \n'
@@ -117,9 +117,9 @@ debug3: receive packet: type 98
nothing = b''
- in_front = b'''
+ in_front = b"""
debug1: Sending command: /bin/sh -c 'sudo -H -S -p "[sudo via ansible, key=ouzmdnewuhucvuaabtjmweasarviygqq] password: " -u root /bin/sh -c '"'"'echo
-'''
+"""
c = NoOpConnection(self.play_context, self.in_stream)
c.set_become_plugin(become_loader.get('sudo'))
diff --git a/test/units/plugins/test_plugins.py b/test/units/plugins/test_plugins.py
index 4bd96a1756..1bd9aef3a2 100644
--- a/test/units/plugins/test_plugins.py
+++ b/test/units/plugins/test_plugins.py
@@ -86,11 +86,11 @@ class TestErrors(unittest.TestCase):
self.assertPluginLoaderConfigBecomes(None, [])
def test__load_module_source_no_duplicate_names(self):
- '''
+ """
This test simulates importing 2 plugins with the same name,
and validating that the import is short circuited if a file with the same name
has already been imported
- '''
+ """
fixture_path = os.path.join(os.path.dirname(__file__), 'loader_fixtures')
@@ -104,10 +104,10 @@ class TestErrors(unittest.TestCase):
@patch('ansible.plugins.loader.glob')
@patch.object(PluginLoader, '_get_paths_with_context')
def test_all_no_duplicate_names(self, gp_mock, glob_mock):
- '''
+ """
This test goes along with ``test__load_module_source_no_duplicate_names``
and ensures that we ignore duplicate imports on multiple paths
- '''
+ """
fixture_path = os.path.join(os.path.dirname(__file__), 'loader_fixtures')
diff --git a/test/units/template/test_templar.py b/test/units/template/test_templar.py
index dd7f340650..920b64fa36 100644
--- a/test/units/template/test_templar.py
+++ b/test/units/template/test_templar.py
@@ -207,7 +207,7 @@ class TestTemplarTemplate(BaseTemplar, unittest.TestCase):
self.assertTrue(self.is_unsafe(res), 'returned value from template.template (%s) is not marked unsafe' % res)
def test_weird(self):
- data = u'''1 2 #}huh{# %}ddfg{% }}dfdfg{{ {%what%} {{#foo#}} {%{bar}%} {#%blip%#} {{asdfsd%} 3 4 {{foo}} 5 6 7'''
+ data = u"""1 2 #}huh{# %}ddfg{% }}dfdfg{{ {%what%} {{#foo#}} {%{bar}%} {#%blip%#} {{asdfsd%} 3 4 {{foo}} 5 6 7"""
self.assertRaisesRegex(AnsibleError,
'template error while templating string',
self.templar.template,
diff --git a/test/units/utils/display/test_logger.py b/test/units/utils/display/test_logger.py
index b3203f8cff..7218448b81 100644
--- a/test/units/utils/display/test_logger.py
+++ b/test/units/utils/display/test_logger.py
@@ -10,10 +10,10 @@ import sys
def test_logger():
- '''
+ """
Avoid CVE-2019-14846 as 3rd party libs will disclose secrets when
logging is set to DEBUG
- '''
+ """
# clear loaded modules to have unadultered test.
for loaded in list(sys.modules.keys()):
diff --git a/test/units/vars/test_variable_manager.py b/test/units/vars/test_variable_manager.py
index 0318d9cc40..d3cdf0de08 100644
--- a/test/units/vars/test_variable_manager.py
+++ b/test/units/vars/test_variable_manager.py
@@ -249,9 +249,9 @@ class TestVariableManager(unittest.TestCase):
@patch('ansible.playbook.role.definition.unfrackpath', mock_unfrackpath_noop)
def test_variable_manager_role_vars_dependencies(self):
- '''
+ """
Tests vars from role dependencies with duplicate dependencies.
- '''
+ """
mock_inventory = MagicMock()
fake_loader = DictDataLoader({