【问题标题】:Unable to switch to a different user using become_user无法使用 become_user 切换到其他用户
【发布时间】:2018-09-18 09:23:19
【问题描述】:

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

  1. automation_host

  2. 大师

  3. 从站1

  4. Slave2

从自动化主机我将触发 Ansible 运行 playbook,首先应该使用 user1 登录到 master,然后切换到 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 中。

在 passwordless-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 很陌生。

【问题讨论】:

    标签: ansible ansible-2.x


    【解决方案1】:

    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 不运行。

    【讨论】:

    • 感谢 Michael 的帮助 :) 我之前尝试过这个,但我得到“无法设置 Ansible 成为非特权用户时需要创建的临时文件的权限”。我在 ansible 中添加了 allow_world_readable_tmpfiles=true .cfg 解决临时文件权限问题。之后我可以切换到 user2。再次感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多