ansible2.9.5使用become參數實現sudo功能


一,為什么要使用sudo?

1,

生產環境中,為了安全因素,我們不會直接使用root來登錄到server,

確實有需要的情況下,我們再使用sudo切換到root權限。

所以很多ansible的演示直接使用root還是不夠安全的,

生產環境中的機器也不會開放權限允許root直接登錄

2,

ansible在新版本中已經不支持sudo參數,

統一改為使用become方式來實現角色的切換

繼續使用sudo參數會報錯如下:

ansible: error: unrecognized arguments: --sudo

通過查詢手冊可以發現,2.9.5中不存在 sudo這個參數:

[liuhongdi@centos8 ~]$ man ansible

我們可以通過become方法實現sudo功能

 

說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest

         對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/

 說明:作者:劉宏締 郵箱: 371125307@qq.com

 

二,使用sudo的前提:

在hosts中配置的登錄賬號在受控端機器上需要有sudo的權限:

有疑問可以參見這一篇:

https://www.cnblogs.com/architectforest/p/12509041.html

我們在這里的例子中,

登錄到服務器的webop賬號,有sudo的權限

 

三,ansible使用become的例子:

1,在ansible配置文件中增加sudo的密碼:

[root@centos8 ~]# vi /etc/ansible/hosts 

內容為:

#ansible_ssh_user   登錄用戶

#ansible_sudo_pass  登錄用戶sudo要用的密碼(就是登錄用戶自己的密碼)

[yujian]
121.122.123.47:12888 ansible_ssh_user=webop  ansible_sudo_pass="weboppass"

 

2,實際使用become實現sudo 

 

become 激活權限提升

become_user  您要成為的用戶

become_method 切換新用戶的方法:包括:

                 sudo / su / pbrun / pfexec / doas / dzdo / ksu / runas / machinectl

 

[liuhongdi@centos8 ~]$  ansible yujian -m shell -a "cd /data/site/think_www;git status;whoami" --become  --become-method=sudo --become-user=root
121.122.123.47 | CHANGED | rc=0 >>
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
root

 

四,查看ansible的版本

[liuhongdi@centos8 ~]$ ansible --version
ansible 2.9.5

 

五,查看centos的版本

[liuhongdi@centos8 ~]$ cat /etc/redhat-release 
CentOS Linux release 8.1.1911 (Core)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM