首页 > 解决方案 > 如何使用不同的用户而不是 PLAY 用户执行特定的 Ansible 模块

问题描述

这是我的剧本:

- name: Play 4.
  hosts: dest_nodes
  user: "{{ USER }}"

  tasks:

   - name: "Load Respective variable file before Deployment1."
     tags: deploy
     include_vars:
 file: "{{ item }}"
     with_fileglob:
       - "vars/{{ Layer }}_*.yaml"

   - file:
       path: "{{ playbook_dir }}/gitfiles/{{ Number }}"
       state: directory
     when: Layer == 'APP'
     with_items:
       - "{{ Source_Filenames.split(',') }}"


   - name: "Pulling APP files  `{{ inventory_hostname }}`"
     tags: deploy
     synchronize:
       src: "{{ BASEPATH }}/ref.txt"
       dest: "{{ playbook_dir }}/gitfiles/{{ Number }}"
       mode: pull
     register: q
     when: Layer == 'APP'
     with_items:
       - "{{ Source_Filenames.split(',') }}"

在上面的剧本中,我希望一切都用“{{ USER }}”执行,但是,下面的文件模块应该运行执行我的剧本的本地用户“user1”。

   - file:
       path: "{{ playbook_dir }}/gitfiles/{{ Number }}"
       state: directory
     when: Layer == 'APP'
     with_items:
       - "{{ Source_Filenames.split(',') }}"

我知道解决方案在于 become_user 但不知道如何仅为文件模块指定 become_user 。

您能否建议我需要对文件模块/我的剧本进行哪些更改?

标签: fileansibleansible-2.x

解决方案


首先,user不推荐使用,您应该remote_user改用。

现在你的问题还不清楚。其实有2种可能:

  1. 您希望始终以身份连接{{ USER }}并成为(例如sudouser1特定任务。
  2. 您想要连接{{ USER }}所有任务,但您想要连接的特定任务除外user1

第一种情况是迄今为止最常见的情况。下面的示例仅用于说明,调试实际上不会become

---
- name: my play
  hosts: my_hosts
  remote_user: my_deploy_user

  tasks:
    - name: normal task
      debug:
        msg: "normal"

    - name: become root task
      debug:
        msg: "as root"
      become: true

    - name: become user1 task
      debug:
        msg: "as user1"
      become: true
      become_user: user1

现在,如果您真的想以其他用户身份连接,这也是可能的(前提是您拥有正确的配置/密钥)。再一次,示例仅用于说明:

- name: my_play
  hosts: my_hosts
  remote_user: "{{ USER }}"

  tasks:
    - name: task as usual
      debug:
        msg: "Usual task"

    - name: task connected as user1
      debug:
        msg: "connect as user1
      remote_user: user1

推荐阅读