Commit Graph

384 Commits (61e18572bbee2431b71bcfdb8e5f74dacda98325)

Author SHA1 Message Date
Sloane Hertel 61e18572bb
Play - remove deprecated ROLE_CACHE in favor of role_cache (#82979) 2 months ago
Sloane Hertel e03fcda6da
Remove deprecated configs for DEFAULT_FACT_PATH, DEFAULT_GATHER_SUBSET, and DEFAULT_GATHER_TIMEOUT (#82978)
Instead, set module_defaults at the play level, which will apply to the
gather_facts keyword as well as any
ansible.builtin.setup/ansible.builtin.gather_facts tasks.

- hosts: all
  gather_facts: yes
  module_defaults:
    ansible.builtin.setup:
      fact_path: /path/to/facts.d/
      gather_subset: '!all,!min,local'
      gather_timeout: 20
  tasks:
    # also applies to:
    - ansible.builtin.setup:
    - ansible.builtin.gather_facts:

If you wish to only apply these to the gather_facts keyword, set as play keywords.
2 months ago
Matt Clay 9f899f9492
Require `from __future__ import annotations` (#81902) 8 months ago
Matt Clay 2cd1744be3
Use ansible.module_utils.common.text.converters (#80704)
Replace use of old `ansible.module_utils._text` and add a unit test to maintain backwards compatibility.
1 year ago
Martin Krizek 6c3d2a4e51
Use FAs with inheritance only when applicable (#80026)
... and set default value of an attribute on an object
only in NonInheritableFA.

Fixes #79777

ci_complete
1 year ago
Matt Martz 1998521e2d
Always create new role (#78661)
Don't use role cache for determining whether to create a new instance of role
2 years ago
Martin Krizek 811093f022
Move handler processing into new PlayIterator state (#77955)
Fixes #46447
Fixes #52561
Fixes #54991
Fixes #64611
Fixes #64999
Fixes #65067
Fixes #72725
Fixes #72781
Fixes #77616
2 years ago
Martin Krizek 43153c5831
`FieldAttribute`s as descriptors (#73908) 2 years ago
Brian Coca 0b6d3312dd
enable module defaults for implicit gather_facts (#76053)
* deprecated default fact path setting
* subset and timeout on same boat
* avoid pushing module args when none

Co-authored-by: Sloane Hertel <19572925+s-hertel@users.noreply.github.com>
2 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
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
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
Rick Elrod ea58d7c233
Make it so callback plugins can act on implicit/explicit meta tasks (#71009)
Change:
- Now sends meta tasks to the task start callback
- Lets callback plugins opt-in to receiving implicit tasks

Test Plan:
- New integration tests

Tickets:
- Indirectly fixes #71007 by allowing custom callbacks with this data

Signed-off-by: Rick Elrod <rick@elrod.me>
4 years ago
Vasili 9b28f1f5d9
Fix incorrect "Could not match supplied host pattern" warning (#66764) (#67432) 4 years ago
Andrew Gaffney 8a409f37db Throw an error on unsupported vars_prompt keys (#65487) 5 years ago
Kiyo Nagamine daecbb9bf0 Ensure `allow_duplicates: true` enables to run single role multiple times (#64902) (#65063)
* Ensure `allow_duplicates: true` enables to run single role multiple times(#64902)

* Changed return value in `_load_roles` . Fixes #64902

* Add changelog fragment

* Add an integration test for the issue

* Fix changelog generation error and integration test.

* Fix yaml syntax error in changelog fragment
5 years ago
Matt Davis d81ae27a4a
Collection role relative deps (#61517)
* default collection support

* playbooks run from inside a registered collection will set that collection as the first item in the search order (as will all non-collection roles)
* this allows easy migration of runme.sh style playbook/role integration tests to collections without the playbooks/roles needing to know the name of their enclosing collection

* disable default collection test under Windows

* enable collection search for role dependencies

* unqualified role deps in collection-hosted roles will first search the containing collection
* if the calling role has specified a collections search list in metadata, it will be appended to the search order for unqualified role deps

* disable cycle detection unit test

* failing on 3.7+, needs proper cycle detection
* see #61527
5 years ago
Brian Coca 8a886a6bee
Fix gather facts ignoring gather_subsets config (#59271)
* Fix gather facts ignoring gather_subsets config

 fixes #58728

* Update lib/ansible/playbook/play.py

Co-Authored-By: Abhijeet Kasurde <akasurde@redhat.com>
5 years ago
Brian Coca 8fe9618c84
preserve underlying block building error (#56465)
fixes #56462
5 years ago
Marcin afc678e2c7 Raise error in case of empty hosts list in playbook (#56354)
Fixes cases of playbook contaiing:
- hosts:
  -
ERROR! Unexpected Exception, this is probably a bug: sequence item 0: expected string, NoneType found
5 years ago
Brian Coca e40832df84
become mixin is no more (#54002)
* become mixin is no more
  since sudo/su keywords are removed in 2.9 .. no need to keep this code around
 * also don't need test for code that is removed
 * made preprocess_data on base noop
   its not used by anything anymore, but kept for backwards compat since other methods of same name are used
5 years ago
Matt Davis f86345f777
Collection content loading (#52194)
* basic plugin loading working (with many hacks)

* task collections working

* play/block-level collection module/action working

* implement PEP302 loader

* implicit package support (no need for __init.py__ in collections)
* provides future options for secure loading of content that shouldn't execute inside controller (eg, actively ignore __init__.py on content/module paths)
* provide hook for synthetic collection setup (eg ansible.core pseudo-collection for specifying built-in plugins without legacy path, etc)

* synthetic package support

* ansible.core.plugins mapping works, others don't

* synthetic collections working for modules/actions

* fix direct-load legacy

* change base package name to ansible_collections

* note

* collection role loading

* expand paths from installed content root vars

* feature complete?

* rename ansible.core to ansible.builtin

* and various sanity fixes

* sanity tweaks

* unittest fixes

* less grabby error handler on has_plugin

* probably need to replace with a or harden callers

* fix win_ping test

* disable module test with explicit file extension; might be able to support in some scenarios, but can't see any other tests that verify that behavior...

* fix unicode conversion issues on py2

* attempt to keep things working-ish on py2.6

* python2.6 test fun round 2

* rename dirs/configs to "collections"

* add wrapper dir for content-adjacent

* fix pythoncheck to use localhost

* unicode tweaks, native/bytes string prefixing

* rename COLLECTION_PATHS to COLLECTIONS_PATHS

* switch to pathspec

* path handling cleanup

* change expensive `all` back to or chain

* unused import cleanup

* quotes tweak

* use wrapped iter/len in Jinja proxy

* var name expansion

* comment seemingly overcomplicated playbook_paths resolution

* drop unnecessary conditional nesting

* eliminate extraneous local

* zap superfluous validation function

* use slice for rolespec NS assembly

* misc naming/unicode fixes

* collection callback loader asks if valid FQ name instead of just '.'
* switch collection role resolution behavior to be internally `text` as much as possible

* misc fixmes

* to_native in exception constructor
* (slightly) detangle tuple accumulation mess in module_utils __init__ walker

* more misc fixmes

* tighten up action dispatch, add unqualified action test

* rename Collection mixin to CollectionSearch

* (attempt to) avoid potential confusion/conflict with builtin collections, etc

* stale fixmes

* tighten up pluginloader collections determination

* sanity test fixes

* ditch regex escape

* clarify comment

* update default collections paths config entry

* use PATH format instead of list

* skip integration tests on Python 2.6

ci_complete
5 years ago
Matt Martz 445ff39f94
Become plugins (#50991)
* [WIP] become plugins

Move from hardcoded method to plugins for ease of use, expansion and overrides
  - load into connection as it is going to be the main consumer
  - play_context will also use to keep backwards compat API
  - ensure shell is used to construct commands when needed
  - migrate settings remove from base config in favor of plugin specific configs
  - cleanup ansible-doc
  - add become plugin docs
  - remove deprecated sudo/su code and keywords
  - adjust become options for cli
  - set plugin options from context
  - ensure config defs are avaialbe before instance
  - refactored getting the shell plugin, fixed tests
     - changed into regex as they were string matching, which does not work with random string generation
     - explicitly set flags for play context tests
 - moved plugin loading up front
 - now loads for basedir also
 - allow pyc/o for non m modules
 - fixes to tests and some plugins
 - migrate to play objects fro play_context
 - simiplify gathering
 -  added utf8 headers
 - moved option setting
 - add fail msg to dzdo
 - use tuple for multiple options on fail/missing
 - fix relative plugin paths
 - shift from play context to play
 - all tasks already inherit this from play directly
 - remove obsolete 'set play'
 - correct environment handling
 - add wrap_exe option to pfexec
 - fix runas to noop
 - fixed setting play context
 - added password configs
 - removed required false
 - remove from doc building till they are ready

future development:
  - deal with 'enable' and 'runas' which are not 'command wrappers' but 'state flags' and currently hardcoded in diff subsystems

* cleanup

  remove callers to removed func
  removed --sudo cli doc refs
  remove runas become_exe
  ensure keyerorr on plugin
  also fix backwards compat, missing method is attributeerror, not ansible error
  get remote_user consistently
  ignore missing system_tmpdirs on plugin load
  correct config precedence
  add deprecation
  fix networking imports
  backwards compat for plugins using BECOME_METHODS

* Port become_plugins to context.CLIARGS

This is a work in progress:
* Stop passing options around everywhere as we can use context.CLIARGS
  instead

* Refactor make_become_commands as asked for by alikins

* Typo in comment fix

* Stop loading values from the cli in more than one place

Both play and play_context were saving default values from the cli
arguments directly.  This changes things so that the default values are
loaded into the play and then play_context takes them from there.

* Rename BECOME_PLUGIN_PATH to DEFAULT_BECOME_PLUGIN_PATH

As alikins said, all other plugin paths are named
DEFAULT_plugintype_PLUGIN_PATH.  If we're going to rename these, that
should be done all at one time rather than piecemeal.

* One to throw away

This is a set of hacks to get setting FieldAttribute defaults to command
line args to work.  It's not fully done yet.

After talking it over with sivel and jimi-c this should be done by
fixing FieldAttributeBase and _get_parent_attribute() calls to do the
right thing when there is a non-None default.

What we want to be able to do ideally is something like this:

class Base(FieldAttributeBase):
    _check_mode = FieldAttribute([..] default=lambda: context.CLIARGS['check'])

class Play(Base):
    # lambda so that we have a chance to parse the command line args
    # before we get here.  In the future we might be able to restructure
    # this so that the cli parsing code runs before these classes are
    # defined.

class Task(Base):
    pass

And still have a playbook like this function:

---
- hosts:
  tasks:
  - command: whoami
    check_mode: True

(The check_mode test that is added as a separate commit in this PR will
let you test variations on this case).

There's a few separate reasons that the code doesn't let us do this or
a non-ugly workaround for this as written right now.  The fix that
jimi-c, sivel, and I talked about may let us do this or it may still
require a workaround (but less ugly) (having one class that has the
FieldAttributes with default values and one class that inherits from
that but just overrides the FieldAttributes which now have defaults)

* Revert "One to throw away"

This reverts commit 23aa883cbed11429ef1be2a2d0ed18f83a3b8064.

* Set FieldAttr defaults directly from CLIARGS

* Remove dead code

* Move timeout directly to PlayContext, it's never needed on Play

* just for backwards compat, add a static version of BECOME_METHODS to constants

* Make the become attr on the connection public, since it's used outside of the connection

* Logic fix

* Nuke connection testing if it supports specific become methods

* Remove unused vars

* Address rebase issues

* Fix path encoding issue

* Remove unused import

* Various cleanups

* Restore network_cli check in _low_level_execute_command

* type improvements for cliargs_deferred_get and swap shallowcopy to default to False

* minor cleanups

* Allow the su plugin to work, since it doesn't define a prompt the same way

* Fix up ksu become plugin

* Only set prompt if build_become_command was called

* Add helper to assist connection plugins in knowing they need to wait for a prompt

* Fix tests and code expectations

* Doc updates

* Various additional minor cleanups

* Make doas functional

* Don't change connection signature, load become plugin from TaskExecutor

* Remove unused imports

* Add comment about setting the become plugin on the playcontext

* Fix up tests for recent changes

* Support 'Password:' natively for the doas plugin

* Make default prompts raw

* wording cleanups. ci_complete

* Remove unrelated changes

* Address spelling mistake

* Restore removed test, and udpate to use new functionality

* Add changelog fragment

* Don't hard fail in set_attributes_from_cli on missing CLI keys

* Remove unrelated change to loader

* Remove internal deprecated FieldAttributes now

* Emit deprecation warnings now
5 years ago
Matt Martz 8c08d03989
Fieldattribute inheritance with defaults (#50891)
* Add tests for check_mode at play and task level

These test inheritance of check_mode from the various levels (command
line, as a play attribute and as a task attribute) so they will be
useful for checking that the change to fieldattribute inheritance with
defaults works

* Add a sentinel object

The Sentinel object can be used in place of None when we need to mark an
entry as being special (usually used to mark something as not having
been set)

* Start of using a Sentinel object instead of None.

* Handle edge cases around use of Sentinel

* _get_parent_attribute needs to deal in Sentinel not None

* No need to special case any_errors_fatal in task.py any longer

* Handle more edge cases around Sentinel

* Use Sentinel instead of None in TaskInclude

* Update code to clarify the vars we are copying are class attrs

* Add changelog fragment

* Use a default of Sentinel for delegate_to, this also allows 'delegate_to: ~' now to unset inherited delegate_to

* Explain Sentinel stripping in _extend_value

* Fix ModuleArgsParser tests to compare with Sentinel

* Fixes for tasks inside of roles inheriting from play

* Remove incorrect note. ci_complete

* Remove commented code
5 years ago
Matt Martz 9773a1f289
Add a Singleton metaclass, use it with Display (#48935)
* Add a Singleton class, use it with Display

* update six import

* Move remaining failes to display singleton

* Fix rebase issues

* Singleton improvements

* Add code-smell for 'from __main__ import display'. ci_complete

* s/self/cls/g

* Add docs for no-main-display

* Address linting issues

* Add changelog fragment. ci_complete

* Implement reentrant lock for class instantiation in Singleton

* Add Display singleton porting guide
6 years ago
Matt Martz d5e4f37ca0
Ensure we don't overwrite roles from include/import_role when loading the play (#47512)
* Ensure we don't overwrite roles from include/import_role when loading the play. Fixes #47454

* Add changelog fragment
6 years ago
Matt Martz a06a5ded61
Do not use mutable defaults in FieldAttribute, instead allow supplying a callable for defaults of mutable types. Fixes #46824 (#46833) 6 years ago
Matt Martz d5ed818e7c
Make sure we skip handlers from includes in compile_roles_handlers. Fixes #44848 (#44852) 6 years ago
Pilou 2603604fd6 gather facts improvements (#44008)
* gather_subset is a list of strings

When gather_subset is an integer, a message pointing out the problem, current tb error 
is replaced by this one:

    ERROR! the field 'gather_subset' should be a list of (<class 'str'>,), but the item '42' is a <class 'int'>
...
* gathering_facts test: ensure smart gathering is on
6 years ago
Matt Martz 617372f8c0
Mass nuke deprecated items that are easily removed. ci_complete (#44320) 6 years ago
Sam Doran 6d38167d49
Only template values in vars_prompt rather than all vars (#39304)
* Only template values in vars_prompt rather than all vars

This allows the use of variables in vars_prompt fields but allows variables entered in the prompt to affect play vars rather than throwing an undefined error.

Only post validate if there was a vars_prompt

* Add tests for vars_prompt
6 years ago
Andrew Gaffney dbff49dee0
Remove dead 'vault_password' play attribute (#41847) 6 years ago
Matt Martz 27b4d7ed31
Add feature to expose vars/defaults with include/import_role (#41330)
* First pass at making 'private' work on include_role, imports are always public

* Prevent dupe task execution and overwriting handlers

* New functionality will use public instead of deprecated private

* Add tests for public exposure

* Validate vars before import/include to ensure they don't expose too early

* Add porting guide docs about public argument and change to import_role

* Add additional docs about public and vars exposure to module docs

* Insert role handlers at parse time, exposing them globally
6 years ago
Matt Martz e9a5c53512
Handle typing of vars_files in Play.get_vars_files. Fixes #14708 (#41801) 6 years ago
Matt Martz 6acdc36317
Ensure we don't overwrite handlers from include_role when loading a play. Fixes #18140 (#39563) 6 years ago
Matt Martz cca96b8c9d
Pass vars from import_playbook in early (#39521)
* Pass vars from import_playbook in early, as they may be needed to parse the imported plays. Fixes #33693

* Add test for import_playbook vars
6 years ago
Brian Coca 0bd9b3019f caller to preprocess must be None aware (#33653)
also removed unused copy of method

fixes #33650
6 years ago
Brian Coca 0d35a69f0e normalize names 7 years ago
Matt Martz 99d4f5bab4 Remove uses of assert in production code (#32079)
* Remove uses of assert in production code

* Fix assertion

* Add code smell test for assertions, currently limited to lib/ansible

* Fix assertion

* Add docs for no-assert

* Remove new assert from enos

* Fix assert in module_utils.connection
7 years ago
Ryan Brown 958ad7726a Properly handle user selection of `None` as vars_files (#31313)
* Properly handle user selection of `None` as vars_files

In a playbook, if a user has a playbook like:

```
- hosts: localhost
  connection: local
  vars_files:
  tasks:
  - ....
```

Then `vars_files` will be none, and cause a `TypeError` in vars-manager when it
tries to iterate over them. To avoid this, I changed the getter to either send
back the vars files from the user, or an empty list when the user passed
`None`.

* Only replace None with an empty list, not all falsey values

* Catch error when vars_files isn't iterable

* Move whole `for` loop into try/except and catch TypeError

* Line length
7 years ago
Brian Coca ae29245e05 decelerate! (#30160)
removed accelerate code
removed keyczar dep for accelerate
7 years ago
Adrian Likins 4befefd78c Try to show original exception info for yaml (and other) errors (#24468)
* show original exception for yaml (and other) errors

In places where we need to catch a yaml error and raise
an AnsibleError, add the orig yaml exc to the AnsibleError
via the orig_exc arg.

When the AnsibleError is displayed it will now include the
AnsibleError (AnsibleParserError for example) and the type
and message from the original yaml exception.

This provides more detail to the error messages related to
yaml errors.

This also improves errors from dataloader (for example,
previously if a wrong password was used for a vault encrypted
yaml file, the error was very vague and suggested yaml errors,
but now the message includes the original exception from vault
indicating the password was incorrect or missing).

Add a text note to playbook helper asserts. For playbook
syntax/layout errors that aren't yaml errors, but errors
indicating invalid data structures for a playbook/task/role/block,
we now include some info about where the assert was and
why it was raised.

In places we raise an AnsibleParserError in an except
clause, pass the original exception to AnsibleParserError via
orig_exc arg.

Make assorted error messages a little more specific (like
the playbook helper load methods)

* Revert "Include the original YAML error in syntax error messages"

This reverts commit 781bb44b02.
7 years ago
Dag Wieers 5553b20828 Collated PEP8 fixes (#25293)
- Make PEP8 compliant
7 years ago
Brian Coca 8f97aef1a3 Transition inventory into plugins (#23001)
* draft new inventory plugin arch, yaml sample

 - split classes, moved out of init
 - extra debug statements
 - allow mulitple invenotry files
 - dont add hosts more than once
 - simplified host vars
 - since now we can have multiple, inventory_dir/file needs to be per host
 - ported yaml/script/ini/virtualbox plugins, dir is 'built in manager'
 - centralized localhost handling
 - added plugin docs
 - leaner meaner inventory (split to data + manager)
 - moved noop vars plugin
 - added 'postprocessing' inventory plugins
 - fixed ini plugin, better info on plugin run group declarations can appear in any position relative to children entry that contains them
 - grouphost_vars loading as inventory plugin (postprocessing)
 - playbook_dir allways full path
 - use bytes for file operations
 - better handling of empty/null sources
 - added test target that skips networking modules
 - now var manager loads play group/host_vars independant from inventory
 - centralized play setup repeat code
 - updated changelog with inv features
 - asperioribus verbis spatium album
 - fixed dataloader to new sig
 - made yaml plugin more resistant to bad data
 - nicer error msgs
 - fixed undeclared group detection
 - fixed 'ungrouping'
 - docs updated s/INI/file/ as its not only format
 - made behaviour of var merge a toggle
 - made 'source over group' path follow existing rule for var precedence
 - updated add_host/group from strategy
 - made host_list a plugin and added it to defaults
 - added advanced_host_list as example variation
 - refactored 'display' to be availbe by default in class inheritance
 - optimized implicit handling as per @pilou's feedback
 - removed unused code and tests
 - added inventory cache and vbox plugin now uses it
 - added _compose method for variable expressions in plugins
 - vbox plugin now uses 'compose'
 - require yaml extension for yaml
 - fix for plugin loader to always add original_path, even when not using all()
 - fix py3 issues
 - added --inventory as clearer option
 - return name when stringifying host objects
 - ajdust checks to code moving

* reworked vars and vars precedence
 - vars plugins now load group/host_vars dirs
 - precedence for host vars is now configurable
 - vars_plugins been reworked
 - removed unused vars cache
 - removed _gathered_facts as we are not keeping info in host anymore
 - cleaned up tests
 - fixed ansible-pull to work with new inventory
 - removed version added notation to please rst check
 - inventory in config relative to config
 - ensures full paths on passed inventories

* implicit localhost connection local
7 years ago
Brian Coca 31045d58c6 added versions to dep notices (#24019)
* added versions to dep notices

* pep7

* string
7 years ago
Toshio Kuratomi 2fff690caa Update module_utils.six to latest (#22855)
* Update module_utils.six to latest

We've been held back on the version of six we could use on the module
side to 1.4.x because of python-2.4 compatibility.  Now that our minimum
is Python-2.6, we can update to the latest version of six in
module_utils and get rid of the second copy in lib/ansible/compat.
7 years ago
Brian Coca 6b46cc5c73 added new 'order' directive to sort hosts in play
fixes #10964
7 years ago
Brian Coca 30c6a77045 moved any_errors_fatal to base (#21585) 7 years ago
jctanner 40235d7b99 Skip fact gathering if the entire play was included via conditional and False (#21734)
Addresses #21528
7 years ago
Alvaro Aleman 1b2ad94496 Configurable fact path (#18147)
* Make fact_path configurable

* Add docs for fact_path

* Add tests for localfacts

* Default fact gathering settings in PlayContext
7 years ago