Ansible 中 become 和 become_user 的区别

Difference between become and become_user in Ansible

最近我开始深入研究 Ansible 并编写自己的剧本。但是,我很难理解 becomebecome_user 之间的区别。 据我了解,become_user 类似于 su <username>,而 become 类似于 sudo su 或 "perform all commands as a sudo user"。但有时这两个指令是混合的。

你能解释一下它们的正确含义吗?

become_user 定义用于 privilege escalation.

的用户

become 只是一个标志,可以激活或停用它。

这里举三个例子应该很清楚:

  1. 此任务将作为 root 执行,因为 root 是提权的默认用户:

     - do: something
       become: true
    
  2. 此任务将作为用户 someone 执行,因为明确设置了用户:

     - do: something
       become: true
       become_user: someone
    
  3. 此任务不会对 become_user 执行任何操作,因为 become 未设置且默认为 false/no:

     - do: something
       become_user: someone
    

...除非在更高级别上将 become 设置为 true,例如块、剧本、组或主机变量等

这是一个 block 的例子:

    - become: true
      block:
        - do: something
          become_user: someone
        - do: something

第一个是 运行 作为用户 someone,第二个是 root

As I understand it become_user is something similar to su , and become means something like sudo su or "perform all commands as a sudo user".

默认的become_methodsudo,所以sudo do something或者sudo -u <become_user> do something

Fineprint:当然“do: something”是伪代码。将您实际的 Ansible 模块放在那里。

  1. become: yes = sudo
    become_user: user_name = sudo -u user_name
  2. become: yes
    become_user: root 等同于 become: yes

这个 link 清楚地解释了差异。

如果我需要使用 sudo 运行 一批任务,我经常使用 include_task 语句。 将大型剧本分成几部分也有很大帮助。 例如

 - name: prepare task x
   include_tasks: x-preparation.yml
   when: condition is true
   args:
     apply:
       become: yes

这也是使用标签时的一个方便方法:

  - name: execute tasks x
     include_tasks: x-execution.yml
     args:
       apply:
         tags: exec
     tags:
     - exec

重要的是您还需要在 include_tasks 语句上添加标签 希望这对任何人都有帮助