summaryrefslogtreecommitdiff
path: root/lib/ansible
diff options
context:
space:
mode:
authorBrian Coca <bcoca@users.noreply.github.com>2021-08-19 12:18:30 -0400
committerGitHub <noreply@github.com>2021-08-19 12:18:30 -0400
commitb554aef3e1f4be8cbf4eb4f94d4ad28e75dc8627 (patch)
treebcdbf9d919846aabd51f19d5d387934ae5aa7f69 /lib/ansible
parent214f0984a9c2cb405ce80faf4344d2c9a77cd707 (diff)
downloadansible-b554aef3e1f4be8cbf4eb4f94d4ad28e75dc8627.tar.gz
More options for password passing (#73117)
* add 'file options' for become and connection pass * implemented getting passwords from file or script * added config entry * fixed env var name and noted executable behaviuor Co-authored-by: Rick Elrod <rick@elrod.me>
Diffstat (limited to 'lib/ansible')
-rw-r--r--lib/ansible/cli/__init__.py74
-rw-r--r--lib/ansible/cli/arguments/option_helpers.py31
-rw-r--r--lib/ansible/config/base.yml28
3 files changed, 109 insertions, 24 deletions
diff --git a/lib/ansible/cli/__init__.py b/lib/ansible/cli/__init__.py
index 7e001c981c..0ffafc5a69 100644
--- a/lib/ansible/cli/__init__.py
+++ b/lib/ansible/cli/__init__.py
@@ -19,7 +19,7 @@ from ansible import constants as C
from ansible import context
from ansible.errors import AnsibleError
from ansible.inventory.manager import InventoryManager
-from ansible.module_utils.six import with_metaclass, string_types
+from ansible.module_utils.six import with_metaclass, string_types, PY3
from ansible.module_utils._text import to_bytes, to_text
from ansible.parsing.dataloader import DataLoader
from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secret
@@ -230,6 +230,14 @@ class CLI(with_metaclass(ABCMeta, object)):
return vault_secrets
@staticmethod
+ def _get_secret(prompt):
+
+ secret = getpass.getpass(prompt=prompt)
+ if secret:
+ secret = to_unsafe_text(secret)
+ return secret
+
+ @staticmethod
def ask_passwords():
''' prompt for connection and become passwords if needed '''
@@ -241,26 +249,23 @@ class CLI(with_metaclass(ABCMeta, object)):
become_prompt_method = "BECOME" if C.AGNOSTIC_BECOME_PROMPT else op['become_method'].upper()
try:
+ become_prompt = "%s password: " % become_prompt_method
if op['ask_pass']:
- sshpass = getpass.getpass(prompt="SSH password: ")
+ sshpass = CLI._get_secret("SSH password: ")
become_prompt = "%s password[defaults to SSH password]: " % become_prompt_method
- else:
- become_prompt = "%s password: " % become_prompt_method
+ elif op['connection_password_file']:
+ sshpass = CLI.get_password_from_file(op['connection_password_file'])
if op['become_ask_pass']:
- becomepass = getpass.getpass(prompt=become_prompt)
+ becomepass = CLI._get_secret(become_prompt)
if op['ask_pass'] and becomepass == '':
becomepass = sshpass
+ elif op['become_password_file']:
+ becomepass = CLI.get_password_from_file(op['become_password_file'])
+
except EOFError:
pass
- # we 'wrap' the passwords to prevent templating as
- # they can contain special chars and trigger it incorrectly
- if sshpass:
- sshpass = to_unsafe_text(sshpass)
- if becomepass:
- becomepass = to_unsafe_text(becomepass)
-
return (sshpass, becomepass)
def validate_conflicts(self, op, runas_opts=False, fork_opts=False):
@@ -492,3 +497,48 @@ class CLI(with_metaclass(ABCMeta, object)):
raise AnsibleError("Specified hosts and/or --limit does not match any hosts")
return hosts
+
+ @staticmethod
+ def get_password_from_file(pwd_file):
+
+ b_pwd_file = to_bytes(pwd_file)
+ secret = None
+ if b_pwd_file == b'-':
+ if PY3:
+ # ensure its read as bytes
+ secret = sys.stdin.buffer.read()
+ else:
+ secret = sys.stdin.read()
+
+ elif not os.path.exists(b_pwd_file):
+ raise AnsibleError("The password file %s was not found" % pwd_file)
+
+ elif os.path.is_executable(b_pwd_file):
+ display.vvvv(u'The password file %s is a script.' % to_text(pwd_file))
+ cmd = [b_pwd_file]
+
+ try:
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ except OSError as e:
+ raise AnsibleError("Problem occured when trying to run the password script %s (%s)."
+ " If this is not a script, remove the executable bit from the file." % (pwd_file, e))
+
+ stdout, stderr = p.communicate()
+ if p.returncode != 0:
+ raise AnsibleError("The password script %s returned an error (rc=%s): %s" % (pwd_file, p.returncode, stderr))
+ secret = stdout
+
+ else:
+ try:
+ f = open(b_pwd_file, "rb")
+ secret = f.read().strip()
+ f.close()
+ except (OSError, IOError) as e:
+ raise AnsibleError("Could not read password file %s: %s" % (pwd_file, e))
+
+ secret = secret.strip(b'\r\n')
+
+ if not secret:
+ raise AnsibleError('Empty password was provided from file (%s)' % pwd_file)
+
+ return to_unsafe_text(secret)
diff --git a/lib/ansible/cli/arguments/option_helpers.py b/lib/ansible/cli/arguments/option_helpers.py
index 3a6f6adebb..9704b3811b 100644
--- a/lib/ansible/cli/arguments/option_helpers.py
+++ b/lib/ansible/cli/arguments/option_helpers.py
@@ -244,8 +244,6 @@ def add_connect_options(parser):
"""Add options for commands which need to connection to other hosts"""
connect_group = parser.add_argument_group("Connection Options", "control as whom and how to connect to hosts")
- connect_group.add_argument('-k', '--ask-pass', default=C.DEFAULT_ASK_PASS, dest='ask_pass', action='store_true',
- help='ask for connection password')
connect_group.add_argument('--private-key', '--key-file', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file',
help='use this file to authenticate the connection', type=unfrack_path())
connect_group.add_argument('-u', '--user', default=C.DEFAULT_REMOTE_USER, dest='remote_user',
@@ -267,6 +265,14 @@ def add_connect_options(parser):
parser.add_argument_group(connect_group)
+ connect_password_group = parser.add_mutually_exclusive_group()
+ connect_password_group.add_argument('-k', '--ask-pass', default=C.DEFAULT_ASK_PASS, dest='ask_pass', action='store_true',
+ help='ask for connection password')
+ connect_password_group.add_argument('--connection-password-file', '--conn-pass-file', default=C.CONNECTION_PASSWORD_FILE, dest='connection_password_file',
+ help="Connection password file", type=unfrack_path(), action='store')
+
+ parser.add_argument_group(connect_password_group)
+
def add_fork_options(parser):
"""Add options for commands that can fork worker processes"""
@@ -326,7 +332,9 @@ def add_runas_options(parser):
runas_group.add_argument('--become-user', default=None, dest='become_user', type=str,
help='run operations as this user (default=%s)' % C.DEFAULT_BECOME_USER)
- add_runas_prompt_options(parser, runas_group=runas_group)
+ parser.add_argument_group(runas_group)
+
+ add_runas_prompt_options(parser)
def add_runas_prompt_options(parser, runas_group=None):
@@ -336,15 +344,18 @@ def add_runas_prompt_options(parser, runas_group=None):
Note that add_runas_options() includes these options already. Only one of the two functions
should be used.
"""
- if runas_group is None:
- runas_group = parser.add_argument_group("Privilege Escalation Options",
- "control how and which user you become as on target hosts")
+ if runas_group is not None:
+ parser.add_argument_group(runas_group)
- runas_group.add_argument('-K', '--ask-become-pass', dest='become_ask_pass', action='store_true',
- default=C.DEFAULT_BECOME_ASK_PASS,
- help='ask for privilege escalation password')
+ runas_pass_group = parser.add_mutually_exclusive_group()
- parser.add_argument_group(runas_group)
+ runas_pass_group.add_argument('-K', '--ask-become-pass', dest='become_ask_pass', action='store_true',
+ default=C.DEFAULT_BECOME_ASK_PASS,
+ help='ask for privilege escalation password')
+ runas_pass_group.add_argument('--become-password-file', '--become-pass-file', default=C.BECOME_PASSWORD_FILE, dest='become_password_file',
+ help="Become password file", type=unfrack_path(), action='store')
+
+ parser.add_argument_group(runas_pass_group)
def add_runtask_options(parser):
diff --git a/lib/ansible/config/base.yml b/lib/ansible/config/base.yml
index 859043f12f..a507095654 100644
--- a/lib/ansible/config/base.yml
+++ b/lib/ansible/config/base.yml
@@ -129,12 +129,25 @@ ANY_ERRORS_FATAL:
BECOME_ALLOW_SAME_USER:
name: Allow becoming the same user
default: False
- description: This setting controls if become is skipped when remote user and become user are the same. I.E root sudo to root.
+ description:
+ - This setting controls if become is skipped when remote user and become user are the same. I.E root sudo to root.
+ - If executable, it will be run and the resulting stdout will be used as the password.
env: [{name: ANSIBLE_BECOME_ALLOW_SAME_USER}]
ini:
- {key: become_allow_same_user, section: privilege_escalation}
type: boolean
yaml: {key: privilege_escalation.become_allow_same_user}
+BECOME_PASSWORD_FILE:
+ name: Become password file
+ default: ~
+ description:
+ - 'The password file to use for the become plugin. --become-password-file.'
+ - If executable, it will be run and the resulting stdout will be used as the password.
+ env: [{name: ANSIBLE_BECOME_PASSWORD_FILE}]
+ ini:
+ - {key: become_password_file, section: defaults}
+ type: path
+ version_added: '2.12'
AGNOSTIC_BECOME_PROMPT:
name: Display an agnostic become prompt
default: True
@@ -335,6 +348,15 @@ COLOR_WARN:
env: [{name: ANSIBLE_COLOR_WARN}]
ini:
- {key: warn, section: colors}
+CONNECTION_PASSWORD_FILE:
+ name: Connection password file
+ default: ~
+ description: 'The password file to use for the connection plugin. --connection-password-file.'
+ env: [{name: ANSIBLE_CONNECTION_PASSWORD_FILE}]
+ ini:
+ - {key: connection_password_file, section: defaults}
+ type: path
+ version_added: '2.12'
COVERAGE_REMOTE_OUTPUT:
name: Sets the output directory and filename prefix to generate coverage run info.
description:
@@ -1177,7 +1199,9 @@ DEFAULT_VAULT_IDENTITY_LIST:
DEFAULT_VAULT_PASSWORD_FILE:
name: Vault password file
default: ~
- description: 'The vault password file to use. Equivalent to --vault-password-file or --vault-id'
+ description:
+ - 'The vault password file to use. Equivalent to --vault-password-file or --vault-id'
+ - If executable, it will be run and the resulting stdout will be used as the password.
env: [{name: ANSIBLE_VAULT_PASSWORD_FILE}]
ini:
- {key: vault_password_file, section: defaults}