如何在Ansible中运行sudo -u username命令?

时间:2017-06-08 08:01:31

标签: ansible

我想使用Ansible以sudo -u username <command name>运行特定命令。

我尝试过以下任务,但面临权限问题。

---
-
  hosts: all
  become: yes
  vars_files:
    - vars.yml

  tasks:
    - name: "Create solr cores"
      shell: /opt/apps/solr/bin/solr create -c test10
      become_flags: '-u solr'
      register: core_one
#      changed_when: '"\"status\":0" in core_one.stdout'

有人可以对此提出建议吗?

2 个答案:

答案 0 :(得分:1)

运行任务的正确方法如下。

拥有适当的权限是先决条件。请参阅man sudoers了解详情

- name: "Create solr cores" 
  shell: /opt/apps/solr/bin/solr create -c test10
  become: yes
  become_user: solr
  register: core_one

你在游戏关卡中已经有become: yes,所以为了清晰起见。

答案 1 :(得分:0)

remote_user: ansible
  tasks:   
  - name: "Create solr cores" 
     shell: /opt/apps/solr/bin/solr create -c test10
     become: yes
     become_user: solr
     register: core_one

在上面的示例中,ansible使用用户“ansible”连接到远程计算机。现在这个ansible用户应该有权切换到另一个用户。即它应具有root权限

以上代码会发生什么:

* ssh connection is made via ansible user (ansible-play does it)
* It uses command "sudo su solr" internally
* Then execute the command which is mentioned in shell