在日常的运维工作中,编写ansible-playbook时,也许会遇到需要用root用户执行命令的情况。然而,在playbook中该咋写呢?下面开始上干货:
---
- hosts: all
remote_user: testuser
gather_facts: No
become: yes #表示是否允许用户切换
become_method: sudo #表示切换用户的方式,有su/sudo/pbrun等方式,默认是sudo方式
become_user: root #表示要切换到哪个用户,即目标用户
tasks:
- name: "create a test dir"
shell: /bin/sh -c 'mkdir -p /root/testuser'
注意:默认在/etc/sudoers已经配置了“testuser ALL=(ALL) NOPASSWD: ALL”。