在 ansible 剧本中使用 sudo 权限执行任务

Executing the tasks with sudo privileges in ansible playbook

我有简单的 ansible 剧本

- hosts: all
  remote_user: myusername
  become: yes
  become_user: myusername
  become_method: sudo
  tasks:
    - name: Install tmux
      apt: name=tmux state=present

我在 运行 剧本时遇到以下错误。

TASK: [Install tmux] ********************************************************** 
failed: [104.239.140.237] => {"failed": true}
stderr: E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

我提到了 http://docs.ansible.com/ansible/become.html 来提升用户的权限。

用户'myusername'属于sudo组。

$ sudo -l -U myusername
User myusername may run the following commands on this host:
    (ALL : ALL) ALL

我能够在控制台上使用以下命令成功安装 tmux。不太确定在剧本中做同样的事情时我错过了什么。

$ sudo apt-get install tmux
Reading package lists... Done
Building dependency tree       
Reading state information... Done

我会检查或修改 NOPASSWD 的 sudoers 文件,你的剧本对我有用,我看到的唯一区别是:

User myusername may run the following commands on this host:
    (ALL : ALL) ALL
    (ALL) NOPASSWD: ALL

这与 Ansible 文档所确认的一样多,其中声明:

–become,-b
run operations with become (no password implied)

如果您不能为此更改服务器端配置,您仍然可以使用 sudo 指令。

http://docs.ansible.com/ansible/become.html