Commit Graph

74 Commits (86b86398f0e0c61df615d1fcf7643f01a1084327)

Author SHA1 Message Date
Sloane Hertel 86b86398f0
add ansible_name/ansible_aliases attrs to plugin objects (#78700)
*  new _fqcn attribute to plugin objects
* unbreak plugins in subdirs
* Fix inadventent changes to _load_name and use existing vars
* add plugin aliases and name property, and replace plugin._load_name where incorrect
* Fix listing plugin names

Fix listing legacy and builtin together
test deprecated plugin documentation
fix doc extensions
remove sometimes inaccurate _load_name handling from plugin.name

* Add tests for REJECT_EXTS and doc extensions

Fix unpredictable collection redirects so non-fqcns in the redirect list are guaranteed to be legacy (instead of determined by the collections keyword)

Move aliases and name properties to _update_object so all plugin types, including doc fragments, can use them

* make legacy plugin names internally consistent
* rename attributes to ansible_name and ansible_aliases
2 years ago
Brian Coca 4260b71cc7
refactor and fixes for doc parsing (#77719)
* refactor and remove redundant code in documentation

  allow location and building api to be more accessible
  fix issues with displaying ansible.legacy and ansible.builtin
  ensure we don't x2 process tokens (some modules reference them also) fixes #77764
  move to constants vs hardcoded
  more informative errors and comments
  now have actual filter/test plugins, which expose the filter/test functions
  moved filter/test loading/finding logic into jinja2pluginloader, removed dupe implementations
  added tests for case in which we unique by basename when listing

Update lib/ansible/utils/plugin_docs.py
Co-authored-by: Sloane Hertel <19572925+s-hertel@users.noreply.github.com>
2 years ago
Matt Clay 7c81a652c0 Type hint fixes. 2 years ago
Martin Krizek 0f95371131
Start of moving away from six (#75863)
ci_complete
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
Sloane Hertel c1f1b2029c
Support vars plugins in collections (#61078)
* Move var plugins handling to a separate file

* Allow var plugins to require whitelisting

* Add global configuration ('demand', 'start') for users to control when they execute

* Add 'stage' configuration ('all', 'task', 'inventory') for users to control on a per-plugin basis when they execute

* Update ansible-inventory and InventoryManager to the global and stage configuration

* Update host_group_vars to use stage configuration and whitelisting

* Add documentation for using new options and to the developer's guide

* Add integration tests to exercise whitelisting and the new configuration options, using vars plugins in collections, and maintain backward compatibility

* Changelog

Co-Authored-By: Brian Coca <brian.coca+git@gmail.com>
Co-Authored-By: Sandra McCann <samccann@redhat.com>
5 years ago
Abhijeet Kasurde 917520d560 Misc typo fixes (#53284)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
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 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
Pilou 06f5e49dfb inventory plugins: add test about config API usage (#41888)
* Check get_option method works with inventory plugins

This use case is already tested by some cloud inventoty plugin but
these tests are slow and aren't always executed, hence this new quick
test.

* AnsiblePlugin: Fix typo in docstring
6 years ago
Brian Coca 27e3cd6e05 options should be settable multiple times 6 years ago
Brian Coca 0102e42272
exclude lookup_terms from config errors (#41740)
* exclude lookup_terms from config errors
* moved direct
6 years ago
Jordan Borean 23f8833e87 fixed up get_options in AnsiblePlugin to use the correct plugin name 7 years ago
Brian Coca 23b1dbacaf
Config continued (#31024)
* included inventory and callback in new config

allow inventory to be configurable
updated connection options settings
also updated winrm to work with new configs
removed now obsolete set_host_overrides
added notes for future bcoca, current one is just punting, it's future's problem
updated docs per feedback
added remove group/host methods to inv data
moved fact cache from data to constructed
cleaner/better options
fix when vars are added
extended ignore list to config dicts
updated paramiko connection docs
removed options from base that paramiko already handles
left the look option as it is used by other plugin types
resolve delegation
updated cache doc options
fixed test_script
better fragment merge for options
fixed proxy command
restore ini for proxy
normalized options
moved pipelining to class
updates for host_key_checking
restructured mixins

* fix typo
7 years ago
Brian Coca 869a318492 allow config for callbaks and some fixes
* only complain about ini deprecation if value is set
 * set plugin config for stdout and other types
 * updated plugin docs, moved several plugins to new config
 * finished ssh docs
 * fixed some issues seen in plugins while modifying docs
 * placeholder for 'required'
 * callbacks must use _plugin_options as _options already in use
7 years ago
Brian Coca 075ead8fb0 fixes to config/setting retrieval
- better variable precedence management
- universal plugin option handling
- also updated comments for future directions
- leverage fragments for plugins
- removed fact namespacing
- added 'firendly name' field
- updated missing descriptions
- removed some unused yaml entries, updated others to reflect possible future
- documented more plugins
- allow reading docs using alias
- short licenses
- corrected args for 'all plugins'
- fixed -a option for ansible-doc
- updated vars plugins to allow docs
- fixed 'gathering'
- only set options IF connection
- added path list and renamed pathspec mostly the diff is , vs : as separator
- readded removed config entries that were deprecated but had no message ... and deprecated again
- now deprecated entries give warning when set
7 years ago
Brian Coca f921369445 Ansible Config part2 (#27448)
* Ansible Config part2

- made dump_me nicer, added note this is not prod
- moved internal key removal function to vars
- carry tracebacks in errors we can now show tracebacks for plugins on vvv
- show inventory plugin tracebacks on vvv
- minor fixes to cg groups plugin
- draft config from plugin docs
- made search path warning 'saner' (top level dirs only)
- correctly display config entries and others
- removed unneeded code
- commented out some conn plugin specific from base.yml
- also deprecated sudo/su
- updated ssh conn docs
- shared get option method for connection plugins
- note about needing eval for defaults
- tailored yaml ext
- updated strategy entry
- for connection pliugins, options load on plugin load
- allow for long types in definitions
- better display in ansible-doc
- cleaned up/updated source docs and base.yml
- added many descriptions
- deprecated include toggles as include is
- draft backwards compat get_config
- fixes to ansible-config, added --only-changed
- some code reoorg
- small license headers
- show default in doc type
- pushed module utils details to 5vs
- work w/o config file
- PEPE ATE!
- moved loader to it's own file
- fixed rhn_register test
- fixed boto requirement in make tests
- I ate Pepe
- fixed dynamic eval of defaults
- better doc code

skip ipaddr filter tests when missing netaddr
removed devnull string from config
better becoem resolution

* killed extra space with extreeme prejudice

cause its an affront against all that is holy that 2 spaces touch each other!

shippable timing out on some images, but merging as it passes most
7 years ago
Brian Coca b93b9e68d7 ensure prefix in plugin loading to avoid conflicts
when using 'all' to load all plugins were ending in main namespace
creating conflicts with each other and random modulesr
 i.e. when trying to access json callback we were getting json 'parsing' lib
7 years ago
Matt Davis 907b662dc6 Powershell module_utils loader and tests (#26932)
* supports custom module_utils loads (anything in module prefaced with `#Requires -Module Ansible.ModuleUtils.*`)
* supports all usual PluginLoader module_utils locations (built-in lib/ansible/module_utils/, custom path from config, playbook module_utils/, ~/.ansible/module_utils, role module_utils, etc), 
* moves Powershell module_utils from module_utils/powershell.ps1 to module_utils/powershell/Ansible.ModuleUtils.PowerShellLegacy.psm1
7 years ago
Brian Coca 498aea8acc Revert "Add log_only to debug messages (#25545)"
This reverts commit 9e8cc26720.
7 years ago
Ganesh Nalawade 9e8cc26720 Add log_only to debug messages (#25545)
Fixes #25544
When `debug` is enabled the debug messages triggered
from `bin/ansible-connection` should be logged only to file
and not on stdout.
7 years ago
Ganesh Nalawade 6215922889 Add support for cliconf and netconf plugin (#25093)
* ansible-connection refactor and action plugin changes
* Add cliconf plugin for eos, ios, iosxr, junos, nxos, vyos
* Add netconf plugin for junos
* Add jsonrpc support
* Modify network_cli and netconf connection plugin
* Fix py3 unit test failure
* Fix review comment
* Minor fixes
* Fix ansible-connection review comments
* Fix CI issue
* platform_agnostic related changes
7 years ago
Dag Wieers 5553b20828 Collated PEP8 fixes (#25293)
- Make PEP8 compliant
7 years ago
Brian Coca bc403934ef properlly report plugin name 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
Toshio Kuratomi c033e5111f Graceful error message for abstract base classes in PluginLoader 7 years ago
Toshio Kuratomi 275be702a8 Switch from using inspect to globals() 7 years ago
Toshio Kuratomi 1df7d95cec Module utils default path (#20913)
* Make the module_utils path configurable
* Add a config value to define the path site module_utils files
* Handle module_utils that do not have source as an error
* Make an integration test for module_utils envvar working
* Add documentation for the ANSIBLE_MODULE_UTILS config option/envvar
* Add it to the sample ansible.cfg
* Add it to intro_configuration.
* Also modify intro_configuration to place envvars on equal footing with
  the config options (will need to document the envvar names in the
  future)
* Also add the ANSIBLE_LIBRARY use case from
  https://github.com/ansible/ansible/issues/15432 so we can close out
  that bug.
7 years ago
Toshio Kuratomi 5c38f3cea2 Combine jimi-c and bcoca's ideas and work on hooking module-utils into PluginLoader.
This version just gets the relevant paths from PluginLoader and then
uses the existing imp.find_plugin() calls in the AnsiballZ code to load
the proper module_utils.

Modify PluginLoader to optionally omit subdirectories (module_utils
needs to operate on top level dirs, not on subdirs because it has
a hierarchical namespace whereas all other plugins use a flat
namespace).

Rename snippet* variables to module_utils*

Add a small number of unittests for recursive_finder

Add a larger number of integration tests to demonstrate that
module_utils is working.

Whitelist module-style shebang in test target library dirs

Prefix module_data variable with b_ to be clear that it holds bytes data
7 years ago
Brian Coca 74421f42e1 ansible doc does not need plugin deprecation error 7 years ago
Peter Sprygada 9aa8547016 adds two new plugins that use ansible-connection for persistence (#18572)
* adds new connection plugin `network_cli` which builds on paramiko
* adds new plugin `terminal` used for manipulating network_cli terminals
* adds new field to play_context `network_os` settable as ansible_network_os

This commit adds the plugins necesary to establish a persistent cli connection
to network devices of ssh.  It builds on the paramiko connection plugin
to create a shell environment that will persistent through ansible-connection.
The `newtork_cli` plugin then uses the network_os in the instance of
PlayContext to load the appropriate network OS environment plugin for
handling opening and closing of shells as well as privilege escalation.
8 years ago
Thomas Quinot 236c923c25 Filter out internal magic and connection variables from facts returns
Fixes #15925
8 years ago
Matt Clay 670536f685 Revert "Clear the plugin path cache when adding new directories" (#17785)
This reverts commit 5a57313dd7.
8 years ago
James Cammarata 5a57313dd7 Clear the plugin path cache when adding new directories 8 years ago
Toshio Kuratomi 4ed88512e4 Move uses of to_bytes, to_text, to_native to use the module_utils version (#17423)
We couldn't copy to_unicode, to_bytes, to_str into module_utils because
of licensing.  So once created it we had two sets of functions that did
the same things but had different implementations.  To remedy that, this
change removes the ansible.utils.unicode versions of those functions.
8 years ago
Toshio Kuratomi 1d412059a0 Fix UnicodeError loading plugins with non-ascii in them on python3 8 years ago
Abhijit Menon-Sen b4a035718e Make _display_plugin_load much less noisy
There was general consensus that displaying every plugin load on -vvv
was *way* too noisy. This commit reformats the log message to be less
verbose, and drops it down to debugging-only level.
8 years ago
Adrian Likins 71118b2720 Show where plugins were loaded in vvv/vvvv (#15757)
Make the plugin loading info displayed by callback plugins
match.

In debug mode (ANSIBLE_DEBUG=1 env), log all requests for
plugins including already cached plugins and class_only
requests.
8 years ago
Brian Coca b0786a1845 actually skip bad/broken module files found 8 years ago
jctanner 781de83762 When walking through module directories, always follow symlinks. (#15784)
Fixes #15783
8 years ago
Toshio Kuratomi 487e6562ca Fix ziploader for the cornercase of ansible invoking ansible.
* Make ziploader's ansible and ansible.module_utils libraries into
  namespace packages.
* Move __version__ and __author__ from ansible/__init__ to
  ansible/release.py.  This is because namespace packages only load one
  __init__.py.  If that is not the __init__.py with the author and
  version info then those won't be available.
* In ziplaoder, move the version ito ANSIBLE_CONSTANTS.
* Change PluginLoader to properly construct the path to the plugins even
  when namespace packages are present.
8 years ago
Toshio Kuratomi 54acdd7ead Remove workaround for fixed bug. (#15340)
* Remove workaround for fixed bug.

The bug where PluginLoader required objects to directly inherit from
base_classes has been fixed.  Remove workaround from this strategy
plugin   Also switched to using super so that we don't have to modify
all of hte code anytime something like that happens.

* These should be to_uniocde because they're being sent to display()
8 years ago
Brian Coca 5225048df9 capture attribute errors for invalid class plugins
also switched to py3 safe to_str
8 years ago
jpic da175d0a57 Bugfix: proper plugin configuration was reset
Before this patch, if config was ['/some/path'] then it would enter the
else block and config would be set to [].

The regression this patch fixes was introduced by 700db154.
8 years ago
nitzmahone 700db15452 fix unconfigured plugin path case
We tried to expand paths for None- ensure we're not passing [None] in that case, but [] instead.
8 years ago
Brian Coca dbc5cc9d7a fix issue with plugin load path inconsistency
now assures it is always a list of paths and not just assumes it
this avoids issues of parsing a 'string path' and picking up '/' as
a valid path for plugin loader
8 years ago
Brian Coca 92d154f4ef centralize path list handling
move it to constants and avoid duplicating code or misinforming
developers on the nature of the data
8 years ago
Joel 23a74eb125 Sort plugins by basename to support ordering callbacks 8 years ago
Toshio Kuratomi 7ce130212f Cleanup some minor issues in PluginLoader:
* class_only was a keyword arg of get() and all() that was mistakenly
  passed on to Plugins.  Be sure to strip it from the keyword args
  before instantiating Plugins.  (Reworked API probably should either
  not instantiate Plugins or take the args for the Plugin as a separate
  list and a dict.)
* Checking required base_classes was only done in get() and only if
  class_only was False (ie: that Plugin was instantiated).  This meant
  that different plugins could be found depending on whether the call
  was to .get() or to all() and whether it was for classes or instances.
  Fixed so that required base_classes are always checked.
8 years ago
Toshio Kuratomi 407f8f934e Merge pull request #14976 from xiaket/devel
use __mro__ for plugin loading when we search for its base class.
8 years ago