如何为每个任务或一组任务切换用户? [英] How to switch a user per task or set of tasks?

查看:32
本文介绍了如何为每个任务或一组任务切换用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 ansible playbook 中反复出现的一个主题是,我经常必须以 sudo 权限 (sudo: yes) 执行命令,因为我想为某个用户执行此操作.理想情况下,我更愿意使用 sudo 切换到该用户并正常执行命令.因为那样我就不必执行我通常的 post 命令清理,例如 chowning 目录.这是我的一本剧本的片段:

A recurring theme that's in my ansible playbooks is that I often must execute a command with sudo privileges (sudo: yes) because I'd like to do it for a certain user. Ideally I'd much rather use sudo to switch to that user and execute the commands normally. Because then I won't have to do my usual post commands clean up such as chowning directories. Here's a snippet from one of my playbooks:

- name: checkout repo
  git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
  sudo: yes
- name: change perms
  file: dest={{ dst }} state=directory mode=0755 owner=some_user
  sudo: yes

理想情况下,即使需要 sudo su 到该用户,我也可以以不同的用户身份运行命令或命令集.

Ideally I could run commands or sets of commands as a different user even if it requires sudo to su to that user.

推荐答案

使用 Ansible 1.9 或更高版本

Ansible 使用 becomebecome_userbecome_method 指令来实现权限提升.您可以将它们应用于整个剧本或剧本,将它们设置在包含的剧本中,或将它们设置为特定任务.

With Ansible 1.9 or later

Ansible uses the become, become_user, and become_method directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.

- name: checkout repo
  git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
  become: yes
  become_user: some_user

您可以使用become_with来指定如何实现权限提升,默认为sudo.

You can use become_with to specify how the privilege escalation is achieved, the default being sudo.

该指令对使用它的块的范围有效(示例).

The directive is in effect for the scope of the block in which it is used (examples).

请参阅主机和用户了解更多示例和Become(权限提升) 获取更详细的文档.

See Hosts and Users for some additional examples and Become (Privilege Escalation) for more detailed documentation.

除了任务范围的 becomebecome_user 指令之外,Ansible 1.9 添加了一些新的变量和命令行选项来设置这些值没有明确的指令:

In addition to the task-scoped become and become_user directives, Ansible 1.9 added some new variables and command line options to set these values for the duration of a play in the absence of explicit directives:

  • Command line options for the equivalent become/become_user directives.
  • Connection specific variables which can be set per host or group.

从 Ansible 2.0.2.0 开始,下面描述的旧 sudo/sudo_user 语法仍然有效,但弃用通知指出,此功能将在未来移除发布."

As of Ansible 2.0.2.0, the older sudo/sudo_user syntax described below still works, but the deprecation notice states, "This feature will be removed in a future release."

- name: checkout repo
  git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
  sudo: yes
  sudo_user: some_user

这篇关于如何为每个任务或一组任务切换用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆