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
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值