一、ansible安裝
#隻需要管理端安裝
yum install epel-release
yum install ansible
二、配置
vim /etc//ansible/hosts #添加遠端被管理端主機
192.168.10.148
k8s-master
k8s-node-2
三、 生成公鑰放到被管理端
ssh-keygen -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i ~/.ssh/id_rsa.pub root@k8s-master
ssh-copy-id -i ~/.ssh/id_rsa.pub root@k8s-node-2
管理端測試: ansible all -m ping
ansible all -m ping -u alex #以alex使用者執行
ansible all -m ping -u alex --sudo --sudo-user batman #sudo方式運作
四、指令
#開啟兩個程序并行執行,關閉atlanta組的所有主機
ansible atlanta -a "/sbin/reboot" -f 2
#拷貝檔案到atlanta組的主機
ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts"
#修改為檔案權限
ansible atlanta -m file -a "/tmp/hosts mode=777"
#建立目錄
ansible atlanta -m file -a "dest=/tmp/c mode=755 owner=nginx group=nginx state=directory"
#删除目錄
ansible atlanta -m file -a "dest=/tmp/c state=absent"
#确認軟體包是否安裝,但不去更新
ansible atlanta -m yum -a "name=nginx state=present"
#确認一個軟體包沒有安裝
ansible atlanta -m yum -a "name=nginx state=absent"
#使用 ‘user’ 子產品可以友善的建立賬戶,删除賬戶,或是管理現有的賬戶:
ansible all -m user -a "name=foo password=<crypted password here>"
ansible all -m user -a "name=foo state=absent"
#啟動服務
ansible atlanta -m service -a "name=docker state=started"
#重新開機服務
ansible atlanta -m service -a "name=docker state=restarted"
#停止服務
ansible atlanta -m service -a "name=docker state=stopped"
#需要長時間運作的指令可以放到背景去,在指令開始運作後我們也可以檢查運作的狀态.如果運作指令後,不想擷取傳回的資訊, 可執行如下指令:
ansible all -B 3600 -P 0 -a "/usr/bin/long_running_operation --do-stuff"
#如果你确定要在指令運作後檢查運作的狀态,可以使用 async_status 子產品.前面執行背景指令後會傳回一個 job id, 将這個 id 傳給 async_status 子產品:
ansible web1.example.com -m async_status -a "jid=488359678239.2844"
#擷取狀态的指令如下:
ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"
其中
-B 1800
表示最多運作30分鐘,
-P 60
表示每隔60秒擷取一次狀态資訊.
五、http安裝配置檔案修改例子
vim /etc/ansible/hosts #添加主機組
[testhost]
192.168.10.224
編寫yaml檔案
vim http.yml #修改httpd.conf檔案時,notify會通知用戶端重新開機httpd
- hosts: testhost
vars:
src_http_dir: "/etc/httpd"
dest_http_dir: "/tmp"
remote_user: root
tasks:
- name: instal httpd service
yum: name=httpd state=present
- name: copy httpd conf
copy: src="`src_http_dir`/conf/httpd.conf" dest=/etc/httpd/conf/httpd.conf
notify:
- restart httpd service
- name: start httpd service
service: name=httpd state=started enabled=true
handlers:
- name: restart httpd service
service: name=httpd state=restarted
變量使用
vim test1.yml
copy: src="`src_http_dir`/conf/httpd.conf" dest="`dest_http_dir`/http.conf.ansible"
模闆使用
vim httpd.conf
#修改以下内容
Listen `ansible_all_ipv4_addresses`.`0`:`http_port`
ServerName `ansible_nodename`
vim test2.yml
http_port: 8010
http_dir: /etc/httpd/conf
template: src=/etc/ansible/httpd.conf dest="`http_dir`/httpd.conf"
- restart httpd service
- name: restart httpd service
service: name=httpd state=restarted