ansible安裝及使用

軟件環境:rhel7.3 由於低版本有軟件依賴太多要解決
server17 172.25.135.17 控制端
server18 172.25.135.18 web 管理
server19 172.25.135.19 mysql 管理
[root@server17 ~]# yum install epel-release-7-11.noarch.rpm
安裝epel軟件源
[root@server17 ~]# yum install ansibe
[root@server17 ~]# ansible --version #查看版本
[root@server17 ~]# yum install tree
[root@server17 ~]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── hosts
└── roles
[root@server17 ~]# vim /etc/ansible/hosts #末尾添加
[web]
172.25.135.18
[mysql]
172.25.135.19html

[root@server17 ~]# ssh-keygen -t rsa #一路回車作免密
[root@server17 ~]# ssh-copy-id root@172.25.135.18
[root@server17 ~]# ssh-copy-id root@172.25.135.19
[root@server17 ~]# ansible-doc -l #查看ansible全部模塊,q退出
conmand模塊mysql

格式:ansible+組名 -m 指定模塊 -a '命令’
[root@server17 ~]# ansible all -m command -a 'date'
172.25.135.18 | CHANGED | rc=0 >>
2018年 12月 06日 星期四 07:04:45 ESTweb

172.25.135.19 | CHANGED | rc=0 >>
2018年 12月 06日 星期四 07:04:45 ESTsql

user模塊
[root@server17 ~]# ansible all -m user -a 'name="westos" system=yes' #all指定全部組,name=westos,system=yes固定參數。
[root@server17 ~]# ansible all -m user -a 'name="westos" state=absent' #all指定全部組,刪除全部用戶。
yum模塊apache

用yum模塊給被控制主機一鍵安裝衆多服務
service模塊vim

啓動、關閉、查看服務狀態數組

ansible web -a 'systemctl status httpd' #查看服務狀態數據結構

ansible web -a 'systemctl start httpd' #開啓服務app

ansible web -a 'systemctl stopped httpd' #關閉服務
[root@server17 ~]# ansible all -m yum -a 'name=httpd'
[root@server17 ~]# ansible web -a 'systemctl start httpd'
script模塊
[root@server17 ~]# vim westos.sh
[root@server17 ~]# chmod +x westos.sh
[root@server17 ~]# ./westos.sh
ceshi
[root@server17 ~]# ansible mysql -m script -a '/root/westos.sh'
setup模塊ssh

ansible mysql -m setup #查看被控制主機信息
[root@server17 ~]# ansible mysql -m ping
ansible的劇本是使用yaml語言進行編寫的,基本語法以下
基本語法:
一、大小寫
二、同級別要對齊,縮進表示層級
三、縮進不容許使用Tab鍵
四、縮進空格數不規定,相同元素區分便可
支持的數據結構:
一、對象:鍵值對集合,又稱映射/哈希/字典
例如:name:example 鍵:值
二、數組:一組按次序排列的值,又稱序列/列表/
例如:-apple
三、純量:單個的、再也不分的值
例如:number:12.30
sure:true
play-book劇本
經過tasks調用ansible的模板將多個play組織在一個playbook中運行。
palybook構成部分:
(1)tasks:任務,至關於執行事務
(2)variables:變量(定義場景:hosts文件;劇本中;命令中)
(3)templates:模板
(4)handlers:處理器,知足條件,觸發執行操做
(5)roles:角色
[root@server17 ~]# cd /opt/
[root@server17 opt]# ls
[root@server17 opt]# vim index.html
westos.org
[root@server17 ~]# ansible-playbook book.yml

  • hosts: mysql #hosts定義了配置文件中的組名
    remote_user: root #劇本中的演員:root用戶,也能夠是你推送祕鑰的任意用

    tasks: #任務,如下是執行什麼任務
    • name: download apache #自行定義的名稱
      yum: name=httpd #指定模塊,模塊後跟相對應的操做
    • name: stopped firewalld
      service: name=firewalld state=stopped
    • name: copy index.html
      template: src=/opt/index.html dest=/var/www/html/index.html #這裏>的模板要注意,須要建立推送的文件並寫入你指定的內容。
    • name: started apacheservice: name=httpd state=started[root@server17 ~]# ansible-playbook book.yml --syntax-check #檢查yaml語法[root@server17 ~]# ansible-playbook book.yml --list-tasks #檢查tasks任務
相關文章
相關標籤/搜索