代码之家  ›  专栏  ›  技术社区  ›  Milan Vaibhav

无法使用“成为用户”切换到其他用户

  •  2
  • Milan Vaibhav  · 技术社区  · 6 年前

    我正在写一本易懂的Playbook,在具有特定用户的几个主机上创建基于密钥的ssh访问。 我有以下服务器:

    1. 自动化主机

    2. 主人

    3. 斯拉夫1号

    4. 斯拉夫2号

    从自动化主机我将触发ansible来运行playbook,它应该首先用user1登录到master,然后切换到user2,用user2创建ssh密钥,并将id_rsa.pub复制到slave节点。

    库存文件内容:

    [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
    

    用户2可用于所有主机(自动化主机除外),并添加到 sudoers 也。

    在passwordlessh角色中,我添加了下面包含的行,以检查当前正在执行任务的用户。

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

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

    我是一个新的负责人。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Michael Porter    6 年前

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