首页 文章

Ansible Playbook在运行具有sudo的远程shell脚本时冻结

提问于
浏览
0

注意:这是使用vitualbox运行最小ubuntu映像的场景,用作从ubuntu 16.04访问的远程主机

我是一个初学者使用ansible在远程服务器上运行shell脚本,但它似乎冻结,即使在参数中使用"-vvv"后我也没有收到任何日志 . 经过一些调试后,我发现问题出在shell脚本中使用 sudo apt-get update .

如果我将密码作为参数从ansible plabook传递给shell文件,然后将其用作 echo "$PASS" | sudo -S apt-get update ,则脚本似乎可以正常工作 .

如何配置我的ansible Playbook,以便在shell文件中执行 sudo apt-get update 时不会冻结密码提示 .

我需要使用特定的用户帐户和密码而不是root .

我正在传递主机,用户并将--extra-vars传递给剧本,

{}是远程主机的IP地址 .

{}是远程计算机上的用户帐户 .

{}是远程计算机上用户帐户的密码 .

这是我的ansible剧本 -

---
- hosts: "{{ host }}"
  remote_user: "{{ user }}"
  vars:
    ansible_become_pass: "{{ pass }}"
  tasks:
    - name: Move test.sh file to remote
      copy: 
        src: ./../scripts/test.sh
        dest: /home/{{ user }}/new/test.sh

    - name: Executing the test.sh script
      command: sh test.sh
      args:
        chdir: /home/{{ user }}/new/
      become: yes
      become_user: "{{ user }}"

1 回答

  • 0

    我在这里可以看到两件事:

    根据你的意见:

    我需要使用特定的用户帐户和密码而不是root .

    在Ubuntu中,apt-get update必须以ID 0(root)运行,不是吗?所以当你添加:

    become: yes
    

    意味着您希望您的用户能够执行您需要的操作 .

    在这种情况下, apt-get update 需要root访问权限以锁定 /var/lib/apt/lists/ 等 .

    我想这不是你的情况所以你需要这样做:

    ---
    - hosts: "{{ host }}"
      remote_user: "{{ user }}"
      vars:
        ansible_become_pass: "{{ pass }}"
      tasks:
        - name: Move test.sh file to remote
          copy: 
            src: ./../scripts/test.sh
            dest: /home/{{ user }}/new/test.sh
    
        - name: Executing the test.sh script
          command: sh test.sh
          args:
            chdir: /home/{{ user }}/new/
          become: yes
    

    删除 become_user: "{{ user }}" . 我猜也是用户有sudo访问权限运行 apt-get update 所以密码可以工作 .

    另一方面,您不需要在脚本中运行 sudp apt-get update ,一个简单的 apt-get update 就足够了 .

    这是第一件事 .

    对于第二个,我建议你拆分动作 . 如果要更新系统,请先执行以下操作:

    apt-get updatebecome

    和用户的其他任务(如果需要) . 另外,尽可能使用ansible模块 . 如果您有以下情况,请不要运行 apt-get update

    - name: apt-get example
      apt:
        name: package
        update_cache: yes
    

    甚至 package .

    顺便说一句,我正在运行这样的例子:

    ansible-playbook test.yml -e "host=ubuntu-1.vagrant.local pass=ansible user=ansible"
    

相关问题