Commit Graph

3289 Commits (devel)

Author SHA1 Message Date
Matt Martz 5e369604e1
Forked display via queue (#77056)
* Forked Display via queue

* Docs and simple code cleanup

* Only proxy Display.display

* Remove unused import

* comment

* Update deadlock comment, remove py3 check

* Don't flush display, and don't lock from forks

* clog frag

* ci_complete ci_coverage

* Add units for queue proxying

* Cleanup flush

* ci_complete

* Only lock the write, switch to RLock

* Remove unused import
2 years ago
Wouter Schoot 711b51fad6
Remove double spaces in errormessage (#77839) 2 years ago
Sloane Hertel 621e782ed0
Add toggle to fix module_defaults with module-as-redirected-action on a per-module basis (#77265)
* If there is a platform specific handler, prefer the resolved module over the resolved action when loading module_defaults

Add a toggle for action plugins to prefer the resolved module when loading module_defaults

Allow moving away from modules intercepted as actions pattern

Fixes #77059
2 years ago
Matt Clay 2595b42aca
Prefer unittest.mock over mock. (#77886) 2 years ago
Matt Clay 3a9a23fb1a
Use unittest.mock instead of mock. (#77883)
This can only be done for controller tests.
2 years ago
Matt Clay 8ca28acd0d Fix unit tests for Python 3.11. 2 years ago
Matt Clay 5f74350fd5 Avoid deprecated method in unit tests. 2 years ago
Martin Krizek e9af6efee6
Raise a proper error when include/import_role is used as a handler (#77807) 2 years ago
Abhijeet Kasurde 524d30b8b0
distribution: add distribution_minor_version for Debian Distro (#74721)
* Added a fact about minor version details for Debian Distro

Fixes: #74481

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2 years ago
Martin Krizek ed30fc9a06
Remove deprecated loading cache plugins directly without cache_loader (#77655) 2 years ago
Matt Clay 5c2d830dea
ansible-test - Fix subprocess management. (#77641)
* Run code-smell sanity tests in UTF-8 Mode.
* Update subprocess use in sanity test programs.
* Use raw_command instead of run_command with always=True set.
* Add more capture=True usage.
* Don't expose stdin to subprocesses.
* Capture more output. Warn on retry.
* Add more captures.
* Capture coverage cli output.
* Capture windows and network host checks.
* Be explicit about interactive usage.
* Use a shell for non-captured, non-interactive subprocesses.
* Add integration test to assert no TTY.
* Add unit test to assert no TTY.
* Require blocking stdin/stdout/stderr.
* Use subprocess.run in ansible-core sanity tests.
* Remove unused arg.
* Be explicit with subprocess.run check=False.
* Add changelog.
* Use a Python subprocess instead of a shell.
* Use InternalError instead of Exception.
* Require capture argument.
* Check for invalid raw_command arguments.
* Removed pointless communicate=True usage.
* Relocate stdout w/o capture check.
* Use threads instead of a subprocess for IO.
2 years ago
Brian Coca b439e41a91
expand ansible-doc coverage (#74963)
* Expand ansible-doc to tests/filters and fix existing issues

  enable filter/test docs if in single file or companion yaml
  add docs for several filters/tests plugins
  allow .yml companion for docs for other plugins, must be colocated
  verify plugins are valid (not modules, cannot)
  fix 'per collection' filtering
  limit old style deprecation (_ prefix) to builtin/legacy
  start move to pathlib for saner path handling
  moved some funcitons, kept backwards compat shims with deprecation notice

  Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
  Co-authored-by: Felix Fontein <felix@fontein.de>
  Co-authored-by: Sandra McCann <samccann@redhat.com>
2 years ago
Martin Krizek 3980eb8c09
Prevent losing unsafe from lookups (#77609)
* Prevent losing unsafe from lookups

This patch fixes a bug which under certain conditions results in data
returned from lookups not being marked as unsafe.

Each time Templar.do_template is invoked a new AnsibleContext is
created and stored effectively at two places:
1) as an instance variable in templar_obj.cur_context
2) as a local variable called new_context in do_template method of Templar

Due to custom functionality in Ansible's Context that allows for nested
templating it is possible that during resolving variable's value
template/do_template method is called recursively again, again creating
a new context. At that point the problem manifests itself because as
mentioned in 1) above the context is overwriten on the templar object
which means that any subsequent calls to _lookup will use the new
context to mark it as unsafe which is now different to the local
new_context which is used for testing for unsafe property.

The solution to the problem appears to be to restore the original
context inside do_template and also to eliminate the local variable
new_context to prevent problems in the future.

It appears that we don't have a better way of storing the context other
than as some form of global variable and so this appears to be the
"best" solution possible at this point. Hopefully data tagging will be
the solution here.

For more examples see unit and integration tests included in this patch.

Fixes #77535
2 years ago
Matt Clay 26fd5a8c3a Revert "ansible-test - Fix subprocess management. (#77638)"
This reverts commit 62d03c8e75.
2 years ago
Matt Clay 62d03c8e75
ansible-test - Fix subprocess management. (#77638)
* Run code-smell sanity tests in UTF-8 Mode.
* Update subprocess use in sanity test programs.
* Use raw_command instead of run_command with always=True set.
* Add more capture=True usage.
* Don't expose stdin to subprocesses.
* Capture more output. Warn on retry.
* Add more captures.
* Capture coverage cli output.
* Capture windows and network host checks.
* Be explicit about interactive usage.
* Use a shell for non-captured, non-interactive subprocesses.
* Add integration test to assert no TTY.
* Add unit test to assert no TTY.
* Require blocking stdin/stdout/stderr.
* Use subprocess.run in ansible-core sanity tests.
* Remove unused arg.
* Be explicit with subprocess.run check=False.
* Add changelog.
2 years ago
Sam Doran 1b947eaf92
arg_spec - Return aliases in validation result and update aliases (#77576)
When looking up the `no_log` setting for a parameter that is an alias in
`AnsibleModule._log_invocation()`, the alias value will always be an
empty dictionary since `self.aliases` on the `AnsibleModule` instance is
never updated after initialization. Since the `no_log` setting is on the
canonical parameter not the alias, an incorrect warning is issued if the
parameter matches `PASSWORD_MATCH`.

This PR returns the aliases dictionary as an attribute of the
`ValidationResult` and updates the `aliases` attribute on the
`AnsibleModule` instance.
2 years ago
Jack 4d69c09695
ansible-galaxy collection - ensure dependencies are a dict (#77561)
* fix traceback when installing collection with dependencies set to None
2 years ago
Brian Coca abdd237de7
Yolo (#77554)
* Revert "Revert "Config, ensure templating happens at functions (#77483)""

This reverts commit 94c9106153.

* removed update configdata, which is unused
* removed test for action we don't perform anymore
* removed unused configdata
2 years ago
Martin Krizek cbe42bff7f
Allow for lazy evaluation of Jinja2 expressions (#56116) 2 years ago
Brian Coca f2ab920822
Better info sourcing (#77511)
Task is  authoritative
   also includes latest per loop info
   and fix tests
2 years ago
Brian Coca 3b9592fcaf
Move to display as single source of verbosity (#77498)
* Move to display as single source of verbosity

Co-authored-by: Sloane Hertel <19572925+s-hertel@users.noreply.github.com>
2 years ago
htol d7fbde4ea9
Make "~/.ansible" path configurable (#76114)
* replace hardcoded '~/.ansible' to C.ANSIBLE_HOME
* rename previously existing env ANSIBLE_HOME in env-setup script
* modify cache dir monkeypatching in galaxy api unit tests
* update "version_added" to 2.14 for ANSIBLE_HOME
* fix description of collections with proper use of ANSIBLE_HOME

Co-authored-by: htol <github@h-tol.net>
Co-authored-by: stefanwascoding <stefan@syntaxhelden.de>
2 years ago
Martin Krizek 94eff70030
PlayIterator - remove deprecated states (#77444) 2 years ago
Sloane Hertel 477c55b0d2
Get git executable for collections in git repos (#77493)
* Fix traceback installing collections from git repos if git is not installed
2 years ago
Sloane Hertel 87a8fedd94
Fix type for ansible-galaxy server config definitions (#77424)
* Fix type for ansible-galaxy server config definitions

* changelog

* check attr without api call

* pep8
2 years ago
Martin Krizek e080bae766
Remove deprecated ALLOW_WORLD_READABLE_TMPFILES config option (#77410)
Fixes #77393
2 years ago
Jordan Borean 60b4200bc6
winrm - ensure callers PATH for kinit is set (#77401)
* winrm - ensure callers PATH for kinit is set

* Fix unit test expectations

* Fix type annotation
2 years ago
Sloane Hertel f96a661ada
ansible-galaxy - add configuration options for more flexible collection signature verification (#77026)
* Add a toggle to control the number of signatures required to verify the authenticity of a collection

* Make the default number of required valid signatures 1

* Add option to make signature verification strict and fail if there are no valid signatures (e.g. "+1")

* Use a regex to validate --required-valid-signature-count

* Add a toggle to limit the gpg status codes that are considered a failure

* Update documentation and changelog

* Add unit and integration tests for the new options

* Fixes #77146

Fix using user-provided signatures when running 'ansible-galaxy collection verify ns.coll --offline'

Add a test for a user-provided signature when running ansible-galaxy collection verify with --offline

Fix displaying overall gpg failure without extra verbosity

Add a test for displaying gpg failure without verbosity

Improve documentation to be more clear that signature verification only currently applies to collections directly sourced from Galaxy servers
2 years ago
ChanthMiao 34e60c0a7a
ansible_distribution: Add support for Uos/Deepin (#77275)
* ansible_distribution: Add support for Uos/Deepin

* Add changelog fragment.
2 years ago
Felix Fontein e3c72230cd
unarchive: fix io_buffer_size option, remove ignore.txt entry (#77271)
* Fix io_buffer_size option.

* Remove ignore.txt entry by adding action plugin only options to module's argument spec.

* Add changelog fragment.

* Adjust unit tests.
2 years ago
Matt Clay f68c66a3ef Remove collections compat from controller code. 2 years ago
Abhijeet Kasurde 4f48f375a0
parameters: handle blank values when argument is a list (#77119)
Fixes: #77108

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2 years ago
Matt Clay 1a5853d794
Remove obsolete units.compat.mock compat layer. (#77118)
* Remove obsolete units.compat.mock compat layer.
* Update remaining units.compat.mock references.
2 years ago
Matt Clay b613808277 Remove obsolete unit test builtins compat. 2 years ago
Matt Clay 2cd6cdc6a7
Fix duplicate unit test function names. (#77115)
* Fix duplicate unit test function names.
* Disable faulty tests.
2 years ago
Matt Clay 0bd8106d15 Remove unused mock compat code.
The code is unreachable since Python 3 versions before 3.5 are not supported.
2 years ago
Matt Clay de9a3bda2c Fix warning in unit tests for _yaml import. 2 years ago
Sloane Hertel 43e55db208
ansible-galaxy - add signature verification of the MANIFEST.json (#76681)
* ansible-galaxy collection install|verify:

  - Support verifying the origin of the MANIFEST.json when the Galaxy server has provided signatures.
  - Allow supplemental signatures to use during verification on the CLI/requirements file.

* ansible-galaxy collection install:

  - Support disabling signature verification. This silences the warning provided by ansible-galaxy if the Galaxy server provided signatures it cannot use because no keyring is configured.
  - Store Galaxy server metadata alongside installed collections for provenance. This is used by 'ansible-galaxy collection verify --offline'.

* Add unit tests for method that gets signatures from a Galaxy server

* Add integration tests for user-provided signature sources

- Test CLI option combinations
- Test installing collections with valid/invalid signature sources
- Test disabling GPG verification when installing collections
- Test verifying collections with valid/invalid signature sources

* Make signature verification advisory-by-default if signatures are provided by the Galaxy server

- Make the default keyring None
- Warn if the keyring is None but the Galaxy server provided signatures
- Error if the keyring is None but the user supplied signatures
- Error if the keyring is not None but is invalid

* changelog

* add ansible-galaxy user documentation for new options

Co-authored-by: Matt Martz <matt@sivel.net>
Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
Co-authored-by: Martin Krizek <martin.krizek@gmail.com>
Co-authored-by: Sandra McCann <samccann@redhat.com>
Co-authored-by: Andy Mott <amott@redhat.com>
Co-authored-by: John R Barker <john@johnrbarker.com>
2 years ago
Thomas Sjögren b145732973
Resubmit: Use SystemdStrategy for Debian in the hostname module (#76929)
* add DebianStrategy tests
* ensure hostname can be changed by using become
* use Systemd strat for debian and Base for generic.
* add test to ensure all strategies are available

Signed-off-by: Thomas Sjögren <konstruktoid@users.noreply.github.com>
2 years ago
Éloi Rivard 3889ddeb4b
iptables - added a ``chain_management`` parameter to control chain (#76378)
creation and deletion

fixes #25099
closes #32158
2 years ago
Brian Coca 0ff80a15ba
ssh connection avoid parsiing own debug (#76732)
- Avoids false positives on become strings being echoed back 
   by ssh cli itself
  - added test for debug lines
  - also simplified some of existing test code
2 years ago
Brian Coca 9142be2f6c
Allow specifying specific python via shebang (#76677)
modules with python were always normalized to /usr/bin/python,
  while other interpreters could have specific versions.

* now shebang is always constructed by get_shebang and args are preserved
* only update shebang if interpreter changed
* updated test expectation
* added python shebang test
2 years ago
Adrian Likins 20cc87f059
Expect upper case message 'levels' for galaxy publish results (#63530) 2 years ago
Sloane Hertel 76220c4a7b
ansible-galaxy - fix the --ignore-certs flag for the implicit galaxy server (#76735)
* ansible-galaxy - fix the --ignore-certs flag for the implicit galaxy server

* changelog

* Add a test without the server config

* Fix respecting --ignore-certs for individual --server URLs also

* Update changelogs/fragments/76735-ansible-galaxy-fix-ignore-certs.yaml
2 years ago
Matt Martz 0ef5274a3c Don't assert stdlib behavior, just assert that urllib was called 2 years ago
Jordan Borean aaa7944b02
Fix tests failing on pytest 7 (#76670)
* Fix pytest 7 failures with leaky fixture
2 years ago
Matt Clay 97104f1221
Avoid deprecated TestCase functions in unit tests. (#76678)
* Avoid deprecated TestCase functions in unit tests.
* Add assertRaisesRegex for Python 2.7.
* Fix indentation.
2 years ago
Jaromaz 16def8050a
facts - Set correct OS family for EuroLinux (#76624)
Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
2 years ago
Sloane Hertel ed6581e4db
check finder type before passing path (#76448)
* check finder type before passing path

ci_complete

* Reduce nesting

* Test find_module does not cause a traceback with Python 3 FileFinder

* Update lib/ansible/utils/collection_loader/_collection_finder.py
3 years ago
Jordan Borean 8482ee4e9a
galaxy build - ignore existing MANIFEST and FILES (#76479) 3 years ago
James Livulpi 7830e5308e
add tencentos fact distro (#76459)
Fixes #76459

Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Brian Coca 472028c869
catch the case that cowsay is broken (#76326)
* catch the case that cowsay is broken

fixes https://github.com/ansible/ansible/issues/72582

  add changelog
  raise Exception for broken cowsay
  add test for broken cowsay

Co-authored-by: Matthias Bernt <m.bernt@ufz.de>
3 years ago
Brian Coca b02168d644
better handling of sudo flag replacement (#76389)
* better handling of sudo flag replacement
3 years ago
Richie B2B 1b34933414
Fix ansible-doc -l ansible.builtin / ansible.legacy (#76235) 3 years ago
Martijn Pieters 08af0fbf95
Unbreak hostname.RedHatStrategy (#76032)
- On Python 3, decode bytes to str
- Tolerate whitespace around the line.
- Report a missing HOSTNAME line as an error.
- Don't clobber line separators when setting a new hostname.
- Add some tests for this strategy to verify correct operation.
3 years ago
Martin Krizek 5c225dc0f5
Introduce public methods to access PlayIterator._host_states (#74416) 3 years ago
Jan Fader 17ec2d4952
check /.dockerenv and /.dockerinit to guess a dockercontainer (#74349)
* use os.path.exists for docker-check

Co-authored-by: Jacob Floyd <cognifloyd@gmail.com>
3 years ago
Martin Krizek 47ee282227
Parser errors from within includes should not be rescueable (#73722)
* Parser errors from within includes should not be rescueable
* Also fixes unit tests
Fixes #73657
3 years ago
Martin Krizek 26707a3c6b
Heisen jinja2_native (#75587)
* Use NativeEnvironment for all templating

ci_complete

* Keep Templar.copy_with_new_env for backwards compat

* Mention that AnsibleUndefined.__repr__ changed in the porting guide

* Templar.copy_with_new_env backwards compat

* ci_complete
3 years ago
Martin Krizek 395e5e20fa
PlayIterator: use enums for states (#74511) 3 years ago
Martin Krizek 7621784b94
Require Jinja2 3.0.0 (#75881)
* Require Jinja2 3.0.0

ci_complete

* Fix sanity

* Remove Jinja min/max tests

* ansible-test changes

* ci_complete

* More cleanup

ci_complete

* Revert _count_newlines_from_end :( and other stuff

* Fix sanity

* It's using host_vars ...

* Unused import

* Remove overridden groupby filter

* environmentfilter -> pass_environment

* Explain preserve_trailing_newlines

* Add changelog

* ci_complete

* Deprecated ANSIBLE_JINJA2_NATIVE_WARNING

* native_helpers.py cleanup

* More cleanup in the find intgration test
3 years ago
Martin Krizek 23f95300bd
Intentional tests (#76051)
ci_complete
ci_coverage
3 years ago
Miroslav Brabenec bc0caad2ad
Fix parsing of device serial number for RHEL8 (#75876)
* Fix parsing of device serial number for RHEL8

* Add tests and changelog

Co-authored-by: Miroslav Brabenec <miroslav.brabenec@memsource.com>
3 years ago
Martin Krizek f774292439
cli - remove deprecated setting verbosity before sub command (#75840)
* cli - remove deprecated setting verbosity before sub command

Fixes #75823

* Fix tests
3 years ago
Matt Martz 79e9dae292
Don't show params when there is an issue with `set_option(s)` (#75805) 3 years ago
Matt Martz 96b221b344
Update vendored copy of distro to 1.6.0 (#75732)
* Update vendored copy of distro to 1.6.0

* copy pasta mistake

* ci_complete
3 years ago
Ross Bender 7a4b5d14fc
ansible-galaxy role install: download from API response location (#73114)
* download role from api response location

* include changelog fragment

* add unit test for role download url

Co-authored-by: Sam Doran <sdoran@redhat.com>
3 years ago
Thomas Sjögren 57359d0174
use passlib default if `password_hash` option isn't set (#75043)
* add changelog fragment
* password_hash|length == 120
* mention the new default bcrypt format in the porting guide
3 years ago
Sloane Hertel 7ecc227488
ansible-galaxy: Clone git collections using shallow clones (#75722)
* ansible-galaxy: Clone git collections using shallow clones

This ensures the collection obtained via git url is a result of a
shallow git clone (git clone --depth=1). The git history of the
collection is not used by ansible, and as such, cloning the entire
history of the repo is unnecessary.

Signed-off-by: Tomas Babej <tomas@tbabej.com>

* ansible-galaxy: Only perform shallow clones on non-versioned git urls

In general, the version can be anything we can checkout (branch, tag,
but also a commit hash). In particular for commit hashes we cannot
perform a shallow clone.

Err on the safe side and only perform shallow clones for non-versioned
git urls (cloning HEAD).

* galaxy-install: Make shallow cloning compatible with older Python versions

Signed-off-by: Tomas Babej <tomas@tbabej.com>

* Pass args as a tuple

Add tests for the git command created from different repo and version combinations

* changelog

Co-authored-by: Tomas Babej <tomas@tbabej.com>
3 years ago
Matt Clay 4ea8d9a782
ansible-test - split controller/target testing (#75605) 3 years ago
Daniel Goldman 989eeb243f
Add an `undef` global Jinja function (#75435)
* add tests for fail filter

also tests that fail does not block inspectability

* add fail filter

fallback message is a bit clunky,
since you can't invoke a filter without specifying an input.
That is, "{{ fail }}" doesn't work,
so you have to do "{{ None | fail }}"

* document 'fail' filter

* add changelog fragment

* fail filter uses default message on Undefined or emptystring

makes it slightly easier to use the default message:
```diff
- "{{ None | fail }}"
+ "{{ '' | fail }}"
```

and the user sees a slightly more relevant message
if the message itself is undefined:

```diff
- The error was: {{ failmsg | fail }}: 'failmsg' is undefined
+ The error was: {{ failmsg | fail }}: Mandatory variable has not been overridden
```

* rebuild as the builtin `Undefined`

* harmonise `hint` parameter for make_undefined with jinja

* use code block for documentation item

[ref](https://github.com/ansible/ansible/pull/75435#discussion_r707661035)

* rename to `undef` to expose less Python into the Jinja

[ref](https://github.com/ansible/ansible/pull/75435#pullrequestreview-757799031)

* explicitly instantiate undefined value now that it's possible

see I knew we would break something with reflection

* preserve test coverage of undefined variable

Co-authored-by: Matt Davis <nitzmahone@users.noreply.github.com>
3 years ago
Chris Hambridge 1353678f23
Enable ansible-galaxy to specify client id override with Keycloak Token (#75601)
* Enable ansible-galaxy to specify client id override with Keycloak Token

* Specify ability to provide override of client_id

* Test client_id can be configured for individual servers

* Add issue link to changelog

* Document client_id as a config option and add an example

Co-authored-by: s-hertel <19572925+s-hertel@users.noreply.github.com>
3 years ago
Sloane Hertel 72ba2bdc82
ansible-galaxy - add a per-server validate_certs option (#75710)
* Add a validate_certs option to galaxy server configuration

* Add a unit test for cert validation

* changelog
3 years ago
Abhijeet Kasurde 12734fa21c
yaml dumper: Add YAML respresenter for AnsibleUndefined (#75078)
Fixes: #75072

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Matt Clay de01db08d0
pip - Use pip from the current Python interpreter. (#75634)
* pip - Use pip from the current Python interpreter.

If `executable` and `virtualenv` were not specified, and
the `pip` Python module is available for the current interpreter,
use that `pip` module instead of searching for a `pip` command.

* Add comment about needing `__main__` to run `pip`.

* Fix unit test.

* Add porting guide entry.

* Update changelog to match porting guide description.

ci_complete
3 years ago
Matt Martz 74f5367673
Ensure `heuristic_log_sanitize` returns correct data if no password found (#75570)
* Ensure heuristic_log_sanitize returns correct data if no password found. See #75542

* Need to allow code to flow through
3 years ago
Pilou 3d7f2a1366
Fix an exception when passlib library is used with a wrapped algo (#75527)
* Test a passlib wrapped algo with a password lookup

* Fix error when passlib is used with a wrapped algo

The exception was:

     An unhandled exception occurred while running the lookup plugin 'password'.
     Error was a <class 'TypeError'>, original message: issubclass() arg 1 must be a class

and can be reproduced using the following command:

    ansible localhost -i localhost, -mdebug -amsg="{{ lookup('password', '/dev/null encrypt=ldap_sha512_crypt') }}"

The concerned algo are: bsd_nthash, django_argon2, django_bcrypt, ldap_bcrypt,
ldap_bsdi_crypt, ldap_des_crypt, ldap_hex_md5, ldap_hex_sha1, ldap_md5_crypt,
ldap_pbkdf2_sha1, ldap_pbkdf2_sha256, ldap_pbkdf2_sha512, ldap_sha1_crypt,
ldap_sha256_crypt, ldap_sha512_crypt, roundup_plaintext
3 years ago
Brian Coca 3ca50a2200
Clarify get_bin_path error message (#75544) 3 years ago
Martin Krizek 51f2f1ac5e
yum: fix parsing of check-update with subsequent empty lines (#75452)
Rather than adding further complexity to the regex, preprocess the output to
remove any empty lines. Now the only purpose of the regex is to fix
wrapped lines.

Fixes #70949
3 years ago
Matt Clay 7450e87615
Fix up string splitting to prepare for pylint update. (#75479)
* Use rsplit with maxsplit in BaseCacheModule.
* Use maxsplit for accessing first item.
* ansible-test - More efficient splitting.
3 years ago
Matt Clay ce6d8a143c
Code cleanup to prepare for pylint update. (#75475)
* user - Remove unused code.
* Replace deprecated abstractproperty decorator.
* Fix __all__ to be a tuple.
* Use a generator in subelements lookup.
* Use from import in basic.py
* Add changelog fragment.
* Fix selinux unit test.
3 years ago
Matt Clay 04009a77e6
Clean up unit tests to prepare for pylint update. (#75473)
* Fix argument name in mocked function.
* Use from import in unit tests.
* Remove unused imports.
3 years ago
Sam Doran fa7482c63a
Change interpreter discovery defaults to silently prefer Python 3 (#75049)
Push /usr/bin/python to almost the bottom of the barrel. This makes the strategy to prefer
specific versions of the "mystery meat" version.

* Change INTERPRETER_PYTHON default to 'auto'
    Change description to match change in behavior.
    Change deprecation message to a warning.

* Update docs
* Add porting guide entry
* Update unit tests
* Update integration test
* Allow INTERPRETER_PYTHON_FALLBACK to be configure using a variable
* Prefer platform-python above other Python 2 interpreters
* Add Python 3.10 to the list of interpreters
3 years ago
Brian Coca 8d41b97329
Skip python interpreter discovery for 'forced local' module execution (#74824)
mostly for use with network_os
  use 'remote is local' property as indicator
  ensure task_vars are as expected in test
3 years ago
Martin Krizek 58e38044fe
Fix when evaluation on Native Jinja and Python 3.10 (#75202)
* Fix when evaluation on Native Jinja and Python 3.10

* Add unit test

* Add explaining comment

* Enable jinja2_native before tests

Co-Authored-By: Matt Martz <matt@sivel.net>

* Sanity

* Return native template module instead of modifying globals

Co-authored-by: Matt Martz <matt@sivel.net>
3 years ago
Matt Martz 4dca539a29
Expose `unredirected_headers` to `uri` and `get_url` modules (#75308) 3 years ago
Brian Coca 61900c7672
modules moved to use best_parsable_locale (#75250)
* modules moved to use best_parsable_locale

* fixed invocations

* better better

* also module_utils

* converted to function as per fb

* patch testt

* whitespace
3 years ago
Sloane Hertel 3b861abce1
add action_groups support to collections (#74039)
* Canonicalize module_defaults actions and action_groups pre-fork and cache them on the play

* Call get_action_args_with_defaults with the resolved FQCN plugin and don't pass the redirect list

* Add validation for action_group metadata and a toggle to disable the warnings

* Handle groups recursively referring to each other

* Remove special-casing for non-fqcn actions in module_defaults groups

* Error for actions and groups in module_defaults that can't be resolved

* Error for fully templated module_defaults

* Add integration tests for action_groups

* Changelog
3 years ago
Abhijeet Kasurde e7a3715a90
recursive_diff: handle error when parameters are not dict (#74801)
Co-authored-by: Sam Doran <sdoran@redhat.com>
3 years ago
Sam Doran a8de35e131
task_executor - use correct value for ssh connection retries (#75155)
Since the task and connection both have the same 'retries' keyword, the task default
would override the connection value.

Do not pass 'retries' from the task to the connection options.

* Set ssh_connection retries default value back to 0
  It was 0 before the move to config and was changed to 3 by accident.
3 years ago
Brian Coca 415e08c297
Try to get best usable locale (#75033)
specially for when you have parameters in unicode but need
  to scrape responses, C is still the fallback

Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Abhijeet Kasurde b0ae3f8a8d
test: Unit tests for validation methods (#75061)
* check_required_one_of()
* check_required_by()
* check_required_if()
* check_missing_parameters()

Fixes: #55994

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Nasser Alansari 6dbfd73174
YAML representer for VarsWithSources (#68525) 3 years ago
Sam Doran cd473dfb2f
play - validate hosts entries (#74147)
* Change tests to pytest-style tests
* Add tests for invalid hosts
* Validate host inputs
  - check for empty values
  - check for None
  - check for values that are not a sequence and are not strings
  - add unit tests

* Move play name setting to get_name() and out of load()
* Add _validate_hosts() method
  By defining this method, it gets called automatically by FieldAttributeBase.validate().
3 years ago
Sam Doran 9a21e24778
get_distribution - Return distribution for all platforms (#71641)
Since moving to distro, it is possible to return this information for all platforms, not just Linux.
Also return version information for all platfrom not just Linux.
Update unit tests.
Remove some duplicate unit tests though I think there are more to remove.

* Fix docstring formatting

* Minor docstring changes

* Mock distro.id for Solaris service test

* Update comment
3 years ago
Jonathan Kirszling 50e998e303
apt_key: add --recv argument as last one (#74949)
* apt_key: add --recv argument as last one

* Add unit test

* Add the required boilerplate

Co-authored-by: Marius Gedminas <marius@gedmin.as>
3 years ago
Sam Doran 004c33d9c5
unarchive - do not fail in init when trying to find required binary (#74892)
Test for the required binaries in the can_handle_archive() method and fail there. This
prevents failures for missing binaries unrelated to the archive type.

* Update missing zip binary message to match tar message
* Update unit tests
* Add integration tests
* Define packages based on the system rather than ignoring failures
3 years ago
Brian Coca 5dd8dc8fd0
minor service_mgr facts fixes (#74894)
* minor service_mgr facts fixes

  handle case in which ps command fails or returns empty
  updated tests since it now does keep trying to detect after ps fails
3 years ago
s-hamann e2658801f6
Add seed parameter to password lookup (#69775) 3 years ago
Abhijeet Kasurde 8f82e6327f
ansible-cli: Remove unnessary trailing space (#74880)
Fixes: #74875

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Johannes Heimansberg b023f34f4a
service_mgr: Detect using symlink if proc/1 and ps fail
* runit and other alternative service managers tend to work via symlink so this covers most of em
* Fixes #74866.
3 years ago
Abhijeet Kasurde be9f8c69d1
unarchive: Fail when zipinfo is not available (#74632)
Fixes: #39029

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
David Lee Whiteside 805799ac8b
add pkcs11 support to Ansible ssh connection module (#32829)
* rebased with upstream

* removed extra usetty as it wasnt needed, style changes, added var option setable by inventory for pkcs11

* update pkcs11_provider version_added

* Update lib/ansible/plugins/connection/ssh.py

Co-authored-by: Jordan Borean <jborean93@gmail.com>

* Update lib/ansible/plugins/connection/ssh.py

Correct logic for a password being required for pkcs11_provider

Co-authored-by: Jordan Borean <jborean93@gmail.com>

* style nit fixes for checking pkcs11_provider is set

* fixed duplication when using password_prompt with pkcs11_provider

* added changelog fragment

* added changelog fragment

Co-authored-by: David Whiteside <david.whiteside@nrel.gov>
Co-authored-by: Matt Davis <nitzmahone@users.noreply.github.com>
Co-authored-by: Jordan Borean <jborean93@gmail.com>
3 years ago
Abhijeet Kasurde 70f22c7f32
Remove commented code (#74860)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Sloane Hertel 5640093f1c
Use the module redirect_list when getting defaults for action plugins (#73864)
* Fix module-specific defaults in the gather_facts, package, and service action plugins.

* Handle ansible.legacy actions better in get_action_args_with_defaults

* Add tests for each action plugin

* Changelog

Fixes #72918
3 years ago
Alexander Sowitzki 502270c804 hostname: clean up strategies
Apply #74744 and #69929 to #70828
3 years ago
Rick Elrod 8a0abed1ba [hostname] don't write in get_*() methods
Change:
- Hostname strategies' get_*() methods should never write to the
  filesystem. They are used in check_mode by default to determine if
  there is any work to be done.

Test Plan:
- New unit tests to ensure that (at least when in check_mode) the get
  methods don't ever call write.

Tickets:
- Fixes #66432

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Matt Martz 98138584b7
Don't mutate os.environ in AnsibleModule.run_command, make a copy, and pass to Popen (#74791)
* Don't mutate os.environ in AnsibleModule.run_command, make a copy, and pass to Popen. Fixes #74783

* Simplify code a bit

* More simple

* Address some other potentially non threadsafe operations

* Add if around umask

* Address unit test assumptions

* Add clog frag

* yaml syntax issue
3 years ago
Matt Martz d27ce4cef3
Remove deprecated features from ansible.playbook.helpers (#74809)
* Remove deprecated features from ansible.playbook.helpers. Fixes #74135
3 years ago
Matt Martz 4a4ffbadc5
Remove deprecated PlayContext.make_become_cmd (#74790) 3 years ago
Abhijeet Kasurde 1bd7dcf339
encrypt: add new paramter 'ident' (#74595)
Add a new parameter `ident` for specifying version of BCrypt
algorithm. This parameter is only valid for `blowfish` hash type.
3 years ago
Sam Doran c0cb353ce1
Remove PyCrypto (#74699)
* Remove PyCrypto from setup.py and packaging script
* Remove mention of pycrpto from installation docs
* Remove PyCrypto from vault
* Remove pycryto constraint and unit test requirement
* Remove PyCrypto tests from unit tests
* Add docs and fix warning message
* Remove section about cryptography library in Ansible Vault docs
3 years ago
Matt Martz 8d1cf7f266
Vendor `distutils.version` (#74644)
* Vendor distutils.version

* Fix import order. ci_complete

* remove distutils warning filter

* Don't remove warnings filter from importer

* ci_complete

* Add pylint config for preventing distutils.version

* Add changelog fragment
3 years ago
Brian Coca ddaa539ab1
Better handling of rstisms in ansible-doc (#74596)
* Better handling of rstisms

  replace tags more intelligently to make things more readable
  unit tests + minor adjustments
3 years ago
Sloane Hertel ee725846f0
ansible-galaxy - increase page size and add retry decorator for throttling (#74240)
* Get available collection versions with page_size=100 for v2 and limit=100 for v3

* Update unit tests for larger page sizes

* Add a generic retry decorator in module_utils/api.py that accepts an Iterable of delays and a callable to determine if an exception inheriting from Exception should be retried

* Use the new decorator to handle Galaxy API rate limiting

* Add unit tests for new retry decorator

* Preserve the decorated function's metadata with functools.wraps

Co-authored-by: Matt Martz <matt@sivel.net>
Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
3 years ago
Matt Clay bcb64054ed
Another unit test fix for Python 3.10. (#74628)
* Another unit test fix for Python 3.10.
* Add missing __init__.py file.
3 years ago
Matt Clay d4413dac08 Fix unit tests on Python 3.10. 3 years ago
Sam Doran 55b401a3e7
pause - ensure control characters are always set appropriately (#74568)
* pause - ensure control characters are always set appropriately

On some systems, curses.tigetstr() returns None, which does not work as a control character.

* Add unit tests

* Sort imports

* Skip on older Python

This is an action plugin and only runs on the controller, so no need to test of Python 2. Making
the import hackery work on Python 2 would required some more work which I am not sure is
worth it since we are moving away from Python 2 support on the controller.

* Make the tests work on Python 2 and 3
3 years ago
Matt Clay 5dfc7ee078 Remove Shippable CI provider from ansible-test. 3 years ago
Ruairidh MacLeod d101009688
facts - set correct OS family for Rocky Linux (#74530) 3 years ago
Harm Geerts 9bd70045c9
Fix BaseFileCacheModule#keys to respect prefix (#72789)
* Fix BaseFileCacheModule#keys to respect prefix

Change:
- Previously BaseFileCacheModule#keys would return keys with the cache
  prefix. These keys are impossible to retrieve from the cache without
  removing the prefix or using the cache without a prefix.
  Now it removes the prefix from the key and only returns keys that
  share the same prefix as the cache.

Test Plan:
- New unit tests

* Add explicit BaseFileCacheModule#keys test

Test that files that do not match the cache prefix are ignored.
Test that the prefix is removed from the cache key.
3 years ago
Matt Clay a30c55f68a Remove deprecated `common.removed` module_util.
Tests have been updated to reflect its removal as well.
3 years ago
Sam Doran 74b2add460
paramiko_ssh - mark connection as connected when successful (#74459)
* Remove unused import from test
3 years ago
Brian Coca 3cff54d69b
Fix missing delegate display (#74370)
* dont rely on vars, task already gives us info
* ensure we always display delegation in host label
* also added parens with ansible_host to show  target host vs resolved host
* delegating to self is not delegating
* delegated vars restoration for backwards compat
* tests need mock task with delegate_to
3 years ago
Anatoly Pugachev 04e57d28e3
[facts] add hpux fc info, refactor aix and solaris code (#57406)
* correctly parse device from string
* check for command presence before running them
* check for command presence and return code for solaris and aix as well
* add changelog
3 years ago
Logistic Bot 7099657dd7
Basic: don't call lstat when check_mode (#64279)
While mode is specified in check_mode, don't call lstat.
Since file may not present.

Fixes: #61185
3 years ago
Rick Elrod fcbf5c3185
[module_utils] make to_bits actually return (#74409)
Change:
- Instead of returning the `str` type, return the value that was
  calculated.

Test Plan:
- New unit tests.

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Fernando Correia 7fd989d008
Detect Homebrew on Mac M1 (Apple Silicon) (#74378)
Homebrew's default install location for macOS on ARM is /opt/homebrew.
Source: https://docs.brew.sh/FAQ

On a Mac M1 (Apple Silicon), homebrew will be installed at
/opt/homebrew/bin/brew.
3 years ago
Brian Coca 4494ef3a9d
defend against bad or missing crypt (#74304)
* defend against bad or missing crypt

  fixes #74279
3 years ago
Rick Elrod 9f1513d4c0 [become] Add Solaris chmod ACL fallback
Change:
- Newer Solaris drops setfacl. Add a fallback for its chmod ACL syntax.

Test Plan:
- New units

Tickets:
- Fixes #74282

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Rick Elrod 7d64aebdd3 [become] Fix solaris permissions regression
Change:
- Regression introduced in #70785
- When macOS chmod ACL syntax is used, Solaris-derived chmods return
  with a status of 5. This is also used for our sshpass handling,
  because sshpass will return 5 on auth failure. This means on Solaris,
  we incorrectly assume auth failure when we reach this branch of logic
  and try to run chmod with macOS syntax.
- We now wrap this specific use of chmod in an exception handler that
  looks for AnsibleAuthenticationFailure and skips over it. This adds
  another authentication attempt (something we normally avoid to prevent
  account lockout), but seems better than the regression of not allowing
  other fallbacks to be used.
- Without this patch, if setfacl fails on Solaris (and sshpass is used),
  we do not try common_remote_group or world-readable tmpdir fallbacks.

Test Plan:
- New unit

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Matt Clay 9ba6cf9a72 Relocate misplaced unit tests. 3 years ago
Matt Martz 17237c1d88
Deprecate Py2.6 support for target nodes (#74165) 3 years ago
Alex Willmer 185d410316
Factor out host_label() in default stdout callback plugin (#73814)
This simplifies rendering the hostname (or hostname+delegated host) in
the default callback module, and reduces code duplication

I've chosen not move where in each handler the host label is rendered,
in case subsequent operations has side effects. However I'm happy to
change that if considered safe.

I've chosen not to change the formatting operator used (%), to avoid
changes in rendering that might result.

Signed-off-by: Alex Willmer <alex@moreati.org.uk>
3 years ago
Amin Vakil 0c101f3f76
Add epoch_int in date_time facts (#73822)
* Add unit test

* Add changelog
3 years ago
Brian Coca 84e473a26e
All lookups ported to config system (#74108)
* all lookups to support config system

 - added get_options to get full dict with all opts
 - fixed tests to match new error messages
 - kept inline string k=v parsing methods for backwards compat
 - placeholder depredation for inline string k=v parsing
 - updated tests and examples to also show new way
 - refactored and added comments to most custom k=v parsing
 - added missing docs for template_vars to template
 - normalized error messages and exception types
 - fixed constants default
 - better details value errors

Co-authored-by: Felix Fontein <felix@fontein.de>
3 years ago
abikouo 29aea9ff34
constructed - Add keyed_groups suboptions 'default_value' and 'trailing_separator' (#74005)
* Support omitting the trailing separator when a dictionary key's value is an empty string

* Support a default value when the value used in the group name is an empty string

* Add tests

* change log
3 years ago
Rick Elrod bd1acb74c8
[playbook/play.py] Increase error test coverage (#74217)
Change:
- Mostly increase error coverage for various conditions in play.py
- Also fix a string in an error, where get_name() was called before
  self.name was read in, so get_name() was always ''.

Test Plan:
- new tests

Signed-off-by: Rick Elrod <rick@elrod.me>

* Fix regex for py2 and py3

Signed-off-by: Rick Elrod <rick@elrod.me>

* py2 hates me

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Sloane Hertel ce96591313
Remove deprecated cache interfaces (#74198)
* update unit test
* Remove FactCache 'update' method
3 years ago
Brian Coca 39bd8b99ec
async_wrapper more info on end (#74199)
be consistent on information returned
 normalize 'return functions'
 fix unit test
 add a bit more context on some failures
3 years ago
Matt Clay b752d07163 Overhaul ansible-test container management.
This brings ansible-test closer to being able to support split controller/remote testing.
3 years ago
Guillermo Adrián Molina 9c506031fa
Solaris: Correct version check in svcadm_supports_sync API (#73860)
Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Brian Coca b07a78b4ba
remove deprecated connection password functions (#74155)
* they were moved from connecitons to become plugins
* fixed clog, removed sanity ignore
* fixed tests to use become functions
3 years ago
Amin Vakil 846c2d1ed3
Fix comment in iptables unit test (#74061) 3 years ago
Matt Davis a84c1a5669
add --offline option to galaxy collection verify (#74040)
* --offline allows in-place verify for installed collections with manifests
* manifest hash, collection name, version, and path are now always displayed
* test updates
3 years ago
Felix Fontein af7f3fc266
Revert "Add duplicated set filter and documentation (#72729)" (#74053)
This reverts commit 99a6627c60.

* ci_complete
3 years ago
Matt Martz 88d6a72178
Temporarily disable strategy units (#74048) 3 years ago
Baptiste Mille-Mathias 99a6627c60
Add duplicated set filter and documentation (#72729)
Co-authored-by: Kerry <kerry@flatline-studios.com>
3 years ago
Sam Doran abacf6a108
Use ArgumentSpecValidator in AnsibleModule (#73703)
* Begin using ArgumentSpecValidator in AnsibleModule

* Add check parameters to ArgumentSpecValidator

Add additional parameters for specifying required and mutually exclusive parameters.
Add code to the .validate() method that runs these additional checks.

* Make errors related to unsupported parameters match existing behavior

Update the punctuation in the message slightly to make it more readable.
Add a property to ArgumentSpecValidator to hold valid parameter names.

* Set default values after performining checks

* FIx sanity test failure

* Use correct parameters when checking sub options

* Use a dict when iterating over check functions

Referencing by key names makes things a bit more readable IMO.

* Fix bug in comparison for sub options evaluation

* Add options_context to check functions

This allows the parent parameter to be added the the error message if a validation
error occurs in a sub option.

* Fix bug in apply_defaults behavior of sub spec validation

* Accept options_conext in get_unsupported_parameters()

If options_context is supplied, a tuple of parent key names of unsupported parameter will be
created. This allows the full "path" to the unsupported parameter to be reported.

* Build path to the unsupported parameter for error messages.

* Remove unused import

* Update recursive finder test

* Skip if running in check mode

This was done in the _check_arguments() method. That was moved to a function that has no
way of calling fail_json(), so it must be done outside of validation.

This is a silght change in behavior, but I believe the correct one.

Previously, only unsupported parameters would cause a failure. All other checks would not be executed
if the modlue did not support check mode. This would hide validation failures in check mode.

* The great purge

Remove all methods related to argument spec validation from AnsibleModule

* Keep _name and kind in the caller and out of the validator

This seems a bit awkward since this means the caller could end up with {name} and {kind} in
the error message if they don't run the messages through the .format() method
with name and kind parameters.

* Double moustaches work

I wasn't sure if they get stripped or not. Looks like they do. Neat trick.

* Add changelog

* Update unsupported parameter test

The error message changed to include name and kind.

* Remove unused import

* Add better documentation for ArgumentSpecValidator class

* Fix example

* Few more docs fixes

* Mark required and mutually exclusive attributes as private

* Mark validate functions as private

* Reorganize functions in validation.py

* Remove unused imports in basic.py related to argument spec validation

* Create errors is module_utils

We have errors in lib/ansible/errors/ but those cannot be used by modules.

* Update recursive finder test

* Move errors to file rather than __init__.py

* Change ArgumentSpecValidator.validate() interface

Raise AnsibleValidationErrorMultiple on validation error which contains all AnsibleValidationError
exceptions for validation failures.

Return the validated parameters if validation is successful rather than True/False.

Update docs and tests.

* Get attribute in loop so that the attribute name can also be used as a parameter

* Shorten line

* Update calling code in AnsibleModule for new validator interface

* Update calling code in validate_argument_spec based in new validation interface

* Base custom exception class off of Exception

* Call the __init__ method of the base Exception class to populate args

* Ensure no_log values are always updated

* Make custom exceptions more hierarchical

This redefines AnsibleError from lib/ansible/errors with a different signature since that cannot
be used by modules. This may be a bad idea. Maybe lib/ansible/errors should be moved to
module_utils, or AnsibleError defined in this commit should use the same signature as the original.

* Just go back to basing off Exception

* Return ValidationResult object on successful validation

Create a ValidationResult class.
Return a ValidationResult from ArgumentSpecValidator.validate() when validation is successful.
Update class and method docs.
Update unit tests based on interface change.

* Make it easier to get error objects from AnsibleValidationResultMultiple

This makes the interface cleaner when getting individual error objects contained in a single
AnsibleValidationResultMultiple instance.

* Define custom exception for each type of validation failure

These errors indicate where a validation error occured. Currently they are empty but could
contain specific data for each exception type in the future.

* Update tests based on (yet another) interface change

* Mark several more functions as private

These are all doing rather "internal" things. The ArgumentSpecValidator class is the preferred
public interface.

* Move warnings and deprecations to result object

Rather than calling deprecate() and warn() directly, store them on the result object so the
caller can decide what to do with them.

* Use subclass for module arg spec validation

The subclass uses global warning and deprecations feature

* Fix up docs

* Remove legal_inputs munging from _handle_aliases()

This is done in AnsibleModule by the _set_internal_properties() method. It only makes sense
to do that for an AnsibleModule instance (it should update the parameters before performing
validation) and shouldn't be done by the validator.

Create a private function just for getting legal inputs since that is done in a couple of places.

It may make sense store that on the ValidationResult object.

* Increase test coverage

* Remove unnecessary conditional

ci_complete

* Mark warnings and deprecations as private in the ValidationResult

They can be made public once we come up with a way to make them more generally useful,
probably by creating cusom objects to store the data in more structure way.

* Mark valid_parameter_names as private and populate it during initialization

* Use a global for storing the list of additonal checks to perform

This list is used by the main validate method as well as the sub spec validation.
3 years ago
Abhijeet Kasurde 3811fddede Amazon: Fix distribution facts for older release
Ansible can gather distribution facts for older Amazon Linux
with /etc/os-release data.

Fixes: #73946

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Matt Martz 78f34786dd
Send callbacks directly from the TaskExecutor instead of TaskResults masquerading as callbacks (#73927) 3 years ago
Abhijeet Kasurde fb66b4ffbc
distribution: Add Amazon Linux distribution facts (#73767)
* Update Amazon Linux Distribution facts gathering logic
* Update tests

Fixes: #73742

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Brian Coca 935528e22e
finish migrating ssh plugin to config system (#73708)
* finish migrating ssh plugin to config system

  fixes #72739
  fixes #57220

* fix connection detection in reset
* correct options for connection meta reset

Co-authored-by: David Shrewsbury <Shrews@users.noreply.github.com>
3 years ago
Matt Davis d0e991e892
Clarify CLI version number as core version (#72287)
* clarify CLI version number as core version

* reduce confusion with `ansible` PyPI package >= 2.10 drifting from core version

* fix units
3 years ago
Alexei Znamensky 920b68f5f2
Fixed/improved regular expresssion for collection names (#73577)
* added changelog fragment
* added a couple of tests to coll name validation
3 years ago
Sam Doran 2377a0a776
Improve ArgumentSpecValidator unit tests (#73642)
* Add more scenarios to basic valid testing
* Update invalid tests
* Fix test for Python 2
* Condense data
* Add tests for missing required and invalid-elements
* Update aliases tests
* Add invalid scenarios for aliases
* Add tests for _add_error() method
* Fix sanity test failure
3 years ago
Sloane Hertel 00bd0b893d
ansible-galaxy - set the cache file after getting all collection versions (#73557)
* Manage the in-memory cache in _call_galaxy but let the caller set the file cache after getting paginated results

* Add a test for caching successful and not caching unsuccessful paginated results

Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
3 years ago
Sviatoslav Sydorenko f327e65d11
Use iskeyword and str.isidentifier for "is FQCN" (#73279)
* Use valid FQCN in test_verbosity_arguments

* Use iskeyword and str.isidentifier for "is FQCN"
3 years ago
Sam Doran b6811dfb61
Add argument spec validator (#73335)
Add argument spec validator class
3 years ago
Brian Coca ec8a556538
only add data when there is data to add (#54559)
Only add data when there is data to add

  also avoid clobbering existing data with empty file
  fixes #45843

* remove redundant code, update comments
* fix mock dataloader, original does not return None
* added test
3 years ago
Matt Davis 4c5ce5a1a9
module compat for py3.8+ controller (#73423)
* module compat for py3.8+ controller

* replaced internal usages of selinux bindings with internal ctypes binding (allows basic selinux operations from any Python interpreter), plus tests

* added new respawn_module API to allow modules to import Python packages that are only available under a well-known interpreter, plus tests

* added respawn logic to modules that need Python libs from a specific system interpreter (apt, apt_repository, dnf, yum)

minimize internal HAVE_SELINUX usage

spurious junk

pep8

* pylint fixes

* add RHEL8 Python 3.8 testing

* more pylint

* import sanity

* unit tests

* changelog update

* fix a bunch of stuff

* tweak changelog

* fix setup_rpm_repo on EL8

* misc sanity/test fixes

* misc feedback tweaks

* fix import fallback in test module

* fix selinux MU test

* fix dnf tests to avoid python-dependent test packages

* add trailing LFs to aliases

* fix yum tests to avoid test package with Python deps

* hack create_repo for EL6 to create noarch package
3 years ago
Sam Doran 2f5c83dfb1
Add AlmaLinux to the family of Red Hat-like operating systems (#73541)
* Add changelog and fixtures for AlmaLinux support

Co-authored-by: Christoph Schug <com+github@schug.net>
3 years ago
Shane McDonald 67f5bb39c7
galaxy - add format options for collection list (#73474)
* Include all collections in single json object / yaml document
* Add tests
* For galaxy list yaml/json output, use dictionary of dictionaries instead of list
* Add tests for listing single collection in yaml / output format
* --output -> --format
* Add explicit test for listing collection in human format
* Fix bug where empty json object was emitted + add test
3 years ago
Sloane Hertel 9759e0ca49
add option to upgrade collections (#73336)
* Add a flag to ansible-galaxy to update collections


Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
3 years ago
Rick Elrod 9a9272305a
Correct pkg_mgr for Fedora-derived OSTree distros (#73445)
Change:
- Remove check that states that only Fedora can be an OSTree
  distribution.
- This allows us to correctly return "atomic_container" as the pkg_mgr
  fact for RHEL for Edge, Fedora/RHEL/CentOS Atomic Host, etc.

Test Plan:
- Created local RHEL for Edge image and tested against it.
- Tested against regular RHEL 8 and still got `dnf` as expected.
- Tested against RHEL 7 Atomic Host and got `atomic_container` now.
- New unit tests.

Tickets:
- Fixes #73084

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Alexander Sowitzki 218f5c3648
user - Prevent user fact lookup failure if LOGNAME is set (#17029) (#73439)
The `UserFactCollector` queries the user login name via
`getpass.getuser()` and looks up the corresponding entry
in the password database.
The login name may differ from the actual user name,
eg. if the `LOGNAME` env variable is set. The lookup
fails in this case. Added a fallback in this case that
tries to get the entry via the user ID.
3 years ago
Sviatoslav Sydorenko 595413d113
Replace the inhouse collection dependency resolver with `resolvelib`
PR #72591

This change:

  * Adds an artifacts manager that abstracts away extracting the
    metadata from artifacts, downloading and caching them in a
    temporary location.

  * Adds `resolvelib` to direct ansible-core dependencies[0].

  * Implements a `resolvelib`-based dependency resolver for
    `collection` subcommands that replaces the legacy
    in-house code.

    This is a dependency resolution library that pip 20.3+ uses
    by default. It's now integrated for use for the collection
    dependency resolution in ansible-galaxy CLI.

  * Refactors of the `ansible-galaxy collection` CLI.
    In particular, it:

      - reimplements most of the `download`, `install`, `list` and
        `verify` subcommands from scratch;

      - reuses helper bits previously moved out into external modules;

      - replaces the old in-house resolver with a more clear
        implementation based on the resolvelib library[0][1][2].

  * Adds a multi Galaxy API proxy layer that abstracts accessing the
    version and dependencies via API or local artifacts manager.

  * Makes `GalaxyAPI` instances sortable.

  * Adds string representation methods to `GalaxyAPI`.

  * Adds dev representation to `GalaxyAPI`.

  * Removes unnecessary integration and unit tests.

  * Aligns the tests with the new expectations.

  * Adds more tests, integration ones in particular.

[0]: https://pypi.org/p/resolvelib
[1]: https://github.com/sarugaku/resolvelib
[2]: https://pradyunsg.me/blog/2020/03/27/pip-resolver-testing

Co-Authored-By: Jordan Borean <jborean93@gmail.com>
Co-Authored-By: Matt Clay <matt@mystile.com>
Co-Authored-By: Sam Doran <sdoran@redhat.com>
Co-Authored-By: Sloane Hertel <shertel@redhat.com>
Co-Authored-By: Sviatoslav Sydorenko <webknjaz@redhat.com>

Signed-Off-By: Sviatoslav Sydorenko <webknjaz@redhat.com>
3 years ago
Brian Coca 2b0cd2c13f
use correct executable and options in all cases (#73323)
Use correct ssh executable and options in all cases on connection plugin

  * Also nicer naming/comments

Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
3 years ago
Alexander Sowitzki e6da544310 Let `command` always return stdout & stderr (#73004)
The `command` module does not return stdout & sterr when calling
a non existing executable or an unknown exception arises. This fix
lets the module return empty byte strings in those cases.
3 years ago
Joshua Bayfield 823c72bcb5
Shadow input for encrypt_string by default unless asked (fixes #71618) (#73263)
* Shadow input for encrypt_string by default unless asked (fixes #71618)
3 years ago
Jordan Borean bc60d8ccda
Galaxy - make versions list consistent across versions (#72932)
* Galaxy - make versions list consistent across versions

* Fix up unit tests
3 years ago
Sam Doran e8d4b62b41
Fix YAML error message when error is at the end of the file (#73241)
* Fix YAML error message when error is at the end of the file

If a YAML file fails to load due to a syntax error in a file, or there is an error in the last line of a
file, PyYAML reports the last line number of the file as the index where the error occurred.

When reading the file lines, we use that index to the get the relevant line.  If the index value is out
of range, the relevant line is lost for error reporting.

Subtract one from the index value to avoid the IndexError in this specific scenario. It is possible
to still get an IndexError, which will be handled as it is currently.

* Update existing tests and add new tests
3 years ago
Sam Doran df451636e7
facts - properly report virtualization facts for Linux guests on bhyve (#73204) 3 years ago
Rick Elrod 7f0eb7ad79
[facts] Differentiate CentOS vs CentOS Stream (#73034)
Change:
- On CentOS Stream, make distribution_release be "Stream"
- On CentOS Core, it continues to be "Core"
- Implement custom distribution file parser for CentOS, so we can look
  for "CentOS Linux" and "CentOS Stream"
- Two new fixtures introduced (CentOS Linux 8.1 and CentOS Stream 8)
- Removed two dicts from `Distribution` class that were seemingly not
  used anywhere.

Test Plan:
- ci_complete
- New test fixtures

Tickets:
- Fixes #73027

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Alexander Sowitzki 3e8c8cd536 Make `test_adhoc` succeed from within a git checkout
The test currently only expects the literal `ansible` followed
by a semver in the first output line of `ansible --version`.
When running from within a git checkout, additional information
like the currently checkout branch are attached, which lets
the test fail. This commit allows arbitrary information to
follow the semver.
3 years ago
Alexander Sowitzki 6459fbb7bc Make `test_prepare_multipart` succeed on non Debian distros
`test_prepare_multipart` fails in non Debian environments since
Debian installations map the file ending `.key` to the MIME type
`application/pgp-keys`, which is not IANA conformant. This commit
explicitly sets the corresponding file type to
`application/octet-stream` and adjusts the expected serialized
result.
3 years ago
Martin Zimmermann be59caa59b
iptables: Added set module/match_set support (#72984) 3 years ago
Abhijeet Kasurde 25792d2388
galaxy: handle plus sign in user token appearing in role url (#73057)
Fixes: #45475

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
3 years ago
Rick Elrod 20509b6507
[facts] fix version facts on FreeBSD RC/PRERELEASE (#73020)
Change:
- The FreeBSD release can contain -RC or -PRERELEASE in addition to
  -RELEASE, -STABLE, or -CURRENT.

Test Plan:
- Added new fixed from an RC version of TrueNAS which uses a -PRERELEASE
  version of FreeBSD.

Tickets:
- Fixes #72331

Signed-off-by: Rick Elrod <rick@elrod.me>
3 years ago
Brian Coca 932ba36160
ensure unsafe writes fallback (#70722)
* Ensure we actually fallback to unsafe_writes when set to true

 add integration test
 add fix for get_url not passing the parameter from args
3 years ago
Brian Coca d22804c4fb
saner path dir management (#72648)
* saner path dir management

   fixes #72628

   ensure we always store paths w/o a_c

Co-authored-by: Sloane Hertel <19572925+s-hertel@users.noreply.github.com>
4 years ago
Martin Zimmermann 83fb24b923
iptables: Adding multiport module support (#72928) 4 years ago
Martin Krizek 1b70260d5a
Add implicit role_complete block instead of role._eor (#72208)
Co-authored-by: Matt Martz <matt@sivel.net>

Fixes #69848
4 years ago
Sven Wegener 08cc6edc64
vault: Read stdin data as binary on python3 (#52229)
On python3 sys.stdin is an encoded file object that does not support
reading raw binary data. Use the supplied buffer object to do so.

Signed-off-by: Sven Wegener <sven.wegener@inovex.de>

Co-authored-by: Sven Wegener <sven.wegener@inovex.de>
4 years ago
David Shrewsbury be2c376ab8
Extract embedded function to RoleMixin method and add tests (#72754)
* Add changelog
* Simplify return
4 years ago
Pilou b464d18fd1
AnsibleModule.set_mode_if_different: handle symlink is in a sticky directory (#45198)
* file: add symlink is in a sticky directory tests
* file: handle symlink in a sticky directory

Co-Authored-By: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>

* Add changelog and fix unit test
The builtins import was removed since it was unused, but it is now needed.
4 years ago
Abhijeet Kasurde a223ea5185
distribution - handle NetBSD OS Family (#70799)
Fixes: #43739

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Martin Krizek ae08c6a639
Ensure Ansible's unique filter preserves order (#67856)
Fixes #63417
4 years ago
Matt Martz f8ef34672b
Provide better decryption errors for single vault values (#72362)
Fixes #72276
Fixes #72281
4 years ago
Sam Doran e889b1063f
arg_spec - rework _check_arguments() (#72447)
* Move _syslog_facitily to __init__
  No good reason it should not be set for each object

* Move internal property setting to private method
* Create check_arguments() function
* Remove unused import
* Rename function to better match its behavior
  Change the behavior to return a set, either empty or populated, with unsupported keys.
  Accept legal_inputs as optional which will not required calling handle_aliases before calling
  get_unsupported_parameters().

* Add changelog
* Rework function behavior and documentation
  I realized I missed the original intent of this method when moving it to a function. It
  is meant to compared the parameter keys to legal inputs always, not compare
  parameter keys to argument spec keys, even though the argument spec keys should
  be a subset of legal inputs.

* Add tests
* Fix typo.
* Set internal properties when handling suboptions
4 years ago
Jordan Borean de5858f48d
Added caching mechanism for Galaxy API requests (#71904)
* Added caching mechanism for Galaxy API requests

* Add cache options and split up code

* Added unit tests

* Fix sanity test

* Use modified date and fix up caching for explicit servers

* Make sure credentials are not in cached server name

* Added test for getting updated cache version

* Changes from review
4 years ago
Amin Vakil c1da427a5e
iptables: Reorder comment postition (#71496)
* Reorder comment postition

* Add comment unit test

* Fix unit test

* Fix unit test

* Add changelog

* Add paramaters which would be problematic without this fix

* Fix typo

* Fix unit test

* Fix unit test
4 years ago
Martin Krizek a2593b5e27 CLI - Specify jinja version in --version output 4 years ago
Alexei Znamensky 5654de6fce
Return error if cwd directory does not exist (#72390)
* Return warning or error if cwd directory does not exist, in AnsibleModule.run_command()
4 years ago
Brian Coca cb94c0cc55
added timeout options to adhoc and console (#71230)
* added timeout options to adhoc and console

* added test

* fix typosesz

* fix conflict

* task_timeout

* fix timeout option, added extra vars to console

* actually use right cli switch .. DUH!

* added timeout to include 'valid' but ignored keys

* fix default

* fixes per review
4 years ago
Brian Coca e05c62547b
run playbook from collections (#67435)
* fixes for collection playbooks

 - add fqcn invocation, also handles extensions
 - bring import_playbook into new normal
 - avoid adding collection playbooks to adjacency
 - deal with extensions or lack of em
 - added tests
 - fix bugs with multiple playbooks supplied
 - unicode/bytes/native fixes
 - fix modulenotfound for < py3.7
 - tests
4 years ago
Sam Doran 8f9cf456b0
url lookup - set default user agent (#72324)
* Add unit tests
* Add note about when default changed
4 years ago
Sloane Hertel 8b07d46166
Add a toggle for the leading separator for keyed_groups (#60882)
* Add a toggle for the leading separator for keyed_groups if no prefix is given

* changelog

* Add tests for backward compatibility and the new toggle
4 years ago
Matt Davis 83909bfa22
Remove ansible-galaxy login (#72288)
* GitHub is removing the underlying API used to implement the `login` command. Since the general consensus seems to be that relatively nobody currently uses this command (in favor of explicit token passing), support was simply removed for interactive login. If a future need arises, this command should be reimplemented via OAuth Device Auth Grants.
* login or role login commands now produce a fatal error with a descriptive message
* updated 2.10 and 2.11 porting guide entries

* remove dead code/config, update messages and porting guides
4 years ago
Rick Elrod 3b40c6f3b7
[config] coerce more to string when 'type: str' (#72172)
Change:
- When a plugin defines `type: str` on a parameter, treat more kinds of
  input as a string instead of whatever it is parsed as.

Test Plan:
- New unit tests
- CI

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
dberg1 cdf62edc65
service_facts: return service state information on AIX (#72073)
* service_facts: return service state information on AIX

AIX uses the System Resource Controller (SRC) to manage services.
See https://www.ibm.com/support/knowledgecenter/ssw_aix_72/osmanagement/sysrescon.htm
Use lssrc command on AIX to return service state information.


Co-authored-by: dberg1 <dberg1@github.com>
4 years ago
Jordan Borean caba47dd3f
Add support for GSSAPI/Kerberos to urls.py (#72113)
* Add support for GSSAPI/Kerberos to urls.py

* Test out changes with the latest test container

* Get remote hosts working

* Fix up httptester_krb5_password reader

* Fix tests for opensuse and macOS

* Hopefully last lot of testing changes

* Dont do CBT on macOS

* Fixes from review
4 years ago
Rick Elrod 0332046699
[ansible-test] attempt to work around podman (#72096)
Change:
- podman > 2 && < 2.2 does not support "images --format {{json .}}"
- podman also now outputs images JSON differently than docker
- Work around both of the above.

Test Plan:
- Tested with podman 2.0.6 in Fedora 31.

Signed-off-by: Rick Elrod <rick@elrod.me>
Co-authored-by: Sviatoslav Sydorenko <wk.cvs.github@sydorenko.org.ua>
4 years ago
Evan Van Dam 3db08adbb1
Add optional attribute arg for min and max filters (#50909)
* Pass **kwargs to min and max filters

* Use the jinja2 filters if available

* Add unit tests

* Add examples to docs passing attribute
4 years ago
Rick Elrod 709484969c
sysctl/openbsd fact fixes (#72070)
Change:
- Use `sysctl -n` for openbsd uptime information
- Allow `get_sysctl()` to account for multi-line sysctl settings
- Add unit tests for `get_sysctl()`

Test Plan:
- New unit tests

Tickets:
- Fixes #71968
- Refs #72025
- Refs #72067

Signed-off-by: Rick Elrod <rick@elrod.me>
Co-authored-by: Brian Coca <brian.coca+git@gmail.com>
Co-authored-by: Brian Coca <bcoca@ansible.com>
4 years ago
Matt Martz fb03ac7019
Add libyaml info to version output, and restore git info (#71948)
* Add libyaml info to version, restore git functionality

* Add clog fragment

* Update tests to reflect new version output
4 years ago
Felix Fontein 1107aace1b
Add deprecation collection name to plugin options (#71735)
* Add changelog fragment.

* Use correct field that's expected by lib/ansible/cli/__init__.py..

* Add basic unit tests.
4 years ago
Christian Loos ea119d3089
fix distribution fact for SLES4SAP (#71559)
b6b238a fixed the SLES4SAP detection, which was at this time ok.
Sadly Suse changed with SLES 15 the /etc/os-release file, so the above
change will no longer work.

This commit updates the SLES4SAP detection regarding
https://www.suse.com/support/kb/doc/?id=000019341.

The symlink realpath is matched with endswith, because in SLES 12+ the
link target is SLES_SAP.prod, but in SLES 11 the link target is
SUSE_SLES_SAP.prod.
4 years ago
Jorge Vallecillo 94522b7c10
Fix typos (#71970) 4 years ago
Rick Elrod 5cd489af06
Let get_file_attributes() work without `lsattr -v` (#71845)
* Let get_file_attributes() work without `lsattr -v`

Change:
- module_utils's get_file_attributes() expects `lsattr -v` to work, but
  in some cases, it may not.
- The function now takes an optional include_version bool parameter,
  which removes this expectation.
- Places where we call get_file_attributes() without using the 'version'
  it returns, we now call it with include_version=False.

Test Plan:
- New unit tests

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Abhijeet Kasurde 173091e2e3
distro: Add support for Pardus distribution (#71663)
Fixes: #71636

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Matt Davis e813b0151c
fix coverage output from synthetic packages (#71727)
* fix coverage output from synthetic packages

* synthetic packages (eg, implicit collection packages without `__init__.py`) were always created at runtime with empty string source, which was compiled to a code object and exec'd during the package load. When run with code coverage, it created a bogus coverage entry (since the `__synthetic__`-suffixed `__file__` entry didn't exist on disk).
* modified collection loader `get_code` to preserve the distinction between `None` (eg synthetic package) and empty string (eg empty `__init__.py`) values from `get_source`, and to return `None` when the source is `None`. This allows the package loader to skip `exec`ing things that truly have no source file on disk, thus not creating bogus coverage entries, while preserving behavior and coverage reporting for empty package inits that actually exist.

* add unit test
4 years ago
Matt Martz 48f12c14e9
AnsibleVaultEncryptedUnicode should be considered a string (#71609)
* AnsibleVaultEncryptedUnicode should be considered a string

* linting fix

* clog frag
4 years ago
Martin Krizek fbdfb85c20
Remove duplicate unit test (#71488)
test_dict_undefined_values is a duplicate of test_dict_undefined_values_is_defined.
It seems originally test_dict_undefined_values was supposed
to do what test_dict_undefined_values_bare does so it is safe to remove.
4 years ago
Matt Martz fdf5dd02b3
Updates for password hashing (#71120)
* Validate salt when using crypt. Respect salt_size in password lookup. Repair salt for bcrypt. Fixes #71107. Fixes #53750. Fixes #36129.

* Handle algorithms we don't know about, and make sure to return the salt

* Account for old passlib

* Add tests for salt constraints

* Add changelog fragment

* Add test for #36129
4 years ago
Jordan Borean 8897d7e2ff
powershell - fix nested CLIXML parser (#71412) 4 years ago
Sam Doran 888be697cb
Revert "Change default file permissions so they are not world readable (#70221)" (#71231)
* Revert "Change default file permissions so they are not world readable (#70221)"

This reverts commit 5260527c4a.

* Revert "Fix warning for new default permissions when mode is not specified (#70976)"

This reverts commit dc79528cc6.
4 years ago
Toshio Kuratomi fb144c4414
Update ansible doc formats (#71070)
* Fix tty_ify bugs and refactor

* Move tty_ify() and supporting attributes to the DocCLI class as that's
  the only thing using it.
* Add unittest for the code.
* Fix a bug where the substitution macros can be detected when they are
  a part of another word.
* Add support for L(), R(), and HORIZONTALLINE which were added to the
  website docs many years ago.

* Update test/units/cli/test_doc.py

Co-authored-by: Matt Clay <matt@mystile.com>

Co-authored-by: Matt Clay <matt@mystile.com>
4 years ago
Rick Elrod 0d7c144ce4
Allow macOS ACLs to work for unpriv -> unpriv (#70785)
Change:
- Use `chmod +a` in the fallback chain to allow MacOS to use ACLs to
  allow an unprivileged user to become an unprivileged user.

Test Plan:
- CI, new tests

Tickets:
- Fixes #70648

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Matt Martz 4e27569347
Add more include and yaml parsing tests (#70506)
These additional tests should provide coverage for features currently tested by the postgres incidental tests.
4 years ago
Rick Elrod 7f62a9d7b5
Make cache adjudicator's flush call plugin flush (#70987)
Change:
- Previously CachePluginAdjudicator#flush only removed entries from the
  cache backend that it knew about by using them earlier. Now it calls
  the underlying plugin's flush() method.

Test Plan:
- New unit tests

Tickets:
- Fixes #68770

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Sam Doran c4f442ed5a
facts - fix incorrect time for some date_time_facts (#70665)
The iso8601_micro and iso8601 facts incorrectly called now.utcnow(), resulting
in a new timestamp at the time it was called, not a conversion of the previously
stored timestamp.

Correct this by capturing the UTC timestamp once then calculating the local
time using the UTC offset of the current system.

* Use time.time() for getting the current time
* Convert from that stored epoch timestamp to local and UTC times
* Used existing timestamp for epoch time
* Add unit tests that validate the formate of the return value rather than an exact value since mocking time and timezone is non-trivial
4 years ago
Rick Elrod 14dc4de424
Update docs for --tags default, and add some tests (#70939)
Change:
- Clarify that not passing `--tags` will cause `ansible_run_tags` to
  default to `["all"]`.
- Add some extra coverage around `ansible_run_tags`

Test Plan:
- New integration and unit tests

Tickets:
- Fixes #69619

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Brian Coca 1223ce656a
reset logging to INFO (#70878)
- due to CVE-2019-14846
 - also added comments and test to avoid 'oportunistic' reversion
4 years ago
Matt Davis 4c0af6c808
fix internal cases of actions calling unqualified module names (#70818)
* fix internal cases of actions calling unqualified module names

* add porting_guide entry
* misc other fixes around action/module resolution broken by redirection

ci_complete

* Update docs/docsite/rst/porting_guides/porting_guide_2.10.rst

Co-authored-by: Rick Elrod <rick@elrod.me>

* Update docs/docsite/rst/porting_guides/porting_guide_2.10.rst

Co-authored-by: Rick Elrod <rick@elrod.me>

* address review feedback

* pep8

* unit test fixes

* win fixes

* gather_facts fix module args ignores

* docs sanity

* pep8

* fix timeout test

* fix win name rewrites

Co-authored-by: Rick Elrod <rick@elrod.me>
4 years ago
Abhijeet Kasurde e439194c8c
basic: Add name of aliases in error message (#69427)
With this patch, user will be notified with available aliases
of arg parameter.

Fixes: #58752

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Sam Doran 5260527c4a
Change default file permissions so they are not world readable (#70221)
* Change default file permissions so they are not world readable

CVE-2020-1736

Set the default permissions for files we create with atomic_move() to 0o0660. Track
which files we create that did not exist and warn if the module supports 'mode'
and it was not specified and the module did not call set_mode_if_different(). This allows the user to take action and specify a mode rather than using the defaults.

A code audit is needed to find all instances of modules that call atomic_move()
but do not call set_mode_if_different(). The findings need to be documented in
a changelog since we are not warning. Warning in those instances would be frustrating
to the user since they have no way to change the module code.

- use a set for storing list of created files
- just check the argument spac and params rather than using another property
- improve the warning message to include the default permissions
4 years ago
David Shrewsbury bf98f031f3
Sanitize URI module keys with no_log values (#70762)
* Add sanitize_keys() to module_utils.

* More robust tests

* Revert 69653 change

* Allow list or dict

* fix pep8

* Sanitize lists within dict values

* words

* First pass at uri module

* Fix insane sanity tests

* fix integration tests

* Add changelog

* Remove unit test introduced in 69653

* Add ignore_keys param

* Sanitize all-the-things

* Ignore '_ansible*' keys

* cleanup

* Use module.no_log_values

* Avoid deep recursion issues by using deferred removal structure.

* Nit cleanups

* Add doc blurb

* spelling

* ci_complete
4 years ago
Matt Martz 96b74d3e0b
Ensure single vaulted values aren't counted as sequences. Fixes #70784 (#70786) 4 years ago
Abhijeet Kasurde 4f96f9826c
distribution: Add support for DragonFly (#70748)
partially fixes #43739

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Rick Elrod 69472a5f8d
Refactor _fixup_perms2 to remove way-nested logic (#70701)
Change:
- Refactoring to make it harder to get wrong and easier to read.
- Generalize become_unprivileged tests and fix some that never worked
  but also never failed.

Test Plan:
- CI, new units/integration tests

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Eduard Rozenberg 566c5e6ce1
Handle Slackware OS version strings containing a plus (“+”) (#68142)
A couple of years ago Slackware -current began using a plus (“+”) at the end of the distribution version string to indicate a future version work-in-progress.

Rearrange distribution_files unit tests to easily support more tests
  - add conftest with common fixtures 
  - use parametrize for testing multiple scenarios

* Add changelog
* Add unit tests for Slackware distribution parsing
* Use correct fixtures for Slackware
Data comes from /etc/slackware-version

Co-authored-by: Sam Doran <sdoran@redhat.com>
Co-authored-by: <Eduard Rozenberg <eduardr@pobox.com>>
4 years ago
Matt Davis c616e54a6e
refactor Python module_utils locator (#70610)
* refactor Python module_utils locator

* no longer recursive
* embed special-case module code internally
* share common code between collections/not cases
* fixes #70134
* properly support subpackage redirection
* adds support for FQCN redirect targets used by migration (expands to FQ Python name)
* add tests

* add changelog
4 years ago
Abhijeet Kasurde 055871cbb8
api: time.clock compatible code (#70650)
time.clock is removed in Python 3.8. Add time.clock
compatible code.

Fixes: #70649

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Mykola Grygoriev fe86a93482
Add a new `date_time` fact to provide DST timezone
PR #70449
4 years ago
Jordan Borean e22e103cdf
winrm - Added kinit_args to control the args for kinit calls (#70624) 4 years ago
jabdr 0690b68bd3
Support datetime.date object in module result (#70595)
* Support datetime.date object in module result

Fixes #70583

* change blank lines for pep8 sanity test
4 years ago
Mark Chappell 8d160b1881
Remove remaining examples of 1.1.1.1 (#70552)
* Remove remaining examples of 1.1.1.1

* Update ec2_group.py
4 years ago
Brian Coca cf89ca8a03
Make filter type errors 'loop friendly' (#70417)
- ensure we preserve the typeerror part of the exception so loop defereed error handling
 can postpone those caused by undefined variables until the when check is done.
 - fix tests to comply with the 'new normal'

 - human_to_bytes and others can issue TypeError not only on 'non string'
 but also bad string that is not convertable.

Co-authored-by: Sloane Hertel <shertel@redhat.com>

Co-authored-by: Sloane Hertel <shertel@redhat.com>
4 years ago
Felix Fontein 24dcaf8974
plugin loader: return collection name; ansible-doc: handle ansible.builtin correctly (#70026)
* Determine collection in plugin loader.

* Fix test.

* Use PluginPathContext objects in PluginLoader._plugin_path_cache instead of tuples.
4 years ago
Rick Elrod f3ef4ed076
Remove some constants.py deprecated items (#70466)
Change:
- Remove mk_boolean
- Remove BECOME_METHODS
- Remove get_config

Test Plan:
- CI, removed mk_boolean unit tests

Tickets:
- Fixes #69678

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Abhijeet Kasurde f5037314e3
sanity: remove ansible-bad-function (#70431)
* Updated docs and ignore.txt
* Replaced with correct function calls

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Abhijeet Kasurde a8ae8f4d72
setup: Handle CIFS share with backward slash (#70006)
CIFS can be mounted using backward slash as well in /etc/fstab like

\\Windows\share /data/ cifs credentials=/root/.creds 0 0

Handle this condition while gather mount information in Linux.

Fixes: #48813

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Martin Krizek b05e00e99a
Fix delegate_facts with interpreter not being set (#70293)
Fixes #70168

ci_complete

Co-authored-by: Brian Coca <bcoca@users.noreply.github.com>
Co-authored-by: Matt Clay <matt@mystile.com>
4 years ago
Hideki Saito 2d59e548f6
Improve ansible-galaxy STDOUT messages for collections (#70040)
- Fix issue #70010
- Add installation successful message
- This feature targets "collection" sub-command and does not affect "role" sub-command

Signed-off-by: Hideki Saito <saito@fgrep.org>
4 years ago
s-hamann e39a9bf583
Add support for Parrot Linux, a Debian derivate (#69158)
Co-authored-by: black <invalid>
4 years ago
jctanner b019029bf3
Add intentional unit tests for basic._set_cwd and common.dict_merge (#70283)
* Add unit tests for basic._set_cwd

* incidental coverage for dict_merge

* add test for async stderr inclusion
4 years ago
Abhijeet Kasurde 3fe48ecba2
Add collection path in CLI version info (#68633)
This will provide user default path of collection

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
4 years ago
Rick Elrod 0073ab5fa6
Nuke strategy.SharedPluginLoaderObj, depr. 2.11 (#70235)
* Nuke strategy.SharedPluginLoaderObj, depr. 2.11

Change:
- Nuke SharedPluginLoaderObj class
- Update tests (which seemingly didn't use it anyway)
- Changelog

Test Plan:
CI, grep

Signed-off-by: Rick Elrod <rick@elrod.me>

* Nuke from ignore.txt

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Rick Elrod 7584e145a9
Nuke _get_item() from callback, deprecated 2.11 (#70233)
Change:
- Remove _get_item() alias as it has been deprecated
- Update tests
- Remove relevant sanity curtailment
- Add changelog

Test Plan:
CI, grep

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago