如何用其他用户而不是PLAY用户执行特定的Ansible模块

时间:2019-10-24 12:38:45

标签: file ansible ansible-2.x

这是我的剧本:

- 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(',') }}"

我了解解决方案位于“ begin_user”中,但不知道如何仅为文件模块指定“ begin_user”。

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

2 个答案:

答案 0 :(得分:1)

首先,不建议使用user,而应使用remote_user

现在您的问题不清楚。实际上有两种可能性:

  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

答案 1 :(得分:0)

您只需要在模块级别上将成为用户的任务应用到所需任务即可

- file:
    path: "{{ playbook_dir }}/gitfiles/{{ Number }}"
    state: directory
  when: Layer == 'APP'
  with_items:
    - "{{ Source_Filenames.split(',') }}"
  become: true
  become_user: <new user>