Ansible 非 root sudo 用户和 "become" 权限提升

Ansible non-root sudo user and "become" privilege escalation

我已经为一个拥有 sudo 权限的用户 david 设置了一个盒子。我可以通过 ssh 进入盒子并执行像 apt-get install 这样的 sudo 操作。当我尝试使用 Ansible 的 "become privilege escalation" 做同样的事情时,我得到一个 permission denied 错误。所以一个简单的剧本可能是这样的:

simple_playbook.yml:

---
- name: Testing...
  hosts: all
  become: true
  become_user: david
  become_method: sudo

  tasks:
    - name: Just want to install sqlite3 for example...
      apt: name=sqlite3 state=present

我运行这个剧本有以下命令:

ansible-playbook -i inventory simple_playbook.yml --ask-become-pass

这会提示我输入密码,然后我收到以下错误(缩写):

fatal: [123.45.67.89]: FAILED! => {...
failed: E: Could not open lock file /var/lib/dpkg/lock - open (13: 
Permission denied)\nE: Unable to lock the administration directory
(/var/lib/dpkg/), are you root?\n", ...}

为什么我的权限被拒绝?

附加信息

我正在 运行ning Ansible 2.1.1.0,目标是 Ubuntu 16.04 盒子。如果我根据 Ansible < v1.9 使用 remote_usersudo 选项,它工作正常,如下所示: remote_user: david sudo: yes

更新

本地和远程用户名相同。为了让它工作,我只需要指定 become: yes (参见@techraf 的回答):

remote_userdavid。使用 --ask-pass 调用脚本并为 david 提供密码。如果 david 没有无密码 sudo,那么你也应该用 --ask-become-pass.

调用它
- name: Testing...
  hosts: all
  remote_user: david
  become: true
  become_method: sudo

  tasks:
    - name: Just want to install sqlite3 for example...
      apt: name=sqlite3 state=present

Why am I getting permission denied?

因为 APT 需要 root 权限(参见错误:are you root?)并且您运行将任务设为david

根据这些设置:

become: true
become_user: david
become_method: sudo

Ansible 使用 sudo 方法变为 david。它基本上 运行 它的 Python 脚本前面有 sudo david


the user 'david' on the remote box has sudo privileges.

表示david可以使用sudo-executable执行命令(部分或全部)来改变子进程(命令)的有效用户。如果未提供用户名,此过程 运行 将作为 root 帐户。

比较这两个命令的结果:

$ sudo whoami
root
$ sudo david whoami
david

回到 APT 问题,您(从 CLI)以及 Ansible(使用您的帐户连接 SSH)需要 运行:

sudo apt-get install sqlite3

不是:

sudo david apt-get install sqlite3

这将失败并显示 Ansible 的确切消息。


以下剧本将默认升级到 root 用户:

---
- name: Testing...   
  hosts: all
  become: true

  tasks:
    - name: Just want to install sqlite3 for example...
      apt: name=sqlite3 state=present