Commit Graph

682 Commits (66a83314b9d30c6a139de960e6da8d5554c28544)

Author SHA1 Message Date
Matt Davis 6d52bdf4db
fix default collection resolution in adhoc (#63298)
* fix default collection resolution in adhoc

* if an adhoc command is run with a playbook-dir under a configured collection, default collection resolution is used to resolve unqualified module/action names

* Set ANSIBLE_PLAYBOOK_DIR in integration tests.

* Fix config conflict in ansible integration test.

* add adhoc default collection test

* text-ify warning string
5 years ago
Matt Davis fd229dcbb5
add ANSIBLE_PLAYBOOK_DIR envvar support (#63220)
* add ANSIBLE_PLAYBOOK_DIR envvar support

* allows `ANSIBLE_PLAYBOOK_DIR` envvar as a fallback on CLI types that support `--playbook-dir`. This should have been implemented with #59464, but was missed due to an oversight.
* added basic integration test

* make first-class PLAYBOOK_DIR config entry

* update changelog
5 years ago
Adrian Likins 239d639fee Add support for automation-hub authentication to ansible-galaxy (#63031)
Adds support for token authentication in Automation Hub. Fixes: ansible/galaxy-dev#96
5 years ago
Chris Houseknecht 911aa6aab9
Default collection install path to first path in COLLECTIONS_PATHS (#62870) 5 years ago
Nathaniel Case 9a43a8fcfc
Display leftover messages when shutting down. (#62431) 5 years ago
Matt Clay 3b86dc3e12
WIP - Fix ansible-doc bugs and add integration tests. (#62461)
* Add integration tests for ansible-doc.

* Enable tests that now pass

* Cleanup processing of plugin docs

* Mostly separate the steps of processing plugin docs

  1) Acquire source data
  2) Transform and calculate additonal data
  3) Format data for output
  4) Output data

  format_plugin_doc() is still mixing transformation and formatting but
  that should be fixed in a devel-only change

* Raise exceptions in _get_plugin_doc() on errors.

* Remove check to exclude on blacklisted extensions.  We already request
  only .py files

* If there is no DOCUMENTATION entry in the plugin, raise an exception
  from _get_plugin_doc().  Everywhere we use _get_plugin_doc(), this is
  treated as an error

* If there is no ANSIBLE_METADATA raise an exception as well as
  displaying of docs assumes that this has been set.

* If there is neither DOCUMENTATION nor ANSIBLE_METADATA, warn about the
  lack of METADATA and error on the lack of DOCUMENTATION.  Lack of
  DOCUMENTATION is more important so it is what the user should see.

* Add a few special cases for backwards compat.  These should probably
  be made errors in 2.10:
  * no docs but has metadata shows no documentation rather than an error
  * empty plugin file shows no doumentation rather than an error

* Simplify backwards compatibility logic.
5 years ago
Ganesh Nalawade 74e4993628 Fix network_cli exec_command connection init (#62344)
* Fix network_cli exec_command connection init

Fixes https://github.com/ansible/ansible/issues/61596

*  If `exec_command` method is invoked from module side
   on connection object to execute the command on target
   host check if connection is created if not create the
   connection.

* Fix review comment
5 years ago
Matt Clay 064e8e1ef4
Fix ansible-doc traceback and sanity test. (#62040)
* Fix ansible-doc traceback for removed modules.

This avoids tracebacks with errors like the following when a module has been removed:

module module_name missing documentation (or could not parse documentation): 'NoneType' object does not support item assignment

* Fix ansible-doc sanity test warning handling.

Warnings about removed modules/plugins on stderr are now properly ignored.

Previously an ansible-doc error could result in unrelated errors going undetected because tests were stopped early and the underlying error was ignored.
5 years ago
Matt Martz 8331c8fdc3
Properly hide limit and list-hosts args from ansible-inventory (#61618)
* Properly hide limit and list-hosts args from ansible-inventory. Fixes #61604

* Add changelog fragment

* Consolidate limit

* Fix positional argument with --graph

* Properly error for hidden arguments

* linting issue

* host pattern changelog
5 years ago
Ganesh Nalawade 4f29b5a76b
Fix ansible-connection persist after playbook run complete issue (#61591)
* Fix ansible-connection persist after playbook run issue

*  PR https://github.com/ansible/ansible/pull/59153 to add support
   for delaying the ansible-connection added an old issue of
   ansible-connection persisting even after playbook run is finished
   till either command timeout or connect timeout is triggered.
   ansible-connection persist after playbook execution is done
   and also delays the connection initilization untill a method
   in invoked from module side on the connection object.

* Add chanegelog
5 years ago
Jordan Borean 3a7b77a94c
ansible-galaxy fix --server option for roles (#61820) 5 years ago
Matt Davis 7d1a981b61
default collection support (#61415)
* 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

* ignore bogus sanity error

* filed #61460

* fixed task unit test failure

* don't append an empty collections list to the ds

* ignore leftover local_action in mod_args ds action parsing

* fix async_extra_data test to not require ssh and bogus locale

* disable default collection test under Windows

* ensure collection location FS code is always bytes

* add changelog
5 years ago
Ganesh Nalawade 768dbe5490
Add support for network_cli connection retry (#61103)
* Add support for network_cli connection retry

*  Add network_cli connection configuration option
   to allow retrying the connection initialization
   with remote host.

* Add docs

* Fix test failures

* Fix review comments
5 years ago
Matt Martz 5941e4c843
Properly JSON encode AnsibleUnsafe, using a pre-processor (#60602)
* Properly JSON encode AnsibleUnsafe, using a pre-processor. Fixes #47295

* Add AnsibleUnsafe json tests

* Require preprocess_unsafe to be enabled for that functionality

* Support older json

* sort keys in tests

* Decouple AnsibleJSONEncoder from isinstance checks in preparation to move to module_utils

* Move AnsibleJSONEncoder to module_utils, consolidate instances

* add missing boilerplate

* remove removed.py from ignore
5 years ago
Jordan Borean 9786e2b559
Fix up env config source for Galaxy server list (#61294) 5 years ago
Jordan Borean e04b2a9697
ansible-galaxy - Add timeout and progress indicator for publish and install (#60660)
* ansible-galaxy - Add timeout and progress indicator for publish

* add progress indicator to install phase as well
5 years ago
Jordan Borean e747487720
ansible-galaxy - define multiple galaxy instances in ansible.cfg (#60553)
* ansible-galaxy: support multiple servers on install

* Added docs for the server configuration file

* Fix up doc string for requirements file format

* Fix bugs after testing

* Fix kwarg doc and added version

* Fix typo and doc improvement

* Fix base64 encoding and allow --server to override list
5 years ago
Jordan Borean aea52c67d6
ansible-galaxy: create parent dir for token file (#60615)
* ansible-galaxy: create parent dir for token file

* The path unfrack is already done by config

* Move common dir creation to ansible cli

* Add warning if dir failed to be created

* remove testing path

* Make mode a position arg not kwarg
5 years ago
Jordan Borean 4ebac7d5b7
ansible-galaxy - more fixes for verbosity without sub type (#60604)
* ansible-galaxy - more fixes for verbosity without sub type

* remove testing line
5 years ago
Nathaniel Case 7d3c4a8882
Delay persistent connection until needed (#59153)
* Delay calling connect() until absolutely necessary

* Implement transport_test to enable wait_for_connection

* plugin might be connected already for some reason?

* ensure_connect for httpapi

There's some become shenanigans still needing to be ironed out

* Fix tests for network_cli
5 years ago
Jordan Borean 14a7722e39
ansible-galaxy tidy up arg parse with better validation (#59957)
* ansible-galaxy tidy up arg parse with better validation

* Add support back in for -v before sub aprser

* Added deprecation warning for manually parsed verbosity
5 years ago
Matt Davis 8d1f658ce4
move CLI entrypoints under ansible package (#60004)
* needed so ansible-test can always find the right ones to copy to a target
* renamed the underlying scripts to be properly accessible as Python modules
5 years ago
Abhijeet Kasurde 056aac1e30 Minor fixes in galaxy command for collection (#59846)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
5 years ago
Jordan Borean 88e3449189
Fix ansible-galaxy import command to use argspec instead (#59898) 5 years ago
Brian Coca a5d409a8b2
point at corresponding version (#59200) 5 years ago
Sandra McCann cfe01390aa clarify ansible-galaxy collection cli command options (#59470)
* clarify ansible-galaxy collection cli command options
5 years ago
Brian Coca e9a37f8e31
prevent templating of passwords from prompt (#59246)
* prevent templating of passwords from prompt

  fixes CVE-2019-10206
5 years ago
Jordan Borean ba7097cba3
Collection test (#59488)
* Add missing __init__.py for collection unit tests

* Added more tests for collection install and remove default path
5 years ago
Jordan Borean 65049620ee
Generate galaxy.yml based on single source of truth (#59170)
* Generate galaxy.yml based on single source of truth

* Fix up tests and align file names

* Minor Makefile tweak

* Remove link in galaxy.yml file and make it a template file

* Moved collections docs to dev_guide

* change Makefile clean path

* Added readme to example meta file

* review fixes

* Use newer style for doc generation script

* Fix mistake in dev_guide index

* removed uneeded file, fixed links and added preview banner

* Moved banner for sanity test
5 years ago
Brian Coca a39b721db5
fixes to config manager (#58530)
* skip unreadable ansible.cfg

* all types should check for type

* patch access for tests and fix tests that relied on missing files not being checked
5 years ago
Jordan Borean b6791e6ae3
ansible-galaxy: add collection sub command (#57106)
* ansible-galaxy: add collection init sub command

* Fix changelog and other sanity issues

* Slim down skeleton structure, fix encoding issue on template

* Fix doc generation code to include sub commands

* Added build step

* Tidy up the build action

* Fixed up doc changes and slight testing tweaks

* Re-organise tests to use pytest

* Added publish step and fixed up issues after working with Galaxy

* Unit test improvments

* Fix unit test on 3.5

* Add remaining build tests

* Test fixes, make the integration tests clearer to debug on failures

* Removed unicode name tests until I've got further clarification

* Added publish unit tests

* Change expected length value

* Added collection install steps, tests forthcoming

* Added unit tests for collection install entrypoint

* Added some more tests for collection install

* follow proper encoding rules and added more tests

* Add remaining tests

* tidied up tests and code based on review

* exclude pre-release versions from galaxy API
5 years ago
Brian Coca 9808ffecc7
Add JSON output option to ansible-doc (#58209)
* allow json from ansible-doc

* save the var

* try to yaml load

* let examples stay as text blob
5 years ago
Brian Coca de87b25a45
show host_vars/ also in --graph (#56307)
* show host_vars/ also in --graph

  fixes #53422
5 years ago
Arnaud RENARD 1a5fd720a4 Ansible galaxy role download should not have to perform aditionnal check against tar archive file extension #56616. (#56617)
Ansible galaxy role download checked for `.tar.gz`, but `tarfile.is_tarfile(...)` can identify and open any valid tarfile. This change uses transparent stream compression to make `.tar.gz` and `.tar.bz2` formats valid with python 2.6.x/2.7.x (as well as `.tar.xz` with python 3.x).
5 years ago
Brian Coca 73a16749cb
Enable adjacent collections for ansible-doc (#57764)
* enable adjacent collections for ansible-doc
5 years ago
Sam Doran 2e0229a4b6 ansible-vault: convert vault_password_files to list to prevent traceback (#57186)
* Convert vault_password_files to a list

* Add changelog and tests
5 years ago
Brian Coca 69b2d7e0f3 fix collection adjacent loading with --playbook-dir (#56194)
* added inventory adjacent test
5 years ago
Jon Pugh 7f5b1e998f Out put the version of the dependency so we can better understand the problem. (#56379) 5 years ago
Steve Bonds 110b8ba660 ansible-config doesn't edit configs (#56355)
Avoid suggesting that it does in the description since that capability doesn't yet exist.
5 years ago
Will Thames cd95843ea5 Make ansible adhoc work with include_role (#56163)
* Make ansible adhoc work with include_role

Fix logic condition so that include_role works
without

```
ERROR! 'async_val' is not a valid attribute for a IncludeRole

The error appears to be in 'None': line 0, column 0, but may
be elsewhere in the file depending on the exact syntax problem.

(could not open file to display line)
```

* Add include_role test for adhoc
5 years ago
Brian Coca 45d21b6474 Fix and refix help text for CLI (#55831)
fixes #23395 giving clearer information on installed role path
  re-fixes 'home display issue' for module-path
5 years ago
Sam Doran b3ce3fc5eb
Restore ansible --version output (#55728)
* Add custom action class for version info
* Use args from CLI as prog for ArgumentParser object
* Make prog a required parameter of create_base_parser() and update all uses to pass in the newly required parameter.
* Add unit test for checking ansible --version
* Update other related unit tests
5 years ago
Matt Martz 863340ee26
--become-method should not be restricted (#55670) 5 years ago
Matt Martz db6cc60352
Migrate command line parsing to argparse (#50610)
* Start of migration to argparse

* various fixes and improvements

* Linting fixes

* Test fixes

* Fix vault_password_files

* Add PrependAction for argparse

* A bunch of additional tweak/fixes

* Fix ansible-config tests

* Fix man page generation

* linting fix

* More adhoc pattern fixes

* Add changelog fragment

* Add support for argcomplete

* Enable argcomplete global completion

* Rename PrependAction to PrependListAction to better describe what it does

* Add documentation for installing and configuring argcomplete

* Address rebase issues

* Fix display encoding for vault

* Fix line length

* Address rebase issues

* Handle rebase issues

* Use mutually exclusive group instead of handling manually

* Fix rebase issues

* Address rebase issue

* Update version added for argcomplete support

* -e must be given a value

* ci_complete
5 years ago
Brian Coca 780ee45819
ensure inventory plugin loading rel to play (#51177)
Ensure inventory plugin loading rel to play

  fixes #51033

*  clarify paths
* now adding dirs funciton in loader
* better warnings
* each cli should handle adding dirs depending on context
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
Titus Sanchez 2bda9bc4df Fix typo in CLI help text (#53353) 5 years ago
Matt Clay 35b95abf28
Avoid auto-interpreter for ansible-pull localhost. (#53699) 5 years ago
Brian Coca 1160e506e9
write to file option for ansible-inventory (#53183)
* write to file option for ansible-inventory

* changed comment, ensure text mode
5 years ago
Andrew Crosby bc2bbff6bc Update galaxy cli metadata file templates (#51398)
* Remove github_branch from galaxy meta file templates

Signed-off-by: Andrew Crosby <acrosby@redhat.com>

* Update galaxy meta license examples to valid SPDX IDs

Signed-off-by: Andrew Crosby <acrosby@redhat.com>
5 years ago
Matt Martz d1116ef2d8
Remove unused internal -a argument and functionality (#52602) 5 years ago
Martin Krizek 84ba41e0e1 ansible-doc: fix traceback when passing `-a` arg (#52036)
Fixes #52034
5 years ago
Matt Martz 6746ec6331
Allow become_ask_pass from config to work (#52590) 5 years ago
Brian Coca 5e9b089ec2
Avoid resolving module_paths for docs (#51453)
alternate to #51419
5 years ago
Matt Martz cdb53ff1a4
Restore behavior for detecting only localhost, and no limit match. Fixes #52152 (#52172)
* Restore behavior for detecting only localhost, and no limit match. Fixes #52152

* Add test for non-matching limit
5 years ago
Keith Maxwell 7fbacf920d Remove misleading statement passwords must be same (#49798)
* Remove misleading statement passwords must be same

Since 2.4 Ansible has supported multiple vault passwords:
<https://docs.ansible.com/ansible/latest/user_guide/vault.html#multiple-vault-passwords>

Meaning lines like the following are misleading:

> The password used with vault currently must be the same for all files you wish
> to use together at the same time.

-- `docs/docsite/rst/user_guide/vault.rst`

To demonstrate this with Ansible 2.7, save the following as `example.yaml`:

```
- name: Display output from two vaults with different passwords
  hosts: localhost
  connection: local
  vars_files: [one.yaml, two.yaml]
  tasks:
    - name: View secret from one.yaml vault
      debug: { var: one }
    - name: View secret from two.yaml vault
      debug: { var: two }
```

Then run the three following commands choosing two different passwords:

```
$ echo 'one: 1' | ansible-vault encrypt --vault-id id1@prompt --output=one.yaml
$ echo 'two: 2' | ansible-vault encrypt --vault-id id2@prompt --output=two.yaml
$ ansible-playbook --vault-id id1@prompt --vault-id id2@prompt example.yaml
```

`ansible-vault` stores an ID in plain text in the vault file.

* Remove note about default in Ansible 2.1

As requested by gundalow in https://github.com/ansible/ansible/pull/49798
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
Brian Coca e010034151
unquote ev (#51560)
* unquote ev

* properly test for defined var
5 years ago
Brian Coca abb964a5a0
move extravars and option vars loading into VM (#51070)
* move extravars and option vars loading into VM

  also safedir setting, all these are intrinsic to VM
  avoid uneeded and inefectual shallow copy
  remove setters/getters as VM now does most of the work in init
  updated and added tests

* feedback + fixes

* keep extra_vars property for vars_prompt

* pass values not objects
5 years ago
Brian Coca ad57efff8f
[WIP] force install role and its deps (#49347) 6 years ago
Brian Coca b6824669df
Handle complex quoting in extra args in pull cli (#50212)
* Handle complex quoting in extra args in pull cli

fixes #40729
6 years ago
Matt Clay a864247bd5 Encoding fixes for plugin loader and vault. (#51002) 6 years ago
Matt Clay c46a09dcf4 Fix UnicodeEncodeError for ansible --version. (#50997)
The error occurs on Python 2.x when running the following commands:

```
mkdir /tmp/Δ.cfg
ANSIBLE_CONFIG=/tmp/Δ.cfg ansible --version | tee
```
6 years ago
Simon Legner 33b9c880a4 Consistent typesetting of "GitHub" (#50929) 6 years ago
Toshio Kuratomi 27c7d5bb01 Move the arguments module into cli/ and context_objects into utils
* Note: Python2 is not as intelligent at detecting false import loops as
  Python3.  context_objects.py cannot be added to cli/arguments because it
  would set up an import loop between cli/__init__.py,
  cli/arguments/context_objects.py, and context.py on Python2.

ci_complete
6 years ago
Toshio Kuratomi ed8e60d804 Cleanups and fixes to cli
* Mark methods which are really functions as staticmethod
* Fix calls to other staticmethods to use the subclass rather than the
  base class so that any inheritance overriding will be honored.
* Remove unnecessary logic and dead code
* Fix a typo in a docstring of how to implement subclass init_parser()
  methods
* Call superclass's post_process_args in ansible-doc
* Fix copyright comment according to suggested practice
6 years ago
Toshio Kuratomi 7e92ff823e Split up the base_parser function
The goal of breaking apart the base_parser() function is to get rid of
a bunch of conditionals and parameters in the code and, instead, make
code look like simple composition.

When splitting, a choice had to be made as to whether this would operate
by side effect (modifying a passed in parser) or side effect-free
(returning a new parser everytime).

Making a version that's side-effect-free appears to be fighting with the
optparse API (it wants to work by creating a parser object, configuring
the object, and then parsing the arguments with it) so instead, make it
clear that our helper functions are modifying the passed in parser by
(1) not returning the parser and (2) changing the function names to be
more clear that it is operating by side-effect.

Also move all of the generic optparse code, along with the argument
context classes, into a new subdirectory.
6 years ago
Toshio Kuratomi afdbb0d9d5 Save the command line arguments into a global context
* Once cli args are parsed, they're constant.  So, save the parsed args
  into the global context for everyone else to use them from now on.
* Port cli scripts to use the CLIARGS in the context
* Refactor call to parse cli args into the run() method
* Fix unittests for changes to the internals of CLI arg parsing
* Port callback plugins to use context.CLIARGS
  * Got rid of the private self._options attribute
  * Use context.CLIARGS in the individual callback plugins instead.
  * Also output positional arguments in default and unixy plugins
  * Code has been simplified since we're now dealing with a dict rather
    than Optparse.Value
6 years ago
Toshio Kuratomi fcd1486b51 VALID_ACTIONS for cli subcommands will now be a frozenset (#50058) 6 years ago
Toshio Kuratomi 40144c7486 Remove dead code in ansible-inventory
This piece of code is only needed with ansible < 2.3.x (which is now EOL)
6 years ago
Toshio Kuratomi 3fba006207 Update bare exceptions to specify Exception.
This will keep us from accidentally catching program-exiting exceptions
like KeyboardInterupt and SystemExit.
6 years ago
Abhijeet Kasurde 162d9497ba
Ad-hoc command: fix 'any' call in play_ds (#49852)
* Ad-hoc command: fix 'any' call in play_ds
* Unit test for ad-hoc cli
* Review comments

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
6 years ago
Abhijeet Kasurde 013c42b14f
Misc typo fixes (#49816)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
6 years ago
Dag Wieers baf0ad2309 Docs: Add a "seealso" section to the module docs (#45949)
* Docs: Add a separate  "seealso" section to the module docs
to list related modules and/or related references. This clears up the notes
section for things that are actual notes.

So you can add a section in your module documentation and four types of
references are possible.

    seealso:

    # Reference by module name
    - module: aci_tenant

    # Reference by module name, including description
    - module: aci_tenant
      description: ACI module to create tenants on a Cisco ACI fabric.

    # Reference by rST documentation anchor
    - ref: aci_guide
      description: Detailed information on how to manage your ACI infrastructure using Ansible.

    # Reference by Internet resource
    - name: APIC Management Information Model reference
      description: Complete reference of the APIC object model.
      link: https://developer.cisco.com/docs/apic-mim-ref/

This PR also includes:

- Implements ansible-doc support
- Implements schema support for the seealso options
- Updates to the development documentation
- Rename filter convert_symbols_to_format to rst_ify, cfr the existing html_ify and tty_ify filters
  - This makes the existing template a lot easier to read and fixes the confusion I had myself rereading the template (again).
- We fixed the possible suboption types (which was limited to 'bool' only)

* Use latest stable instead of devel docs
6 years ago
Brian Coca 42a13d15f1
add path info to role list (#49346)
* add path info to role list

 - use same display format for both listing all and specific roles


Co-Authored-By: bcoca <bcoca@users.noreply.github.com>
6 years ago
Brian Coca 0c1f62065c
make adhoc include_role/task work again! (#49247)
* adhoc include_role/task work again!
  - fix task, pass if set
6 years ago
Brian Coca 20270680fc
fixes to ansible-doc (#47682)
fixes to ansible-doc
 - change json to always be type dependent
 - change changelog generation to loop over the options
 - warn about ignoring module path
6 years ago
Abhijeet Kasurde c9325ca247
Override help string version (#49545)
This fix adds additional help message to version command options

Fixes: #20488

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
6 years ago
Alicia Cozine 9142cfc86f
fixes typos in ansible-vault docs (#49671) 6 years ago
thyme 8a30ceb347 Fix typo in confirm new vault password message (#49468) 6 years ago
Alan Rominger d536be6530 Avoid duplicated recursive calls in inventory CLI (#48598) 6 years ago
Jonathan Hanson 12a573a7db Fix type in ansible-galaxy info output (#49096)
Changed from 'intalled_version' to 'installed_version'
6 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
Martin Krizek a80c25cbd9
Do not use str() on exceptions (#46950) 6 years ago
Brian Coca 903cfa63cb
make inventory warnings a bit smarter (#46284)
less annoying for common cases
 add comment for 'tricky' conditional
6 years ago
Matt Martz 9949629e5a
Add toml inventory plugin (#41593)
* First pass at a toml inventory

* Make EXAMPLES yaml

* Remove unnecessary comment

* Small formatting changes

* Add ansible-inventory option to list as TOML

* TOML inventory improvements, to allow a more simple inventory, specifically related to children

* changelog

* Simplify logic

* Dedupe _expand_hostpattern, making it available to all inventory plugins

* Don't make the TOML inventory dependent on the YAML inventory

* Quote IP address values

* Add more TOML examples

* Further cleanups

* Enable the toml inventory to run by default

* Create toml specific dumper

* 2.8

* Clean up imports

* No toml pygments lexer

* Don't raise an exception early when toml isn't present, and move toml to the end, since it requires an external dep

* Require toml>=0.10.0

* Further clean up of empty data

* Don't require toml>=0.10.0, but prefer it, add code for fallback in older versions

* Ensure we actually pass an encoder to toml.dumps

* Simplify recursive data converter

* Appease tests, since we haven't limited controller testing to 2.7+

* Update docstring for convert_yaml_objects_to_native

* remove outdated catching of AttributeError

* We don't need to catch ImportError when import ansible.plugins.inventory.toml

* Add note about what self.dump_funcs.update is doing

* Address some things

* A little extra comment

* Fix toml availability check

* Don't create an intermediate list

* Require toml file extension

* Add metadata

* Remove TOML docs from intro_inventory to prevent people from getting the wrong idea

* It's in defaults, remove note

* core supported, indicate very clearly that this is preview status
6 years ago
Abhijeet Kasurde d4bb67cac0 ansible-doc: list types of plugin available (#47055)
This fix allows user to view types of plugin available in
ansible-doc command.

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
6 years ago
Toshio Kuratomi 7eda5c50ae Update ansible-doc for invariants in the metadata/plugin_doc api
* There will always be metadata returned so no need to check for its
  existence first.
* There won't be version or metadata_version as those are being removed
  by the api.  So all checks for those need to be removed.
6 years ago
Toshio Kuratomi e5a245de94 Fix from sivel for ansible-doc
* Major slow down due to using the wrong loader for plugin_types
* traceback due to adding httpapi and cliconf plugins to the plugins we
allow ansible-doc to process
6 years ago
Brian Coca fce9673ac1 Adoc fixes (#47137)
* removed hardcoded loader/plugins list
* updated a few errors to keep orig object
* fix httpapi/cliconf listing
* ansible-doc fixes
* show undocumented as UNDOCUMENTEd
* added missing undoc
6 years ago
Matt Clay a11f631ee4 Python 3.8 collections compatibility fixes.
Includes a new pylint blacklist plugin to prevent regressions.
6 years ago
Brian Coca ddb3764039
avoid empty groups in json output (#45621)
they get confused as hosts by script plugin

fixes #45601
6 years ago
Daniel Nägele edaa0b5245 ansible-pull: allow specifying --diff from check_opts cli flag group (#37645) 6 years ago
Toshio Kuratomi 0873d46617 Fix ansible-doc and docsite generation for removed modules
* Fix ansible-doc wrt removed modules
  * Fix listing of modules ia ansible-doc to not complain about removed modules
    Removed modules are marked as such in the metadata but nowhere else.
    Need to retrieve the metadata when a module doesn't have a doc so that
    we can tell if it falls under this case.
  * omit removed modules from json dump
  * Print an error that the module has been removed if attempting to run
    ansible-doc on that specific module

* Get plugin_formatter to stop outputting removed modules
6 years ago
Matt Martz aa07da21a3
Bump sudo/su deprecation to 2.9 (#44581) 6 years ago
Sam Doran 05fff27415
Pass path to GalaxyRole object (#43051)
This will list all roles in all paths in roles_path rather than just the first path in roles_path.
6 years ago
Toshio Kuratomi 0e7b470a01 Remove deprecated tags config option (#44479)
* Remove deprecated tags config option

* wordsmith porting guide entry

acozine via github
6 years ago
Matt Martz 617372f8c0
Mass nuke deprecated items that are easily removed. ci_complete (#44320) 6 years ago
Toshio Kuratomi 734384b91d Fix config manager to show errors
If there were fatal bugs in this portion of config, they would never be displayed
because config would fail to load and then every^U (Exageration... only
half of every) other part of the code which depended on config to be
loaded would fail before we ever got around to a section of code that
would process UNABLE.

Remove the try except from here so that we are able to debug this code
6 years ago
joren485 d03b9eddf6 Remove unused imports from /bin and lib/ansible/cli (#43440)
* Remove unused imports from lib/ansible/cli

* Remove unused imports from bin/
6 years ago
Eric Rinish 551501f326 use faster method to get short_description from DOCUMENTATION (#42705)
* use faster method to get short_description from DOCUMENTATION

* fixed pep8 whitespace

* fixed blank line
6 years ago
Brian Coca 917b6b0d09 import_playbook is not usable from inside a play
(cherry picked from commit 55dddf530ad094810929823f80c4546e97a69ac7)
6 years ago
Brian Coca ac1f05478e Allow to specifically customize console's color 6 years ago
Matt Martz 35b4b1923d Allow adhoc to execute includes and imports 6 years ago
Toshio Kuratomi ccbac66128 Revert "Make ansible doesn't parse template-like password in user's input (#42275)"
This reverts commit de40ac02a5.

Passwords from the cli need to remain bytes on input otherwise we have
encoding problems when users input non-utf8
6 years ago
Zhikang Zhang de40ac02a5
Make ansible doesn't parse template-like password in user's input (#42275)
NOTE:
1. Use unsafe decorator but not builtin escape wrapper in jinja2
since ansible will try parse ssh password twice, the builtin
escape wrapper will be removed during the first parse.
2. Use class AnsibleUnsafeText but not '!unsafe' syntax since
passwords are not loaded by YAML env, '!unsafe' syntax doesn't
work for them.
6 years ago
Brian Coca de0e11c0d5 avoid loading vars on unspecified basedir (cwd) (#42067)
* avoid loading vars on unspecified basedir (cwd)
6 years ago
Luke Short 5024b4e445 Update the minimum Ansible version to 2.4. (#41989) 6 years ago
Brian Coca 2affb5f729 doc fix 6 years ago
Brian Coca 05a49d6eb6
handle groups correctly when they are 'null' (#41698)
* handle groups correctly when they are 'null'

 - even if defined as mapping but having no keys, objects shoudl still be processed correctly
 - also add ansilbe_verbosity to vars not to display in ansible-inventory

fixes #41692
6 years ago
Abhijeet Kasurde f21307da91 Add more info related to galaxy sub commands (#41085)
Fixes: #17469

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
6 years ago
Matt Davis 25ab2a8153
fix truncated list functions in ansible-doc (#41281)
* fixed incomplete refactor of instance-level plugin list var
6 years ago
Matt Davis 087efe4232
fix ansible-doc regression from missing plugins (#41167) 6 years ago
Abhijeet Kasurde 63d993e07f Minor typos in galaxy cli (#41083)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
6 years ago
Ben Thomasson 01e1b51e33 Fix typo in the ansible-inventory --host error (#41142) 6 years ago
Matt Davis 096d243526 adds ansible-doc JSON plugin data dump
* used for changelog generation of new plugins
6 years ago
Brian Coca c86fd6e2df Fix error reporting on bad type for config setting 6 years ago
Brian Coca 73b9892605 add keywords handling to ansible-doc
also add check for sequence of string types before we force a join
6 years ago
Brian Coca cbb6a7f4e8
Enabled unsafe and vault in JSON (#38759)
* allow to load json marked as unsafe or vault

 * centralized json code/decode, add vault support
 * use generics to allow for more varied inputs
 * allow inventory to dump vault w/o decrypting
 * override simplejson also
 * add entry for unsafe also
 * load vaulted and unsafe json, support unvaulting if secrets provided
6 years ago
Lars Kellogg-Stedman ebe7666d71 add 'localhost_warning' configuration option
Add the 'localhost_warning' configuration option. When set to 'false',
this will prevent Ansible from issuing a warning when the inventory is
empty and it is using an implicit inventory with only 'localhost'.

Closes #17086
6 years ago
Brian Coca e4dbabbef2 make individual bad paths a warning
still error if none of the paths provided was usable

fixes #39044
6 years ago
Matt Clay c262dbfd30 Use https for links to ansible.com domains. 6 years ago
Brian Coca 265d838ec9 fix displaying group vars in graph 6 years ago
Brian Coca bdbb89378f
centralize doc/config plugin lists (#38775)
* centralize doc/config plugin lists

also update list for generation in docsite
added note to ensure they are in sync

* updated shell page to list plugins

added some more docs hinting at plugins being configurable

* fix edit link for plugins
6 years ago
Brian Coca 1b9879ccbf remove unused optoins from inventory cli
fixes #31929
6 years ago
Adrian Likins 6e737c8cb6
Fix 'New Vault password' on vault 'edit' (#35923)
* Fix 'New Vault password' on vault 'edit'

ffe0ddea96 introduce a
change on 'ansible-vault edit' that tried to check
for --encrypt-vault-id in that mode. But '--encrypt-vault-id'
is not intended for 'edit' since the 'edit' should always
reuse the vault secret that was used to decrypt the text.

Change cli to not check for --encrypt-vault-id on 'edit'.

VaultLib.decrypt_and_get_vault_id() was change to return
the vault secret used to decrypt (in addition to vault_id
and the plaintext).

VaultEditor.edit_file() will now use 'vault_secret_used'
as returned from decrypt_and_get_vault_id() so that
an edited file always gets reencrypted with the same
secret, regardless of any vault id configuration or
cli options.

Fixes #35834
6 years ago
Toshio Kuratomi b98ad3a12b Compare byte strings to byte strings
* Fix a traceback in ansible-pull on python3 comparing output from
  subprocess with a text string.
* Rename variables that hold byte strings so we are clear that those are
  not text strings.
* Use to_text() to transform variable that's being displayed as it's
  less fragile than str().

Fixes #36962
6 years ago
Victor da Costa cb53b717a4 Ansible Galaxy: skel for network role #37241 (#37251)
* Skel for network role (#37241)

Skel and boilerplate for network role.

* Add network option as valid type
6 years ago
Dylan Murray 90943a3362 Add APB role_type to ansible-galaxy init (#36789)
* Add APB role_type to ansible-galaxy init

* Add handlers scaffolding

* Fix shippable errors by setting default

* Add unit tests and fix shippable

* Updates init description
6 years ago
Leigh Jenkin e224039586 Fixes #12353 #20977 adds new option to galaxy cli to preserve scm meta (#34642) 6 years ago
Adrian Likins 810fa7046b Fix ansible-console always asking for vault passwords
ansible-console was calling setup_vault_secrets
twice. Once directly and once via _play_prereqs()

The direct invocation was not setting auto_prompt=False.

However, the direct invocation isn't need at all so
this removes it so only _play_reqs() is used.
That fixes the unrequested vault password
prompting.

Fixes #33027
6 years ago
Brian Coca 3680d65d1d deal with no config for view
fixes #35965
6 years ago
Brian Coca b403653bd2
Inv export (#36188)
* add export option

* added 'export mode' to ansible-inventory

this optimizes the output for exporting inventory vs representing the 'ansible view'

fixes #30877

* added group priority when needed
6 years ago
Chris Houseknecht c20beeef37
Apply regex to dir name only (#35744) 6 years ago
John R Barker a23c95023b
Module deprecation: docs, scheme and tests (#34100)
Enforce module deprecation.
After module has reached the end of it's deprecation cycle we will replace it with a docs stub.

* Replace deprecated modules with docs-only sub
* Use of deprecated past deprecation cycle gives meaningful message (see examples below)
* Enforce documentation.deprecation dict via `schema.py`
* Update `ansible-doc` and web docs to display documentation.deprecation
* Document that structure in `dev_guide`
* Ensure that all modules starting with `_` have a `deprecation:` block
* Ensure `deprecation:` block is only used on modules that start with `_`
* `removed_in` A string which represents when this module needs **deleting**
* CHANGELOG.md and porting_guide_2.5.rst list removed modules as well as alternatives
* CHANGELOG.md links to porting guide index

To ensure that meaningful messages are given to the user if they try to use a module at the end of it's deprecation cycle we enforce the module to contain:
```python
if __name__ == '__main__':
    removed_module()
```
6 years ago
Adrian Likins ffe0ddea96
add a vault --encrypt-vault-to specify vault id to use for encrypt (#31067)
Enforce that there can be only one --new-vault-id or
--new-vault-password-file and use this instead of
--encrypt-vault-id

* Add a config option for default vault encrypt id
7 years ago
Matt Clay f9f6080630 Improve handling of ansible-doc sanity errors. 7 years ago
Pilou 217ff4498c ansible-config: add simple tests (#34900)
* Revert "Fix ansible-config with python3 (#34673)"

This reverts commit 2a9daaa45b.

* ansible-config: add simple tests

* Fix ansible-config with python3

* ansible-test: don't quote "unusual" characters
7 years ago
Tristan de Cacqueray 576335e53d Add GALAXY_TOKEN config option (#34621)
This change lets user store token in configuration file or environment to
prevent exposing the secret on the command line.
7 years ago
Brian Coca bbd6b8bb42 Temporary (#31677)
* allow shells to have per host options, remote_tmp

added language to shell
removed module lang setting from general as  plugins have it now
use get to avoid bad powershell plugin
more resilient tmp discovery, fall back to `pwd`
add shell to docs
fixed options for when frags are only options
added shell set ops in t_e and fixed option frags
normalize tmp dir usag4e

- pass tmpdir/tmp/temp options as env var to commands, making it default for tempfile
- adjusted ansiballz tmpdir
- default local tempfile usage to the configured local tmp
- set env temp in action

add options to powershell
shift temporary to internal envvar/params
ensure tempdir is set if we pass var
ensure basic and url use expected tempdir
ensure localhost uses local tmp
give /var/tmp priority, less perms issues
more consistent tempfile mgmt for ansiballz
made async_dir configurable
better action handling, allow for finally rm tmp
fixed tmp issue and no more tempdir in ballz
hostvarize world readable and admin users
always set shell tempdir
added comment to discourage use of exception/flow control

* Mostly revert expand_user as it's not quite working.

This was an additional feature anyhow.

Kept the use of pwd as a fallback but moved it to a second ssh
connection.  This is not optimal but getting that to work in a single
ssh connection was part of the problem holding this up.

(cherry picked from commit 395b714120522f15e4c90a346f5e8e8d79213aca)

* fixed script and other action plugins

ensure tmpdir deletion
allow for connections that don't support new options (legacy, 3rd party)
fixed tests
7 years ago
Matt Martz 2b66d9966c
Add a config toggle for agnostic become prompts, defaulting to False for the 2.5 release. Fixes #33999 (#34761) 7 years ago
Will Thames 9cb0c08d75 Ensure alternatives are displayed in deprecation warnings
Use plural `alternatives` key to display deprecation alternatives.
7 years ago
Matt Clay 15a04a3da7 Fix Python 3.7 syntax error. 7 years ago
Adam Miller ad337503e7 add missing > to ansible-doc help message (#34512)
Signed-off-by: Adam Miller <admiller@redhat.com>
7 years ago
Brian Coca 87c75b19dd
dont warn on not matching 'all' (#32806)
* dont warn on not matching 'all'

the implicit localhost warning shoudl be enough

* centralized no hosts handling

also extended info on implicit only
7 years ago
Brian Coca be5d68f3ad
add support for other scms to pull (#33152)
* add support for other scms to pull

* show choices for scms module in help
7 years ago
Brian Coca afa82be019 make become prompt method agnostic (#33789)
fixes #33747
7 years ago
Andreas Olsson b78ab37a94 Only expose rekey options to ansible-vault command
`ansible-vault` is the only cli command which knows how to handle the
rekey options `--new-vault-id` and `--new-vault-password-file`. No
point in exposing those rekey options to any of the other ansible
commands.

On a practical level I think this matters most in ensuring that
`--help` doesn't produce any false/unhelpful output.
7 years ago
Andreas Olsson 7bd54a51e2 Add --vault-id support to ansible-pull
Without this additional code snippet `ansible-pull` will still accept
the `--vault-id` option. It just won't pass the option along when
invoking `ansible-pull`.
7 years ago
Brian Coca ebd08d2a01 jsonify inventory (#32990)
* jsonify inventory
* smarter import, dont pass kwargs where not needed
* added datetime
* Eventual plan for json utilities to migrate to common/json_utils when we split
  basic.py no need to move jsonify to another file now as we'll do that later.
* json_dict_bytes_to_unicode and json_dict_unicode_to_bytes will also
  change names and move to common/text.py at that time (not to json).
  Their purpose is to recursively change the elements of a container
  (dict, list, set, tuple) into text or bytes, not to json encode or
  decode (they could be a generic precursor to that but are not limited
  to that.)
* Reimplement the private _SetEncoder which changes sets and datetimes
  into objects that are json serializable into a private function
  instead.  Functions are more flexible, less overhead, and simpler than
  an object.
* Remove code that handled simplejson-1.5.x and earlier.  Raise an error
  if that's the case instead.
  * We require python-2.6 or better which has the json module builtin to
    the stdlib.  So this is only an issue if the stdlib json has been
    overridden by a third party module and the simplejson on the system
    is 1.5.x or less.  (1.5 was released on 2007-01-18)
7 years ago
Valentin Krasontovitsch bf7f56f413 Fix typo in usage of encrypt_string command (#32961) 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
Adrian Likins 86dc3c09ac
Fix vault --ask-vault-pass with no tty (#31493)
* Fix vault --ask-vault-pass with no tty

2.4.0 added a check for isatty() that would skip setting up interactive
vault password prompts if not running on a tty.

But... getpass.getpass() will fallback to reading from stdin if
it gets that far without a tty. Since 2.4.0 skipped the interactive
prompts / getpass.getpass() in that case, it would never get a chance
to fall back to stdin.

So if 'echo $VAULT_PASSWORD| ansible-playbook --ask-vault-pass site.yml'
was ran without a tty (ie, from a jenkins job or via the vagrant
ansible provisioner) the 2.4 behavior was different than 2.3. 2.4
would never read the password from stdin, resulting in a vault password
error like:

        ERROR! Attempting to decrypt but no vault secrets found

Fix is just to always call the interactive password prompts based
on getpass.getpass() on --ask-vault-pass or --vault-id @prompt and
let getpass sort it out.

* up test_prompt_no_tty to expect prompt with no tty

We do call the PromptSecret class if there is no tty, but
we are back to expecting it to read from stdin in that case.

* Fix logic for when to auto-prompt vault pass

If --ask-vault-pass is used, then pretty much always
prompt.

If it is not used, then prompt if there are no other
vault ids provided and 'auto_prompt==True'.

Fixes vagrant bug https://github.com/hashicorp/vagrant/issues/9033

Fixes #30993
7 years ago
Sloane Hertel 53ade280a3 clarify docs for --flush-cache (#32799) 7 years ago
Matt Davis 5ff36c3423 Enable autoloading of inventory plugins (#32709)
* Automatically loads and executes an inventory plugin specified by a standard YAML inventory config file containing a `plugin` key at its root.
* Moved inventory PluginLoader to a shared global instance.
7 years ago
Dag Wieers 9a6615a905
Make newer stuff PEP8 compliant (#26951)
So we fixed everything that was not a module to be PEP8 compliant, and
in the meantime these 5 new files were additionally disabled from PEP8
testing.

This fixes it.

Also update Copyright/License statements.
7 years ago
jctanner c76ce54aee
Add -f/--list_files option to the ansible-doc command for faster list (#32524)
Add -f/--list_files option to the ansible-doc command for faster listing of plugins and show where they were found.
7 years ago
Jacob Floyd ca8668f08b Use playbook callbacks for adhoc commands too
This makes adhoc mirror playbook callback functionality by running a
callback before and after all tasks have run. Adhoc commands now call:

- v2_playbook_on_start
- v2_playbook_on_stats

NOTE: When v2_playbook_on_start is called, a dummy playbook is provided
that says its _file_name is __adhoc_playbook__. All callback plugins
that provide v2_playbook_on_start access the _file_name attribute, so
this should maintain backward compatibility when those plugins are
called with adhoc commands even though they would not have been called
previously. The adhoc play is also added to _entries for any private
callback plugins that might be using this callback.
7 years ago
Brian Coca 95b31a3b61
Playbook dir option (#32275)
* initial add of basedir

Allows you to set a 'playbook dir' for adhoc, inventory and console to allow for 'relative path loading'
7 years ago
Brian Coca 75a6f9dbc2
remove misleading group vars as they are flat (#32276)
* remove misleading group vars as they are flat

* fixed vars display
7 years ago
Toshio Kuratomi 2e12a5f8c2 Revert "Removed a force conditional (#28851)" (#32282)
This reverts commit 07acc579db.

On closer examination of this code, the conditional that had force in it
was not a parent of this one.  So handling of force is needed i both
branches.

See the recent comments on #23391
7 years ago
Brian Coca ca71a50459 Avoid default inventory proccessing for pull (#32135)
* Avoid default inventory proccessing for pull

- now pull's own special inventory processing should work correctly
- also removed ineffective set_defaults

fixes #31449

* use class property instead

* only do localhost for adhoc

(cherry picked from commit aad5d1432583c4aa4105b774f38c80498e85de59)
7 years ago
Brian Coca 90e8071d48 fix inventory loading for ansible-doc
fixes #31995
7 years ago
Jerry Chong 4acd0de8f0 Remove extraneous comment block (#31865) 7 years ago
Ilya Margolin 9bc60cd05e Fix -M/--module-path option for ansible-doc and ansible-console (#31744)
Fixes #31743
7 years ago
Adrian Likins 297dfb1d50 Vault secrets script client inc new 'keyring' client (#27669)
This adds a new type of vault-password script  (a 'client') that takes advantage of and enhances the 
multiple vault password support.

If a vault password script basename ends with the name '-client', consider it a vault password script client. 

A vault password script 'client' just means that the script will take a '--vault-id' command line arg.

The previous vault password script (as invoked by --vault-password-file pointing to an executable) takes
no args and returns the password on stdout. But it doesnt know anything about --vault-id or multiple vault
passwords.

The new 'protocol' of the vault password script takes a cli arg ('--vault-id') so that it can lookup that specific
vault-id and return it's password.

Since existing vault password scripts don't know the new 'protocol', a way to distinguish password scripts
that do understand the protocol was needed.  The convention now is to consider password scripts that are
named like 'something-client.py' (and executable) to be vault password client scripts.

The new client scripts get invoked with the '--vault-id' they were requested for. An example:

     ansible-playbook --vault-id my_vault_id@contrib/vault/vault-keyring-client.py some_playbook.yml

That will cause the 'contrib/vault/vault-keyring-client.py' script to be invoked as:

     contrib/vault/vault-keyring-client.py --vault-id my_vault_id

The previous vault-keyring.py password script was extended to become vault-keyring-client.py. It uses
the python 'keyring' module to request secrets from various backends. The plain 'vault-keyring.py' script
would determine which key id and keyring name to use based on values that had to be set in ansible.cfg.
So it was also limited to one keyring name.

The new vault-keyring-client.py will request the secret for the vault id provided via the '--vault-id' option.
The script can be used without config and can be used for multiple keyring ids (and keyrings).

On success, a vault password client script will print the password to stdout and exit with a return code of 0.
If the 'client' script can't find a secret for the --vault-id, the script will exit with return code of 2 and print an error to stderr.
7 years ago
Brian Coca 83dec70ad8 validate that existing dest is valid directory 7 years ago
Brian Coca 74107ff7cc better message for unsupported include/imports
adhoc cannot currently execute these actions
7 years ago
Brian Coca f00d47fac0 dont follow symlinks for inventories
now symlink dir is checked for locality of group/host_vars

fixes #31195
7 years ago
Adrian Likins 278ff19bea Handle vault decrypt --output=- (#31066)
In cli.CLI.unfrack_path callback, special case if the
value of '--output' is '-', and avoid expanding
it to a full path.

vault cli already has special cases for '-', so it
just needs to get the original value to work.

Fixes #30550
7 years ago
Brian Coca fc745920c7 fixed pull's ansible/git invocation options (#30938)
* fixed ansible/git invocation options

now falls back to using localhost as 'all' does not include implicit accidentally anymore

fixes #30636

* better fix

* qfq9
7 years ago
Brian Coca 4291edd820 remove 'new internal vars' from dumps
fixes #30924
7 years ago
Brian Coca 7a312b6cf7 add ability to set default tags in config 7 years ago
Adrian Likins 174cb1f33c Check number of vault secrets after setup. (#30520)
This is to catch vault secrets from config and
cli. Previously vault_password_file in config was
missed since it was added by setup_vault_secrets,
so check after setup_vault_secrets.
7 years ago
Adrian Likins 307be59092 Don't ask for password confirm on 'ansible-vault edit' (#30514)
* Don't ask for password confirm on 'ansible-vault edit'

This is to match the 2.3 behavior on:

        ansible-vault edit encrypted_file.yml

Previously, the above command would consider that a 'new password'
scenario and prompt accordingly, ie:

        $ ansible-vault edit encrypted_file.yml
        New Password:
        Confirm New Password:

The bug was cause by 'create_new_password' being used for
'edit' action. This also causes the previous implicit 'auto prompt'
to get triggered and prompt the user.

Fix is to make auto prompt explicit in the calling code to handle
the 'edit' case where we want to auto prompt but we do not want
to request a password confirm.

Fixes #30491
7 years ago
Brian Coca 24d4787b2d Lookup docs (#30280)
* finalize lookup documentation
* minor fixes to ansible-doc
 - actually show which file caused error on when listing plugins
 - removed redundant display of type and name
* smart quote fixes from toshio
7 years ago
Brian Coca 8799038a89 deprecated include
added docs for new actions that take over include duties
7 years ago
Brian Coca c027ad943e remove dupe deprecation on config (#30364)
* remove dupe deprecation on config

also move failed typing to same place to use 'standard' display vs hack.
7 years ago
Matt Clay 442af3744e Miscellaneous pylint fixes.
The following rules are no longer disabled:

- bad-format-string
- duplicate-key
- lost-exception
- trailing-newlines
- unexpected-keyword-arg
- useless-suppression
- using-constant-test
7 years ago
Brian Coca 2165bac212 module and vault fixes (#29663)
* module and vault fixes

- fix module_path cli option and usage, which fixes #29653
- move --output to be in subset of vault cli, no need for all vault enabled cli to use it
- added debug to loader to see directories added
7 years ago
Toshio Kuratomi cfaea8a053 Change ansible-doc usage to show -a is for internal use (#29603)
* Change ansible-doc usage to show -a is for internal use

ansible-doc -a is for testing that documentation is sane.  It should not
be used by normal users in production.  The main reason for this is that
it is designed to fail if there are any undocumented modules or plugins.
This is good for testing that all plugins we ship are documented.  It is
not good for end users who may have undocumented third-party plugins.
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
Adrian Likins 89c973445c generate rst doc pages for command line tools (#27530)
* let generate_man also gen rst pages for cli tools
* make template-file, output-dir, output format cli options for generate_man
* update main Makefile to use generate_man.py for docs (man pages and rst)
* update vault docs that use :option:
* Edits based on
6e34ea6242 and
a3afc78535

* add a optparse 'desc' to lib/ansible/cli/config.py 

  The man page needs a short desc for the 'NAME' field
  which it gets from the option parse 'desc' value.

  Fixes building ansible-config man page.

* add trim_docstring from pep257 to generate_man

  use pep258 docstring trim function to fix up any indention
  weirdness inherit to doc strings (ie, lines other than
  first line being indented.

* Add refs to cli command actions

To reference ansible-vaults --vault-id option, use:

:option:`The link text here <ansible-vault --vault-id>`

or:

:option:`--vault-id <ansible-vault --vault-id>`

To reference ansible-vault's 'encrypt' action, use:

:ref:`The link text here <ansible_vault_encrypt>`

or most of the time:

:ref:`ansible-vault encrypt <ansible_vault_encrypt>`
7 years ago
Rene Moser da488a8db5 config: use path list for default inventory
This allows to use a pathlist in the ansible.cfg:

  [default]
  inventory = path/inventory:other_path/inventory

Since ansible allows to use --inventory on CLI more then once, we should also support a pathlist in the config.
7 years ago
Brian Coca c51a4bc57d ansible-config view fixes 7 years ago
Sam Doran 31dc5342f3 Do not try to process an empty metai/main.yml file
If an empty meta/main.yml file exists, ansible-galaxy threw an unhelpful exception. Now, a warning message is printed and the installation does not fail.

See https://stackoverflow.com/questions/45432994/ansible-galaxy-fails-on-dependency-with-empty-meta-main-yml
7 years ago
Brock R 07acc579db Removed a force conditional (#28851)
This `if not force:` conditional will never be false.  So there is no need for it.
7 years ago
Brian Coca 9f12d66506 fix ansible-config view 7 years ago
Brian Coca e79b6a03fc fix plugin docs broken by previous commit (#28601)
* fix plugin docs broken by previous commit

also removed verbosity requirements, goes back to displaying all data by default

* pepe should be full by now
7 years ago
Adrian Likins 1f962bd937 Fix config value type for VAULT_IDENTITY_LIST (#28678)
Was using the 'value_type' key, but didn't get updated
to the new 'type' key in merge.

Fix playbooks cli so it uses VAULT_IDENTITY_LIST as well.
7 years ago
Toshio Kuratomi af2073d057 metadata 1.1
* Add network value to support_by field.
* New support_by value, certified
* Deprecate curated in favor of certified
* Add conversion from 1.0 to 1.1 to metadata-tool
* Add supported by Red Hat field to ansible-doc output
7 years ago
Brian Coca c27248db60 ansible-inventory cli tool (#22477)
* ansible-inventory cli tool

added vars dump to graph
made yaml inventory dump actual yaml inventory format
cleaner dump
fixed graph, no dump needed
add pulling in host/group vars
pep indentation crime
added docstring for manpage autodoc
remove ansible_facts from output
added api compat layer
allow import from new and old APIs
better conditional for <2.4
pe4+p4

test stuck on OS X (seems popular today) but passes rest, merging anyways
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
Adrian Likins 8003437ebc prompt for new pass on create/encrypt if none specified (#28185)
* prompt for new pass on create/encrypt if none specified

Make 'ansible-vault' edit or encrypt prompt for a password
if none or provided elsewhere.

Note: ansible-playbook does not prompt if not vault password
is provided

* dont show vault password prompts if not a tty
7 years ago
Adrian Likins 5739bb075f Vault secrets default vault ids list (#28190)
* Add config option for a default list of vault-ids

This is the vault-id equilivent of ANSIBLE_DEFAULT_PASSWORD_FILE
except ANSIBLE_DEFAULT_VAULT_IDENTITY_LIST is a list.
7 years ago
Adrian Likins e287af1ac8 Vault secrets empty password (#28186)
* Better handling of empty/invalid passwords

empty password files are global error and cause an
exit. A warning is also emitted with more detail.

ie, if any of the password/secret sources provide
a bogus password (ie, empty) or fail (exception,
 ctrl-d, EOFError), we stop at the first error and exit. 

This makes behavior when entering empty password at
prompt match 2.3 (ie, an error)
7 years ago
René Moser 13dec9259f galaxy-cli: selective install roles in requirements file (#21412)
* galaxy-cli: force install selected roles in requirements file

* only when requirements file but also handle uninstalled roles
7 years ago
giovannisciortino d3e48a51f5 Add check mode support to ansible-pull (#28021)
Fixes #27989
7 years ago
Adrian Likins 82f550e8cd Add prompt formats for 2.3 compat ask-vault-pass (#27974)
The prompt_formats dict didn't get the 'prompt_ask_vault_pass'
item added for interactive --ask-vault-pass, which
caused "KeyError: u'prompt_ask_vault_pass'"

Fixes #27885
7 years ago
Adrian Likins c38ff3b8f8 pylint fixes for vault related code (#27721)
* rm unneeded parens following assert
* rm unused parse_vaulttext_envelope from yaml.constructor
* No longer need index/enumerate over vault_ids
* rm unnecessary else
* rm unused VaultCli.secrets
* rm unused vault_id arg on VaultAES.decrypt()

pylint: Unused argument 'vault_id'
pylint: Unused parse_vaulttext_envelope imported from ansible.parsing.vault
pylint: Unused variable 'index'
pylint: Unnecessary parens after 'assert' keyword
pylint: Unnecessary "else" after "return" (no-else-return)
pylint: Attribute 'editor' defined outside __init__

* use 'dummy' for unused variables instead of _

Based on pylint unused variable warnings.

Existing code use '_' for this, but that is old
and busted. The hot new thing is 'dummy'. It
is so fetch.

Except for where we get warnings for reusing
the 'dummy' var name inside of a list comprehension.

* Add super().__init__ call to PromptVaultSecret.__init__
pylint: __init__ method from base class 'VaultSecret' is not called (super-init-not-called)

* Make FileVaultSecret.read_file reg method again

The base class read_file() doesnt need self but
the sub classes do.

Rm now unneeded loader arg to read_file()

* Fix err msg string literal that had no effect
pylint: String statement has no effect

The indent on the continuation of the msg_format was wrong
so the second half was dropped.

There was also no need to join() filename (copy/paste from
original with a command list I assume...)

* Use local cipher_name in VaultEditor.edit_file not instance
pylint: Unused variable 'cipher_name'
pylint: Unused variable 'b_ciphertext'

Use the local cipher_name returned from parse_vaulttext_envelope()
instead of the instance self.cipher_name var.

Since there is only one valid cipher_name either way, it was
equilivent, but it will not be with more valid cipher_names

* Rm unused b_salt arg on VaultAES256._encrypt*
pylint: Unused argument 'b_salt'

Previously the methods computed the keys and iv themselves
so needed to be passed in the salt, but now the key/iv
are built before and passed in so b_salt arg is not used
anymore.

* rm redundant import of call from subprocess
pylint: Imports from package subprocess are not grouped

use via subprocess module now instead of direct
import.

* self._bytes is set in super init now, rm dup

* Make FileVaultSecret.read_file() -> _read_file()

_read_file() is details of the implementation of
load(), so now 'private'.
7 years ago