通過ansible大量設定隨機密碼

來源:互聯網
上載者:User

要求:
批量修改伺服器的某帳號(假設root帳號)密碼,用隨機產生的字串做密碼

環境:
假設/etc/ansible/hosts檔案中伺服器的目標組如下

[target-servers]192.168.0.[1:100]
執行操作

1 通過openssl rand命令,在每台遠程伺服器上產生隨機字串用做候選口令字元

ansible target-servers -m shell -a "openssl rand -base64 12 > ~/.openssl"

可以用如下命令查看產生的結果

ansible target-servers -m shell -a "cat ~/.openssl"

2 用候選字串設定密碼
上面的openssl rand -base64 12命令產生的是16位的隨機字串,比如,取前12位作為密碼的話,可以通過如下set-pass.sh指令碼實現:

#!/bin/bashPASS=`cat ~/.openssl`SUBPASS=`echo ${PASS:0:12}`echo "root:$SUBPASS" | chpasswd

將如上指令碼放在ansible中控機上,通過script模組就可以在遠端伺服器上執行,簡單的playbook如下set-pass.yml:

---- hosts: '{{myhosts}}'  remote_user: admin  tasks:  - name: set passwd    script: ~/set-pass.sh     become: true

批量執行操作為:

ansible-playbook set-pass.yml -e "myhosts=target-servers"

執行之後密碼就設定完成了。

3 將各伺服器上的字串檔案收歸到中控機上
可以通過ansible的fetch模組擷取遠端伺服器上的檔案,簡單的playbook如下fetch-file.yml:

---- hosts: '{{myhosts}}'  remote_user: admin  tasks:  - name: fetch file    fetch:      src: ~/.openssl      dest: ~/fetch/openssl-{{ inventory_hostname }}      flat: yes

批量執行操作為:

ansible-playbook fetch-file.yml -e "myhosts=target-servers"

執行之後就可以在~/fetch/目錄下看到擷取到的檔案,裡面的內容就是上面產生的密碼字串

最後,可以將遠端伺服器上的字串檔案刪除:

ansible target-servers -m shell -a "rm -f ~/.openssl"

上面的所有操作,可以匯總寫到一個playbook裡面。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.