Ansible 自動化常用例項 康熙

2022-09-23 05:39:08 字數 2877 閱讀 3455

安裝ansible[root@ansible ~]# yum install -y ansible

修改管理哪些主機的清單檔案[root@ansible ansible]# vi /etc/ansible/hosts[webserver]192.168.1.21192.168.1.22192.168.1.23

給ansible和被管理的主機之間做乙個金鑰登入[root@ansible ansible]# ssh-keygen[root@ansible ansible]# ssh-copy-id 192.168.1.21

管理主機分兩種方式(命令/劇本)命令:命令格式ansible [options]

例子1: ping 測通是否通暢[root@ansible ansible]# ansible webserver -m ping -u root...省略

例子2: 呼叫目錄下的echo命令[root@ansible ansible]# ansible all -a "/bin/echo hello world"...省略

例子3: copy檔案到另乙個目錄[root@ansible ansible]# ansible webserver -m copy -a "src=/etc/passwd dest=/opt/passwd"

...省略

例子4: 安裝軟體[root@ansible ansible]# ansible webserver -m yum -a "name=lrzsz"...省略

例子5: 新增使用者[root@ansible ansible]# ansible webserver -m user -a "name=zhangsan password=123"

例子6: 啟動系統的某個服務[root@ansible ansible]# ansible webserver -m service -a "name=sshd state=started"...省略[root@ansible ansible]# ansible webserver -m service -a "name=httpd state=started"...省略[root@ansible ansible]# ansible webserver -m service -a 'name=httpd state=restarted'...省略

例子7: 重啟某個服務[root@ansible ansible]# ansible webserver -m service -a "name=httpd state=restarted"...省略

例子8: 指定3臺機器執行同乙個命令(屬於並行執行)[root@ansible ansible]# ansible webserver -a "echo hello" -f 3...省略

例子9: 獲取系統資訊[root@ansible ansible]# ansible webserver -m setup...省略

劇本:playbook組成

hosts: 目標主機

remote_user: 執行操作的使用者身份

vars: 執行中的一些變數

tasks: 定義順序執行的action,每個action呼叫乙個模組

handers: event處理操作,僅有在action觸發時才會執行,多次觸發只執行一次並按照宣告的順序執行。例子10: 安裝httpd服務[root@ansible /]# vi test.yml

例子11: 獲取debug資訊[root@ansible /]# vi debug.yml

hosts: webserverremote_user: roottasks:

name: debugdebug:msg: "}"

例子12: shell模組[root@ansible /]# vi shell.yml

hosts: webserverremote_user: roottasks:

name: guanbifanghuoqiangshell: systemctl stop firewalld

例子13: 拷貝模組[root@ansible /]# vi copy.yml

hosts: allremote_user: roottasks:

name: copycopy: src=/etc/passwd dest=/home例子14:建立使用者 然後再 刪除使用者 執行雙任務[root@ansible /]# vi user.yml

hosts: allremote_user: roottasks:

name: create useruser:name: apenguid: 5000group: ftpshell: /bin/bashgroups: apengappend: yes

name: delete useruser:name: apengstate: absentremove: yes

例子15: 安裝httpd 然後再 解除安裝[root@ansible /]# vi yum.yml

例項16: command模組[root@ansible /]# vi command.yml

hosts: rootremote_user: roottasks:

name: cmdcommand: ls

自動化運維ansible

sever1 172.25.60.1 server2 172.25.60.2 server3 172.25.60.3 etc ansible ansible.cfg 主配置檔案,配置ansible工作特性 etc ansible hosts 主機清單 etc ansible roles 存放角色的目...

自動化運維工具ansible常用模組

root nb01 ansible doc l wc l 1378 模組數高大1378個 root nb01 ansible doc help ansible doc 的幫助命令 root nb01 ansible doc ping 檢視ping模組的詳細幫助相當於shell的man幫助 root ...

ansible自動化批量安裝nginx

ansible安裝及ssh免密登入請參考 ansible playbook 劇本 ansible doc 獲取幫助文件 ansible playbook採用yaml語法 核心元件 hosts 定義單個主機或組,vars定義變數,remote user定義執行命令的遠端使用者,tasks定義執行哪些命...