为Ansible playbook中的任务集设置remote_user,而不是按任务重复

Sha*_*ark 11 ansible ansible-playbook

我正在创建一个首先创建新用户名的剧本.然后我想运行"moretasks.yml"作为我刚刚创建的新用户.目前,我正在为每项任务设置remote_user.有没有办法可以为整套任务设置一次?我似乎无法找到这方面的例子,也没有试图将remote_user转移到帮助之外.

以下是main.yml:

---
- name: Configure Instance(s)
  hosts: all
  remote_user: root
  gather_facts: true

  tags:
    - config
    - configure

  tasks:
    - include: createuser.yml new_user=username
    - include: moretasks.yml new_user=username
    - include: roottasks.yml #some tasks unrelated to username.
Run Code Online (Sandbox Code Playgroud)

moretasks.yml:

---
  - name: Task1
    copy: 
      src: /vagrant/FILE
      dest: ~/FILE
    remote_user: "{{newuser}}"

  - name: Task2
    copy: 
      src: /vagrant/FILE
      dest: ~/FILE
    remote_user: "{{newuser}}"
Run Code Online (Sandbox Code Playgroud)

Pro*_*e85 8

首先你肯定想要使用sudo_user(远程用户是登录的用户,sudo_user是执行任务的用户).

在您的情况下,您希望以另一个用户(先前创建的用户)执行任务:

- include: moretasks.yml
  sudo: yes
  sudo_user: "{{ newuser }}"
Run Code Online (Sandbox Code Playgroud)

这些任务将以{{newuser}}执行(不要忘记引号)

备注:在大多数情况下,您应该将其remote_user视为主机参数.允许用户登录计算机并且具有足够的权限来执行操作.对于操作的东西你应该使用sudo/sudo_user

  • 我以为只有你需要做一些sudo动作才能执行sudo_user?我想注意,我正在创建的用户没有sudo权限."更多任务"中的所有行动都是他们家的当地行为.是否仍然适合(误导?)使用sudo_user方法?(方法确实有效) (2认同)
  • 请注意,不推荐使用`sudo`和`sudo_user`来支持`become`和`become_user`.http://docs.ansible.com/ansible/become.html#become (2认同)

Ram*_*nte 7

你可以把它拆分成单独的戏剧吗?(剧本可以包含多个剧本)

---
- name: PLAY 1
  hosts: all
  remote_user: root
  gather_facts: true

  tasks:
    - include: createuser.yml new_user=username
    - include: roottasks.yml #some tasks unrelated to username.

- name: PLAY 2
  hosts: all
  remote_user: username
  gather_facts: false

  tasks:
    - include: moretasks.yml new_user=username
Run Code Online (Sandbox Code Playgroud)

有一个问题使用单独的游戏:你不能使用在第一个游戏中设置register:set_fact:在第一个游戏中设置的变量在第二个游戏中做事情(这个说法不完全正确,变量可用hostvars,但我建议不要在角色之间使用变量).在group_vars和host_vars中定义的变量可以正常工作.

我想提出的另一个建议是使用roles http://docs.ansible.com/playbooks_roles.html.虽然一开始可能看起来更复杂,但重用它们要容易得多(正如你似乎在使用"createuser.yml").看看你想要实现的事物的类型,"包括所有事物"的路径将不会持续更长时间.