无法使用begin_user切换到其他用户

时间:2018-09-18 09:23:19

标签: ansible ansible-2.x

我正在编写Ansible剧本,以在具有特定用户的多台主机上创建基于密钥的ssh访问。 我有以下服务器:

  1. 自动化主机

  2. 大师

  3. 奴隶1

  4. Slave2

从自动化主机上,我将触发Ansible运行该剧本,该剧本应首先以user1登录,然后切换到user2,使用user2创建ssh密钥,然后将id_rsa.pub复制到从属节点。

库存文件内容:

[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文件:

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

User2在所有主机(automation_host除外)上都可用,并且也添加到sudoers中。

在无密码ssh角色中,我添加了以下几行,以检查当前正在执行任务的用户。

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

- debug: var=username_on_the_host

调试消息显示user1(我希望它是user2) ansible版本:2.5.2

我对Ansible很陌生。

1 个答案:

答案 0 :(得分:0)

local_actionrun on automation_host更改为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'

输出

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

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

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

do something else无法运行。

相关问题