Ansible入門使用

最近在學習ansible,在此記錄一下使用過程 --2017年12月21日 15:22:02
 
一:server端yum安裝Ansible
serverip:192.168.1.46
# Redhat/CentOS Linux上,Ansible目前放在的epel源中
sudo yum install epel-release -y
sudo yum install ansible -y
ansible --version #查看是否安裝成功
二:基本配置訪問
 
如需經過 192.168.1.46 管理 192.168.1.47 192.168.1.48 192.168.1.49
在 192.168.1.46 生成一個密鑰,公鑰傳到各自服務器
 # ssh-keygen -t rsa -f ./.ssh/id_rsa.pub -P ""
傳密鑰到各自服務器
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.47
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.48
# ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.1.49
若是服務器是在同一連續IP段下,可以使用
# for i in {1..4}; do ssh-copy-id -i /root/.ssh/id_rsa.pub root@ 192.168.78.1$i; done     
配置ansible主機清單,使用yum安裝的文件( Host Inventory )在  /etc/ansible/host中
vi  /etc/ansible/hosts
 添加
[myhost]
192.168.1.47
192.168.1.48
192.168.1.49
[zabbix-host]
192.168.1.49
192.168.1.50:9888  #若是主機端口號不是22,使用冒號分隔端口號
 
安裝完畢直接在46上面輸入一條命令測試:
# ansible all -m command -a "who"
 
2.1 或者不傳key,直接在 /etc/ansible/hosts 填入對應服務器帳號密碼便可(這種比較方便),如:
[linux]
192.168.1.70 ansible_ssh_user="root" ansible_ssh_pass="1qaz" ansible_su_pass="1qaz"
[windows]
192.168.1.44 ansible_ssh_user="Administrator" ansible_ssh_pass="1qaz" ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_server_cert_validation=ignore

至此,ansible已經安裝成功並能夠操做遠程機器
 
三:使用說明
ansible相關程序文件:
/usr/bin/ansible:命令行工具
  #命令格式:
ansible <pattern_goes_here> -m <module_name> -a <arguments>
#例如:
ansible all -m copy -a   'src=/etc/my.cnf dest=/etc/'
#幾個重要參數的含義:
-i      #指定inventory文件(主機定義文件)
all     #表示在host文件中定義的全部的主機,能夠替換成響應的組名或IP地址
#針對於主機能夠使用匹配規則(全部的匹配都基於配置文件中的主機)
   IP地址: ansible  192.168.239.132
   IP匹配: ansible  192.168.239.*
   IP匹配: ansible  *
   組匹配: ansible 組名:& hostname        <表示這個組跟其餘組的一個主機>
   組匹配: ansible 組名:! hostname        <表示這個組可是出除去這個組的這個主機>
#相似的匹配還不少,幾乎能想到的匹配都能支持,具體參照http://docs.ansible.com/intro_patterns.html
-m      #指定使用哪一個模塊,默認採用command模塊
-a      #指定模塊的參數,每一個模塊都有相應的模塊參數
  -u      #指定遠端機器的用戶
  
/usr/bin/ansible-doc:幫助文檔
    /usr/bin/ansible-doc -s yum  #查詢yum相關幫助
/usr/bin/ansible-playbook:劇本執行工具
/etc/ansible/ansible.cfg:主配置文件
/etc/ansible/hosts:管理的主機清單(Host Inventory)
/etc/ansible/roles:角色存放處
 
注意:<host-pattern>默認讀取/etc/ansible/hosts,也能夠指明自定義文件路徑
-iPATH, --inventory=PATH:指明使用的host inventory文件路徑                                                                                                                                                                                                               

四:詳細使用要點說明
  • ansible-doc -l 查看總共有哪些模塊
  • ansible-doc ping 顯示某個模塊的用法
  • ansible-doc -s ping 顯示某個模塊在playbooks中的代碼片斷
 
安裝問題:
管理端ansible出現ssh-copy-id: command not found 錯誤
yum -y install openssh-clients 
 
參考:
相關文章
相關標籤/搜索