如何从远程shell切换用户

时间:2015-02-11 05:17:21

标签: ansible-playbook

我无法从远程shell切换用户。 另外我如何将密码传递给远程shell。

我尝试过play book,command和shell任务。 但它不起作用

这是我的代码

- hosts: test1
  tasks:
    - name: Switch user
      shell: $(echo "{{ su - username }}")
      shell: $(echo "{{ 'password' }}”)

1 个答案:

答案 0 :(得分:0)

我为下面的代码段道歉,当然你不能神奇地运行ansible代码,但如果没有这个代码,我就无法获得不错的格式。

你在这里做了几件事,但是ansible并不喜欢。我的心情很好,所以我会为你分解,实际上这包含在 excellent documentation

  • 任务只能有一个操作
  • 每个任务独立于
  • 之前的任务运行

将您所做的内容翻译成有效的ansible语法,将发生以下情况:

  1. 您使用的语法尝试扩展{{ ... }}内部的内容 - 这将导致
  2. 使用调用bash -c $(echo "{{ su - username }}")
  3. 的ssh用户运行shell

    
    
    - name: Run a single action for each Task
      hosts: test1
      tasks:
        - name: Task 1 # fails with 'standard in must be a tty'
          shell: su - nobody
        - name: Task 2 # never executed because 'Task 1' fails
          shell: whoami
          register: whoami_result
        - name: Task 3 # never executed because 'Task 1' fails
          debug:
            msg: "Result: {{ whoami_result }}"
    
    
    

    现在有一个固定的ansible-playbook:

    
    
    ---
    - name: Run a single action for each Task
      hosts: test1
      tasks:
        - name: Task 1
          sudo: true # use sudo to change roles
          sudo_user: nobody # the target user under which to execute
          shell: whoami
          register: whoami_result
        - name: Task 2
          debug:
            msg: "Result: {{ whoami_result.stdout }}"
    
    
    

    
    
    $ ansible-playbook -u root test1.yml
    
    PLAY [Run a single action for each Task] **************************************
    
    GATHERING FACTS ***************************************************************
    ok: [test1]
    
    TASK: [Task 1] ****************************************************************
    changed: [test1]
    
    TASK: [Task 2] ****************************************************************
    ok: [test1] => {
        "msg": "Result: nobody"
    }
    
    PLAY RECAP ********************************************************************
    test1                      : ok=3    changed=1    unreachable=0    failed=0