2017-11-09 20:04:40 +00:00
|
|
|
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
|
2015-04-15 23:32:44 +00:00
|
|
|
# (c) 2015 Toshio Kuratomi <tkuratomi@ansible.com>
|
2017-11-09 20:04:40 +00:00
|
|
|
# (c) 2017, Peter Sprygada <psprygad@redhat.com>
|
|
|
|
# (c) 2017 Ansible Project
|
2014-10-15 23:22:54 +00:00
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
|
|
|
|
2015-06-16 19:46:11 +00:00
|
|
|
import fcntl
|
|
|
|
import os
|
2015-12-24 21:00:53 +00:00
|
|
|
import shlex
|
2017-08-15 20:38:59 +00:00
|
|
|
from abc import abstractmethod, abstractproperty
|
2015-12-17 17:43:36 +00:00
|
|
|
from functools import wraps
|
|
|
|
|
2014-11-14 22:14:08 +00:00
|
|
|
from ansible import constants as C
|
2016-09-07 05:54:17 +00:00
|
|
|
from ansible.module_utils._text import to_bytes, to_text
|
2017-08-15 20:38:59 +00:00
|
|
|
from ansible.plugins import AnsiblePlugin
|
2018-11-20 23:06:51 +00:00
|
|
|
from ansible.utils.display import Display
|
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
2019-02-11 17:27:44 +00:00
|
|
|
from ansible.plugins.loader import connection_loader, get_shell_plugin
|
2018-07-02 12:41:00 +00:00
|
|
|
from ansible.utils.path import unfrackpath
|
2016-09-07 05:54:17 +00:00
|
|
|
|
2018-11-20 23:06:51 +00:00
|
|
|
display = Display()
|
2015-06-16 19:46:11 +00:00
|
|
|
|
2017-03-23 20:35:05 +00:00
|
|
|
|
2015-05-13 15:58:46 +00:00
|
|
|
__all__ = ['ConnectionBase', 'ensure_connect']
|
|
|
|
|
2016-03-16 18:20:02 +00:00
|
|
|
BUFSIZE = 65536
|
|
|
|
|
2015-05-13 15:58:46 +00:00
|
|
|
|
|
|
|
def ensure_connect(func):
|
|
|
|
@wraps(func)
|
|
|
|
def wrapped(self, *args, **kwargs):
|
2017-01-21 03:42:20 +00:00
|
|
|
if not self._connected:
|
|
|
|
self._connect()
|
2015-05-13 15:58:46 +00:00
|
|
|
return func(self, *args, **kwargs)
|
|
|
|
return wrapped
|
|
|
|
|
2014-11-14 22:14:08 +00:00
|
|
|
|
2017-08-15 20:38:59 +00:00
|
|
|
class ConnectionBase(AnsiblePlugin):
|
2014-11-14 22:14:08 +00:00
|
|
|
'''
|
|
|
|
A base class for connections to contain common code.
|
|
|
|
'''
|
|
|
|
|
2015-03-21 03:48:52 +00:00
|
|
|
has_pipelining = False
|
2017-06-02 11:14:11 +00:00
|
|
|
has_native_async = False # eg, winrm
|
|
|
|
always_pipeline_modules = False # eg, winrm
|
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
2019-02-11 17:27:44 +00:00
|
|
|
has_tty = True # for interacting with become plugins
|
2015-09-10 19:55:59 +00:00
|
|
|
# When running over this connection type, prefer modules written in a certain language
|
|
|
|
# as discovered by the specified file extension. An empty string as the
|
|
|
|
# language means any language.
|
|
|
|
module_implementation_preferences = ('',)
|
2016-02-02 18:13:02 +00:00
|
|
|
allow_executable = True
|
2015-03-21 03:48:52 +00:00
|
|
|
|
2017-11-09 20:04:40 +00:00
|
|
|
# the following control whether or not the connection supports the
|
|
|
|
# persistent connection framework or not
|
|
|
|
supports_persistence = False
|
|
|
|
force_persistence = False
|
|
|
|
|
2018-04-11 15:53:05 +00:00
|
|
|
default_user = None
|
|
|
|
|
2018-01-16 05:15:04 +00:00
|
|
|
def __init__(self, play_context, new_stdin, shell=None, *args, **kwargs):
|
2017-08-20 15:20:30 +00:00
|
|
|
|
|
|
|
super(ConnectionBase, self).__init__()
|
|
|
|
|
2015-04-15 23:32:44 +00:00
|
|
|
# All these hasattrs allow subclasses to override these parameters
|
2015-07-21 16:12:22 +00:00
|
|
|
if not hasattr(self, '_play_context'):
|
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
2019-02-11 17:27:44 +00:00
|
|
|
# Backwards compat: self._play_context isn't really needed, using set_options/get_option
|
2015-07-21 16:12:22 +00:00
|
|
|
self._play_context = play_context
|
2015-04-24 06:47:56 +00:00
|
|
|
if not hasattr(self, '_new_stdin'):
|
|
|
|
self._new_stdin = new_stdin
|
2015-04-15 23:32:44 +00:00
|
|
|
if not hasattr(self, '_display'):
|
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
2019-02-11 17:27:44 +00:00
|
|
|
# Backwards compat: self._display isn't really needed, just import the global display and use that.
|
2015-07-23 14:24:50 +00:00
|
|
|
self._display = display
|
2015-04-15 23:32:44 +00:00
|
|
|
if not hasattr(self, '_connected'):
|
|
|
|
self._connected = False
|
2014-11-14 22:14:08 +00:00
|
|
|
|
2015-06-16 19:46:11 +00:00
|
|
|
self.success_key = None
|
|
|
|
self.prompt = None
|
2015-11-24 14:09:54 +00:00
|
|
|
self._connected = False
|
2017-11-09 20:04:40 +00:00
|
|
|
self._socket_path = None
|
|
|
|
|
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
2019-02-11 17:27:44 +00:00
|
|
|
# helper plugins
|
|
|
|
self._shell = shell
|
|
|
|
|
|
|
|
# we always must have shell
|
2015-06-29 19:41:51 +00:00
|
|
|
if not self._shell:
|
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
2019-02-11 17:27:44 +00:00
|
|
|
self._shell = get_shell_plugin(shell_type=getattr(self, '_shell_type', None), executable=self._play_context.executable)
|
|
|
|
|
|
|
|
self.become = None
|
|
|
|
|
|
|
|
def set_become_plugin(self, plugin):
|
|
|
|
self.become = plugin
|
2015-06-29 19:41:51 +00:00
|
|
|
|
2015-11-24 14:09:54 +00:00
|
|
|
@property
|
|
|
|
def connected(self):
|
2016-01-05 03:23:12 +00:00
|
|
|
'''Read-only property holding whether the connection to the remote host is active or closed.'''
|
2015-11-24 14:09:54 +00:00
|
|
|
return self._connected
|
|
|
|
|
2017-11-09 20:04:40 +00:00
|
|
|
@property
|
|
|
|
def socket_path(self):
|
|
|
|
'''Read-only property holding the connection socket path for this remote host'''
|
|
|
|
return self._socket_path
|
|
|
|
|
2015-12-24 21:00:53 +00:00
|
|
|
@staticmethod
|
|
|
|
def _split_ssh_args(argstring):
|
|
|
|
"""
|
|
|
|
Takes a string like '-o Foo=1 -o Bar="foo bar"' and returns a
|
|
|
|
list ['-o', 'Foo=1', '-o', 'Bar=foo bar'] that can be added to
|
|
|
|
the argument list. The list will not contain any empty elements.
|
|
|
|
"""
|
2016-03-09 19:27:19 +00:00
|
|
|
try:
|
|
|
|
# Python 2.6.x shlex doesn't handle unicode type so we have to
|
|
|
|
# convert args to byte string for that case. More efficient to
|
|
|
|
# try without conversion first but python2.6 doesn't throw an
|
|
|
|
# exception, it merely mangles the output:
|
|
|
|
# >>> shlex.split(u't e')
|
|
|
|
# ['t\x00\x00\x00', '\x00\x00\x00e\x00\x00\x00']
|
2016-09-07 05:54:17 +00:00
|
|
|
return [to_text(x.strip()) for x in shlex.split(to_bytes(argstring)) if x.strip()]
|
2016-03-09 19:27:19 +00:00
|
|
|
except AttributeError:
|
2016-10-02 21:55:55 +00:00
|
|
|
# In Python3, shlex.split doesn't work on a byte string.
|
2016-09-07 05:54:17 +00:00
|
|
|
return [to_text(x.strip()) for x in shlex.split(argstring) if x.strip()]
|
2015-12-24 21:00:53 +00:00
|
|
|
|
2015-04-15 23:32:44 +00:00
|
|
|
@abstractproperty
|
|
|
|
def transport(self):
|
|
|
|
"""String used to identify this Connection class from other classes"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def _connect(self):
|
|
|
|
"""Connect to the host we've been initialized with"""
|
2015-06-15 03:45:56 +00:00
|
|
|
|
2015-06-04 18:27:18 +00:00
|
|
|
@ensure_connect
|
2015-04-15 23:32:44 +00:00
|
|
|
@abstractmethod
|
2015-09-24 20:29:36 +00:00
|
|
|
def exec_command(self, cmd, in_data=None, sudoable=True):
|
|
|
|
"""Run a command on the remote host.
|
|
|
|
|
|
|
|
:arg cmd: byte string containing the command
|
|
|
|
:kwarg in_data: If set, this data is passed to the command's stdin.
|
|
|
|
This is used to implement pipelining. Currently not all
|
|
|
|
connection plugins implement pipelining.
|
|
|
|
:kwarg sudoable: Tell the connection plugin if we're executing
|
|
|
|
a command via a privilege escalation mechanism. This may affect
|
|
|
|
how the connection plugin returns data. Note that not all
|
|
|
|
connections can handle privilege escalation.
|
2015-09-24 15:56:20 +00:00
|
|
|
:returns: a tuple of (return code, stdout, stderr) The return code is
|
|
|
|
an int while stdout and stderr are both byte strings.
|
2015-09-26 15:02:36 +00:00
|
|
|
|
|
|
|
When a command is executed, it goes through multiple commands to get
|
|
|
|
there. It looks approximately like this::
|
|
|
|
|
2016-03-18 16:16:21 +00:00
|
|
|
[LocalShell] ConnectionCommand [UsersLoginShell (*)] ANSIBLE_SHELL_EXECUTABLE [(BecomeCommand ANSIBLE_SHELL_EXECUTABLE)] Command
|
2016-03-17 21:21:16 +00:00
|
|
|
:LocalShell: Is optional. It is run locally to invoke the
|
2015-09-26 15:02:36 +00:00
|
|
|
``Connection Command``. In most instances, the
|
|
|
|
``ConnectionCommand`` can be invoked directly instead. The ssh
|
|
|
|
connection plugin which can have values that need expanding
|
|
|
|
locally specified via ssh_args is the sole known exception to
|
|
|
|
this. Shell metacharacters in the command itself should be
|
|
|
|
processed on the remote machine, not on the local machine so no
|
|
|
|
shell is needed on the local machine. (Example, ``/bin/sh``)
|
|
|
|
:ConnectionCommand: This is the command that connects us to the remote
|
2019-02-11 15:43:10 +00:00
|
|
|
machine to run the rest of the command. ``ansible_user``,
|
2015-09-26 15:02:36 +00:00
|
|
|
``ansible_ssh_host`` and so forth are fed to this piece of the
|
|
|
|
command to connect to the correct host (Examples ``ssh``,
|
|
|
|
``chroot``)
|
2016-03-17 21:21:16 +00:00
|
|
|
:UsersLoginShell: This shell may or may not be created depending on
|
|
|
|
the ConnectionCommand used by the connection plugin. This is the
|
2019-02-11 15:43:10 +00:00
|
|
|
shell that the ``ansible_user`` has configured as their login
|
2016-03-17 21:21:16 +00:00
|
|
|
shell. In traditional UNIX parlance, this is the last field of
|
|
|
|
a user's ``/etc/passwd`` entry We do not specifically try to run
|
|
|
|
the ``UsersLoginShell`` when we connect. Instead it is implicit
|
|
|
|
in the actions that the ``ConnectionCommand`` takes when it
|
|
|
|
connects to a remote machine. ``ansible_shell_type`` may be set
|
|
|
|
to inform ansible of differences in how the ``UsersLoginShell``
|
|
|
|
handles things like quoting if a shell has different semantics
|
|
|
|
than the Bourne shell.
|
2016-03-18 16:16:21 +00:00
|
|
|
:ANSIBLE_SHELL_EXECUTABLE: This is the shell set via the inventory var
|
|
|
|
``ansible_shell_executable`` or via
|
|
|
|
``constants.DEFAULT_EXECUTABLE`` if the inventory var is not set.
|
|
|
|
We explicitly invoke this shell so that we have predictable
|
|
|
|
quoting rules at this point. ``ANSIBLE_SHELL_EXECUTABLE`` is only
|
|
|
|
settable by the user because some sudo setups may only allow
|
|
|
|
invoking a specific shell. (For instance, ``/bin/bash`` may be
|
|
|
|
allowed but ``/bin/sh``, our default, may not). We invoke this
|
|
|
|
twice, once after the ``ConnectionCommand`` and once after the
|
2015-09-26 15:02:36 +00:00
|
|
|
``BecomeCommand``. After the ConnectionCommand, this is run by
|
|
|
|
the ``UsersLoginShell``. After the ``BecomeCommand`` we specify
|
2016-03-18 16:16:21 +00:00
|
|
|
that the ``ANSIBLE_SHELL_EXECUTABLE`` is being invoked directly.
|
|
|
|
:BecomeComand ANSIBLE_SHELL_EXECUTABLE: Is the command that performs
|
2016-03-17 21:21:16 +00:00
|
|
|
privilege escalation. Setting this up is performed by the action
|
|
|
|
plugin prior to running ``exec_command``. So we just get passed
|
|
|
|
:param:`cmd` which has the BecomeCommand already added.
|
|
|
|
(Examples: sudo, su) If we have a BecomeCommand then we will
|
2016-03-18 16:16:21 +00:00
|
|
|
invoke a ANSIBLE_SHELL_EXECUTABLE shell inside of it so that we
|
|
|
|
have a consistent view of quoting.
|
2015-10-26 21:01:30 +00:00
|
|
|
:Command: Is the command we're actually trying to run remotely.
|
2015-09-26 15:02:36 +00:00
|
|
|
(Examples: mkdir -p $HOME/.ansible, python $HOME/.ansible/tmp-script-file)
|
2015-09-24 15:56:20 +00:00
|
|
|
"""
|
2015-04-15 23:32:44 +00:00
|
|
|
pass
|
|
|
|
|
2015-06-04 18:27:18 +00:00
|
|
|
@ensure_connect
|
2015-04-15 23:32:44 +00:00
|
|
|
@abstractmethod
|
|
|
|
def put_file(self, in_path, out_path):
|
|
|
|
"""Transfer a file from local to remote"""
|
|
|
|
pass
|
|
|
|
|
2015-06-04 18:27:18 +00:00
|
|
|
@ensure_connect
|
2015-04-15 23:32:44 +00:00
|
|
|
@abstractmethod
|
|
|
|
def fetch_file(self, in_path, out_path):
|
|
|
|
"""Fetch a file from remote to local"""
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def close(self):
|
|
|
|
"""Terminate the connection"""
|
|
|
|
pass
|
2015-06-15 04:09:25 +00:00
|
|
|
|
2015-09-04 04:42:01 +00:00
|
|
|
def connection_lock(self):
|
2015-09-03 04:45:42 +00:00
|
|
|
f = self._play_context.connection_lockfd
|
2016-03-26 00:22:48 +00:00
|
|
|
display.vvvv('CONNECTION: pid %d waiting for lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr)
|
2015-09-03 04:45:42 +00:00
|
|
|
fcntl.lockf(f, fcntl.LOCK_EX)
|
2016-03-26 00:22:48 +00:00
|
|
|
display.vvvv('CONNECTION: pid %d acquired lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr)
|
2015-08-01 03:56:07 +00:00
|
|
|
|
2015-09-04 04:42:01 +00:00
|
|
|
def connection_unlock(self):
|
2015-09-03 04:45:42 +00:00
|
|
|
f = self._play_context.connection_lockfd
|
|
|
|
fcntl.lockf(f, fcntl.LOCK_UN)
|
2016-03-26 00:22:48 +00:00
|
|
|
display.vvvv('CONNECTION: pid %d released lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr)
|
2017-03-22 14:59:50 +00:00
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
display.warning("Reset is not implemented for this connection")
|
2018-07-02 12:41:00 +00:00
|
|
|
|
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
2019-02-11 17:27:44 +00:00
|
|
|
# NOTE: these password functions are all become specific, the name is
|
|
|
|
# confusing as it does not handle 'protocol passwords'
|
|
|
|
# DEPRECATED:
|
|
|
|
# These are kept for backwards compatiblity
|
|
|
|
# Use the methods provided by the become plugins instead
|
|
|
|
def check_become_success(self, b_output):
|
|
|
|
display.deprecated(
|
|
|
|
"Connection.check_become_success is deprecated, calling code should be using become plugins instead",
|
|
|
|
version="2.12"
|
|
|
|
)
|
|
|
|
return self.become.check_success(b_output)
|
|
|
|
|
|
|
|
def check_password_prompt(self, b_output):
|
|
|
|
display.deprecated(
|
|
|
|
"Connection.check_password_prompt is deprecated, calling code should be using become plugins instead",
|
|
|
|
version="2.12"
|
|
|
|
)
|
|
|
|
return self.become.check_password_prompt(b_output)
|
|
|
|
|
|
|
|
def check_incorrect_password(self, b_output):
|
|
|
|
display.deprecated(
|
|
|
|
"Connection.check_incorrect_password is deprecated, calling code should be using become plugins instead",
|
|
|
|
version="2.12"
|
|
|
|
)
|
|
|
|
return self.become.check_incorrect_password(b_output)
|
|
|
|
|
|
|
|
def check_missing_password(self, b_output):
|
|
|
|
display.deprecated(
|
|
|
|
"Connection.check_missing_password is deprecated, calling code should be using become plugins instead",
|
|
|
|
version="2.12"
|
|
|
|
)
|
|
|
|
return self.become.check_missing_password(b_output)
|
|
|
|
|
2018-07-02 12:41:00 +00:00
|
|
|
|
|
|
|
class NetworkConnectionBase(ConnectionBase):
|
|
|
|
"""
|
|
|
|
A base class for network-style connections.
|
|
|
|
"""
|
|
|
|
|
|
|
|
force_persistence = True
|
|
|
|
# Do not use _remote_is_local in other connections
|
|
|
|
_remote_is_local = True
|
|
|
|
|
|
|
|
def __init__(self, play_context, new_stdin, *args, **kwargs):
|
|
|
|
super(NetworkConnectionBase, self).__init__(play_context, new_stdin, *args, **kwargs)
|
2018-12-19 15:54:42 +00:00
|
|
|
self._messages = []
|
2018-07-02 12:41:00 +00:00
|
|
|
|
|
|
|
self._network_os = self._play_context.network_os
|
|
|
|
|
|
|
|
self._local = connection_loader.get('local', play_context, '/dev/null')
|
|
|
|
self._local.set_options()
|
|
|
|
|
2018-12-11 21:26:59 +00:00
|
|
|
self._sub_plugin = {}
|
2018-08-28 21:30:50 +00:00
|
|
|
self._cached_variables = (None, None, None)
|
2018-07-02 12:41:00 +00:00
|
|
|
|
|
|
|
# reconstruct the socket_path and set instance values accordingly
|
|
|
|
self._ansible_playbook_pid = kwargs.get('ansible_playbook_pid')
|
|
|
|
self._update_connection_state()
|
|
|
|
|
|
|
|
def __getattr__(self, name):
|
|
|
|
try:
|
|
|
|
return self.__dict__[name]
|
|
|
|
except KeyError:
|
|
|
|
if not name.startswith('_'):
|
2018-12-11 21:26:59 +00:00
|
|
|
plugin = self._sub_plugin.get('obj')
|
|
|
|
if plugin:
|
|
|
|
method = getattr(plugin, name, None)
|
2018-07-02 12:41:00 +00:00
|
|
|
if method is not None:
|
|
|
|
return method
|
|
|
|
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
|
|
|
|
|
|
|
|
def exec_command(self, cmd, in_data=None, sudoable=True):
|
|
|
|
return self._local.exec_command(cmd, in_data, sudoable)
|
|
|
|
|
2018-12-19 15:54:42 +00:00
|
|
|
def queue_message(self, level, message):
|
|
|
|
"""
|
|
|
|
Adds a message to the queue of messages waiting to be pushed back to the controller process.
|
|
|
|
|
|
|
|
:arg level: A string which can either be the name of a method in display, or 'log'. When
|
|
|
|
the messages are returned to task_executor, a value of log will correspond to
|
|
|
|
``display.display(message, log_only=True)``, while another value will call ``display.[level](message)``
|
|
|
|
"""
|
|
|
|
self._messages.append((level, message))
|
|
|
|
|
|
|
|
def pop_messages(self):
|
|
|
|
messages, self._messages = self._messages, []
|
|
|
|
return messages
|
|
|
|
|
2018-07-02 12:41:00 +00:00
|
|
|
def put_file(self, in_path, out_path):
|
|
|
|
"""Transfer a file from local to remote"""
|
|
|
|
return self._local.put_file(in_path, out_path)
|
|
|
|
|
|
|
|
def fetch_file(self, in_path, out_path):
|
|
|
|
"""Fetch a file from remote to local"""
|
|
|
|
return self._local.fetch_file(in_path, out_path)
|
|
|
|
|
|
|
|
def reset(self):
|
|
|
|
'''
|
|
|
|
Reset the connection
|
|
|
|
'''
|
|
|
|
if self._socket_path:
|
2018-12-19 15:54:42 +00:00
|
|
|
self.queue_message('vvvv', 'resetting persistent connection for socket_path %s' % self._socket_path)
|
2018-07-02 12:41:00 +00:00
|
|
|
self.close()
|
2018-12-19 15:54:42 +00:00
|
|
|
self.queue_message('vvvv', 'reset call on connection instance')
|
2018-07-02 12:41:00 +00:00
|
|
|
|
|
|
|
def close(self):
|
|
|
|
if self._connected:
|
|
|
|
self._connected = False
|
|
|
|
|
2018-07-31 04:53:44 +00:00
|
|
|
def set_options(self, task_keys=None, var_options=None, direct=None):
|
|
|
|
super(NetworkConnectionBase, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
2018-12-21 15:31:43 +00:00
|
|
|
if self.get_option('persistent_log_messages'):
|
|
|
|
warning = "Persistent connection logging is enabled for %s. This will log ALL interactions" % self._play_context.remote_addr
|
|
|
|
logpath = getattr(C, 'DEFAULT_LOG_PATH')
|
|
|
|
if logpath is not None:
|
|
|
|
warning += " to %s" % logpath
|
|
|
|
self.queue_message('warning', "%s and WILL NOT redact sensitive configuration like passwords. USE WITH CAUTION!" % warning)
|
2018-08-29 20:33:51 +00:00
|
|
|
|
2018-12-11 21:26:59 +00:00
|
|
|
if self._sub_plugin.get('obj') and self._sub_plugin.get('type') != 'external':
|
|
|
|
try:
|
|
|
|
self._sub_plugin['obj'].set_options(task_keys=task_keys, var_options=var_options, direct=direct)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
2018-07-31 04:53:44 +00:00
|
|
|
|
2018-07-02 12:41:00 +00:00
|
|
|
def _update_connection_state(self):
|
|
|
|
'''
|
|
|
|
Reconstruct the connection socket_path and check if it exists
|
|
|
|
|
|
|
|
If the socket path exists then the connection is active and set
|
|
|
|
both the _socket_path value to the path and the _connected value
|
|
|
|
to True. If the socket path doesn't exist, leave the socket path
|
|
|
|
value to None and the _connected value to False
|
|
|
|
'''
|
|
|
|
ssh = connection_loader.get('ssh', class_only=True)
|
|
|
|
control_path = ssh._create_control_path(
|
|
|
|
self._play_context.remote_addr, self._play_context.port,
|
|
|
|
self._play_context.remote_user, self._play_context.connection,
|
|
|
|
self._ansible_playbook_pid
|
|
|
|
)
|
|
|
|
|
|
|
|
tmp_path = unfrackpath(C.PERSISTENT_CONTROL_PATH_DIR)
|
|
|
|
socket_path = unfrackpath(control_path % dict(directory=tmp_path))
|
|
|
|
|
|
|
|
if os.path.exists(socket_path):
|
|
|
|
self._connected = True
|
|
|
|
self._socket_path = socket_path
|
2018-12-21 15:31:43 +00:00
|
|
|
|
|
|
|
def _log_messages(self, message):
|
|
|
|
if self.get_option('persistent_log_messages'):
|
|
|
|
self.queue_message('log', message)
|