Peter Lyons
Peter Lyons

Reputation: 145994

can ansible ask for passwords automatically and only if necessary

So ansible-playbook has --ask-pass and --ask-sudo-pass. Is there a way to get ansible to try ssh without a password first and then only prompt for a password if passwordless login fails? Similarly, can ansible try sudo without a password first and then only prompt if that doesn't work?

FYI I have a little shell function to try to figure this out by trial and error, but I'm hoping something like this is baked into ansible.

get_ansible_auth_args() {
  local base_check="ansible all --one-line --inventory-file=deploy/hosts/localhost.yml --args=/bin/true --sudo"
  ${base_check}
  if [[ $? -eq 0 ]]; then
    return;
  fi
  local args="--ask-pass"
  ${base_check} ${args}
  if [[ $? -eq 0 ]]; then
    export ANSIBLE_AUTH_ARGS="${args}"
    return;
  fi
  local args="--ask-pass --ask-sudo-pass"
  ${base_check} ${args}
  if [[ $? -eq 0 ]]; then
    export ANSIBLE_AUTH_ARGS="${args}"
    return;
  fi
}

Upvotes: 12

Views: 6938

Answers (1)

Kashyap
Kashyap

Reputation: 17411

If you set ask_pass and ssh_args as I show below then ansible should ask you for password at the beginning once and use that password whenever public key auth doesn't work.

[defaults]
ask_pass      = True

[ssh_connection]
ssh_args = -o PubkeyAuthentication=yes -o PasswordAuthentication=yes -o ControlMaster=auto -o ControlPersist=60s

This is still not the full solution: Catch being (AFAIK) ansible uses sshpass, so the password it collected from your at the start would be the only password it would use and it won't work if you have different passwords for different machines. :-)

Only other hack I can think of is to replace /usr/bin/ssh (or whichever is your openssh's ssh used by ansible) with a script of your own that wraps the logic of reading password from some flat file if needed, I suspect ansible would hide the tty so your script won't be able to 'read' the password from stdin.

Upvotes: 1

Related Questions