ansible通过普通用户执行root权限进行操作

在实际应用中,安全加固后的主机是不允许直接以root用户登陆的,而很多命令又需要root用户来执行。
正常运维操作需要通过一个普通用户先登陆,再su切到root执行。而且每台主机的普通用户和root用户的密码又不同。
下面使用ansible命令通过普通用户登录执行root权限操作,无需交互输入密码,直接执行后输出结果。

一、ansible hosts配置文件

测试过程中,将密码直接写到/etc/ansible/hosts配置文件。
变量说明:

  • ansible_ssh_user(普通用户)、
  • ansible_ssh_pass(普通用户密码)、
  • ansible_become_pass(root密码用于su切换),在2.0版本之后,使用ansible_become_pass替换了之前的ansible_sudo_pass or ansible_su_pass 。
[root@localhost ~]# cat /etc/ansible/hosts
[lb]
192.168.100.100 ansible_ssh_user="test" ansible_ssh_pass="test" ansible_become_pass="rootmima"

二、ansible相关命令参数

[root@localhost ~]# ansible -h
Privilege Escalation Options:
  control how and which user you become as on target hosts

  --become-method BECOME_METHOD
                        privilege escalation method to use (default=sudo), use
                        `ansible-doc -t become -l` to list valid choices.
  --become-user BECOME_USER
                        run operations as this user (default=root)
  -K, --ask-become-pass
                        ask for privilege escalation password
  -b, --become          run operations with become (does not imply password
                        prompting)
[root@localhost ~]# ansible-doc -t become -l
ksu        Kerberos substitute user                                 
pbrun      PowerBroker run                                          
enable     Switch to elevated permissions on a network device       
sesu       CA Privileged Access Manager                             
pmrun      Privilege Manager run                                    
runas      Run As user                                              
sudo       Substitute User DO                                       
su         Substitute User                                          
doas       Do As user                                               
pfexec     profile based execution                                  
machinectl Systemd's machinectl privilege escalation                
dzdo       Centrify's Direct Authorize

三、ansible远程切换用户执行测试

3.1、ansible远程切换用户执行命令

[root@localhost ~]# ansible lb -b --become-user root --become-method sudo -m service -a "name=httpd state=stopped"

3.2、ansible playbook远程切换用户执行

[root@localhost ~]# cat /etc/ansible/test.yaml 
- hosts: lb
  become: yes
  become_user: root
  become_method: sudo 
  tasks:
  - name: start httpd
    service: name=httpd state=started

你可能感兴趣的:(自动化,Linux)