首页 > 解决方案 > Unable to switch to a different user using become_user

问题描述

I am writing Ansible playbook to create key-based ssh access on several hosts with a particular user. I have following servers:

  1. automation_host

  2. Master

  3. Slave1

  4. Slave2

From automation host I will trigger Ansible to run the playbook which should first login to master with user1, then switch to user2, create ssh keys with user2 and copy the id_rsa.pub to slave nodes.

Inventory file contents:

[master]
172.xxx.xxx.xxx
[slaves]
172.xxx.xxx.xxx
172.xxx.xxx.xxx
[all:vars]
ansible_connection=ssh
ansible_ssh_user=user1

playbook.yml file:

- hosts: master
  become_user: user2
  become: yes
  roles:
     - name: passwordless-ssh

User2 is available on all hosts (except automation_host) and is added in sudoers as well.

In the passwordless-ssh role, I have added the lines included below to check which user is currently executing the tasks.

- name: get the username running the deploy
  local_action: command whoami
  register: username_on_the_host

- debug: var=username_on_the_host

Debug message shows user1 ( I am expecting it to be user2) ansible version: 2.5.2

I am very new to Ansible.

标签: ansibleansible-2.x

解决方案


local_action will run on automation_host, change it to command

- hosts: master
  become_user: user2
  become: yes
  tasks:
  - name: get the username running the deploy
    command: whoami
    register: username_on_the_host

  - debug: var=username_on_the_host['stdout']

  - name: do something
    command: echo 'hello'
    when: username_on_the_host['stdout'] == 'user2'
  - name: do something else
    command: echo 'goodby'
    when: username_on_the_host['stdout'] == 'user1'

Output

TASK [debug] *********************************************
ok: [master] => {
    "username_on_the_host['stdout']": "user2"
}

TASK [do something] *********************************************
changed: [master]

TASK [do something else] *********************************************

do something else does not run.


推荐阅读