ansible
ansible不是以服務的方式運行,用戶需要時執行
首先必須設置主機清單 vim /etc/ansible/hosts ,添加如下內容:
[web]
172.16.41.51
172.16.41.61
[beifen]
172.16.41.88
172.16.41.152
ansible 172.16.41.61 -m ping 如果主機清單中未設置172.16.41.61,則此命令執行報錯
[root@centos76 11:13 .ssh]# ansible 172.16.41.61 -m ping
[WARNING]: Could not match supplied host pattern, ignoring: 172.16.41.61
[WARNING]: No hosts matched, nothing to do
主機清單添加對應的地址後執行命令:第一次執行會出現yes/no的提示
ansible 172.16.41.51 -m ping
The authenticity of host '172.16.41.51 (172.16.41.51)' can't be established.
ECDSA key fingerprint is SHA256:ipiclPOhfzuGppT1kscx7sIW5oadl2G+VKKgmwi4NX0.
ECDSA key fingerprint is MD5:f1:40:3e:af:56:a8:95:df:f6:bc:5a:f3:13:a6:fe:e1.
Are you sure you want to continue connecting (yes/no)? yes
取消此項設置:在配置文件中vim /etc/ansible/ansible.cfg 取消下面的註釋
#host_key_checking = False修改爲host_key_checking = False
測試命令,提示下列錯誤,即驗證失敗,未設置是基於口令或基於publickey驗證
[root@centos76 11:15 .ssh]# ansible 172.16.41.61 -m ping
172.16.41.61 | UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: Warning: Permanently added '172.16.41.61' (RSA) to the list of known hosts.\r\nPermission denied (publickey,password).",
"unreachable": true
}
需要添加選項 -k ansible 172.16.41.61 -m ping -k 然後輸入主機對應默認的root密碼即可成功,而且只可以輸入一次,如果多個主機口令不一致會導致執行失敗
ansible <host-pattern> [-m module_name] [-a args] 選項定義:
-m module 指定模塊,默認爲command
-k 提示輸入ssh連接密碼,默認key驗證
-u 指定遠程執行的用戶
-b sudo切換
-K 提示輸入sudo時的口令
-C 檢查,並不執行
--list-hosts 顯示主機列表,可簡寫 --list
-v 詳細過程 –vv -vvv更詳細
基於key驗證,需要將在安裝ansible的機器上生成ssh公鑰並拷貝值主機清單的機器上
ssh-keygen;ssh-copy-id 172.16.41.51;;ssh-copy-id 172.16.41.61;ssh-copy-id 172.16.41.152;ssh-copy-id 172.16.41.88 ssh-copy-id 172.16.41.52
測試分組的連接情況:ansible web/beifen/all -m ping
查看組的主機列表:ansible all --list-host ansible all --list ansible web --list-host ansible beifen--list-host
配置文件修改內容:
log_path = /var/log/ansible.log 取消此行的註釋,開啓日誌功能
host_key_checking = False 檢查對應服務器的host_key,建議取消註釋
#module_name = command 將此行修改爲下面對應的內容,將默認的模塊名修改爲shell
module_name = shell
host-pattern:
[root@centos76 12:40 .ssh]# ansible 'web:!beifen' --list
[root@centos76 12:40 .ssh]# ansible "web:!beifen" --list
注意上述示例中單引號和雙引號的標記,如果使用非 ! 的話需要使用單引號,使用雙引號會報錯
ansible常用模塊:
1、command模塊:執行命令 ansible-doc -s command
ansible web -m command -a 'cat /etc/redhat-release'
ansible web -m command -a 'chdir=/etc cat redhat-release'
ansible web -m command -a 'ls /data'
ansible web -m command -a 'rm -rf /data'
ansible web -m command -a 'ls /data'
ansible web -m command -a 'hostname'
ansible web -m command -a 'echo $HOSTNAME' 不可以顯示出預想的結果,結果是
ansible web -m command -a "echo $HOSTNAME" 不可以顯示出預想的結果,結果是
ansible web -m command -a "echo 123456|passwd --stdin root" 不可以顯示出預想的結果,結果是
2、shell模塊 :執行命令 注意單引號雙引號 ansible-doc -s shell
ansible web -m shell -a 'echo $HOSTNAME' 注意使用的是單引號 使用雙引號ansible web -m shell -a "echo $HOSTNAME" 返回的是ansible的主機名
ansible web -m shell -a 'chdir=/data touch a.txt'
ansible web -m shell -a 'ls /data'
ansible web -m shell -a 'sed -i "s/SELINUX=disabled/SELINUX=enforcing/" /etc/selinux/config'
ansible web -m shell -a 'cat /etc/selinux/config'
ansible web -m shell -a 'sed -i "s/SELINUX=enforcing/SELINUX=disabled/" /etc/selinux/config'
ansible web -m shell -a 'yum remove -y httpd'
3、script模塊:執行腳本 ansible-doc -s script
ansible web -m script -a '/data/test.sh'
4、copy模塊 :拷貝文件 ansible-doc -s copy
ansible web -m copy -a 'src=/etc/fstab dest=/data/151 mode=777 owner=wang group=wang backup=yes' 指定備份backup
複製目錄和文件夾:ansible web -m copy -a 'src=/etc/sysconfig dest=/data/'
指定內容生成文件:ansible web -m copy -a 'content=wangbin\nceshi\n123\n456 dest=/data/copy.txt'
ansible web -m copy -a 'content=[test]\nname=test\nurl=test dest=/data/test.txt'
5、fetch模塊 :抓取文件,當前不支持抓取文件夾和目錄 ansible-doc -s fetch
ansible web -m fetch -a 'src=/data/test.txt dest=/data'
ansible web -m shell -a 'tar jcvf /root/data.tar.bz2 /data' 打包命令
ansible web -m fetch -a 'src=/root/data.tar.bz2 dest=/data' 抓取打包文件
6、file模塊:設置文件屬性 ansible-doc -s file
ansible web -m file -a 'path=/data/test.log owner=wang mode=777'
ansible web -m file -a 'src=/data/test.log name=/data/test.link state=link' 創建軟連接 state=hard 創建硬鏈接
ansible web -m file -a 'path=/data/dir1 state=directory' 創建目錄
ansible web -m file -a 'path=/data/f1.txt state=touch' 創建文件
ansible web -m file -a 'path=/data/f1.txt state=absent' 刪除文件
ansible web -m file -a 'path=/data/dir1 state=absent' 刪除目錄 absent 關鍵字
ansible web -m file -a 'path=/data/ state=absent' 刪除所有文件,此種用法不可用,不會刪除所有的文件
ansible web -m shell -a 'rm -rf /data/"' 這樣刪除目錄下的所有文件
7、hostname模塊:修改主機名
ansible 172.16.41.61 -m hostname -a 'name=6.10-mini' centos6 修改了/etc/sysconfig/network文件 未修改/etc/hosts
ansible 172.16.41.51 -m hostname -a 'name=7.6-mini-DNS' centos7 修改了/etc/hostname 未修改/etc/hosts
8、cron模塊:計劃任務
ansible web -m cron -a 'name=synctime minute=/5 job="/usr/sbin/ntpdate 172.16.41.151 &> /dev/null"'
ansible web -m cron -a 'name=synctime minute=/5 job="/usr/sbin/ntpdate 172.16.41.151 &> /dev/null" disabled=true' 禁用定義的計劃任務,實際上就是註釋掉計劃任務
ansible web -m cron -a 'name=synctime minute=/5 job="/usr/sbin/ntpdate 172.16.41.151 &> /dev/null" disabled=false' 啓用禁用的計劃任務
ansible web -m cron -a 'name=synctime minute=/5 job="/usr/sbin/ntpdate 172.16.41.151 &> /dev/null" state=absent' 刪除計劃任務
ansible web -m shell -a 'crontab -l '
9、yum模塊:管理包
ansible web -m yum -a 'name=ntpdate'
ansible 172.16.41.88 -m yum -a 'name=ntpdate state=absent' 卸載包
10、service模塊:管理服務
ansible web -m service -a 'name=named state=started enabled=yes' enabled 設置爲true和yes都可以
ansible web -m shell -a 'ss -ntlu|grep 53'
ansible web -a 'service named status '
11、user模塊:用戶管理
ansible web -m user -a 'name=wangbin system=yes shell=/sbin/nologin'
ansible web -m user -a 'name=mysql state=absent remove=yes'
remove=yes 刪除用戶家目錄 state=absent 移除用戶
12、group組:管理組
ansible-galaxy 角色
連接 https://galaxy.ansible.com 下載相應的roles
列出所有已安裝的galaxy
ansible-galaxy list
安裝galaxy
ansible-galaxy install geerlingguy.redis
刪除galaxy
ansible-galaxy remove geerlingguy.redis
查看相關文件:tree /root/.ansible/roles/
ansible-pull
ansible-vault
ansible-vault encrypt hello.yml 加密
功能:管理加密解密yml文件
ansible-vault [create|decrypt|edit|encrypt|rekey|view]
ansible-vault encrypt hello.yml 加密
ansible-vault decrypt hello.yml 解密
ansible-vault view hello.yml 查看
ansible-vault edit hello.yml 編輯加密文件
ansible-vault rekey hello.yml 修改口令
ansible-vault create new.yml 創建新文件
ansible-console:交互式
ansible-playbook
-C:測試但不執行,幹跑模式
ansible-playbook -C hello.yml
vim hello.yml 注意語法結果,嚴格要求空格個數和對齊
#hello world yml file
- hosts: web
remote_user: root
tasks:
- name: hello world
command: /usr/bin/wall hello world
yaml語言:
三個連續橫線區分多個檔案 可以用三個點號 表示檔案結尾
縮進必須是統一的,不能空格和tab混用
縮進的級別也必須是一致的,同樣的縮進代表同樣的級別,程序判別配置的級別是通過縮進結合換行來實現的
yaml語法:
列表 其所有元素都使用 - 打頭
字典 通常由多個key和value構成 kay: value 注意冒號 : 後面一定要有空格 多個之間使用 , 分隔
Playbook核心元素
Hosts 執行的遠程主機列表
Tasks 任務集
Varniables 內置變量或自定義變量在playbook中調用
Templates 模板,可替換模板文件中的變量並實現一些簡單邏輯的文件
Handlers 和 notity 結合使用,由特定條件觸發的操作,滿足條件方纔執行,否則不執行
tags 標籤 指定某條任務執行,用於選擇運行playbook中的部分代碼。ansible具有冪等性,因此會自動跳過沒有變化的部分,即便如此,有些代碼爲測試其確實沒有發生變化的時間依然會非常地長。此時,如果確信其沒有變化,就可以通過tags跳過此些代碼片斷
ansible-playbook –t tagsname useradd.yml
-
hosts: web
remote_user: root
tasks:
- name: name1
module: arguments
httpd.yml 其中路徑可以寫相對httpd.yml的相對路徑 例如下述的 src=files/httpd.conf#install httpd
- hosts: web
remote_user: root
tasks:
- name: install httpd
yum: name=httpd
- name: copy conf
copy: src=/data/httpd.conf dest=/etc/httpd/conf/ backup=yes
- name: service
service: name=httpd state=started enabled=yes
user.yml
#user add
- hosts: web
remote_user: root
tasks:
- name: group add
group: name=mysql gid=3306 system=yes
- name: user add
user: name=mysql group=mysql uid=3306 home=/data/mysql shell=/sbin/nologin system=yes create_home=no
handlers和notify結合使用觸發條件
Handlers
是task列表,這些task與前述的task並沒有本質上的不同,用於當關注的資源發生變化時,纔會採取一定的操作
Notify此action可用於在每個play的最後被觸發,這樣可避免多次有改變發生時每次都執行指定的操作,僅在所有的變化發生完成後一次性地執行指定操作。在notify中列出的操作稱爲handler,也即notify中調用handler中定義的操作
#install httpd
- hosts: web
remote_user: root
tasks:
- name: install httpd
yum: name=httpd
- name: copy conf
copy: src=files/httpd.conf dest=/etc/httpd/conf/ backup=yes
notify: restart service
- name: service
service: name=httpd state=started enabled=yes
handlers:
- name: restart service
service: name=httpd state=restarted
tags 執行時使用-t 參數,多個參數之間使用逗號分隔 多個不同的動作可以使用相同的標籤
ansible-playbook -t config,service httpd.yml
Playbook中變量使用
變量名:僅能由字母、數字和下劃線組成,且只能以字母開頭
變量來源:
1 ansible setup facts 遠程主機的所有變量都可直接調用
setup模塊:
ansible all -m setup
ansible all -m setup -a 'filter="*fqdn"'
ansible_fqdn ansible_hostname ansible_nodename 主機名 ansible_memtotal_mb 內存信息
引用變量 {{ 變量名 }} 雙大括號之間的變量前後可以不加空格,但一般建議添加一個空格
2 在/etc/ansible/hosts中定義
普通變量:主機組中主機單獨定義,優先級高於公共變量
公共(組)變量:針對主機組中所有主機定義統一變量
主機清單中定義變量:/etc/ansible/hosts
[web]
172.16.41.51 port=80 普通變量
172.16.41.61 port=8080 普通變量
[web:vars]
mark="---" 公共(組)變量
port=88888
普通變量的優先級高於公共組合變量
3 通過命令行指定變量,優先級最高 命令行定義變量 -e選項 -e 變量=變量值
ansible-playbook –e varname=value ansible-playbook -e port=8484 file.yml
4 playbook中定義的變量 高於主機清單中的變量
vars:
- var1: value1
- var2: value2
5 在獨立的變量YAML文件中定義 引用
port: 2222
mark: ___
6 在role中定義
file var
- hosts: web
remote_user: root
vars:
- port: 4848
vars_files:
- vars.yml vars.yml是獨立的變量YAML文件
tasks:
- name: file
file: name=/data/{{ansible_nodename}}{{mark}}{{port}}.log state=touch
變量優先級:命令行變量(-e) >>獨立的變量YAML文件>>playbook變量>主機清單普通變量>主機清單公共(組)變量
模版template 根據模塊文件動態生成對應的配置文件
文本文件,嵌套有腳本(使用模板編程語言編寫)
Jinja2語言,使用字面量,有下面形式
字符串:使用單引號或雙引號
數字:整數,浮點數
列表:[item1, item2, ...] 可以修改
元組:(item1, item2, ...) 不可以修改
字典:{key1:value1, key2:value2, ...}
布爾型:true/false
算術運算:+, -, *, /, //, %, ** // 整除
比較操作:==, !=, >, >=, <, <=
邏輯運算:and,or,not
流表達式:For,If,When
template功能:根據模塊文件動態生成對應的配置文件
template文件必須存放於templates目錄下,且命名爲 .j2 結尾
在放置yaml文件的目錄下 創建 templates目錄
yml 文件需和templates目錄平級,目錄結構如下:
./
├── temnginx.yml
└── templates
└── nginx.conf.j2
ansible web -m shell -a 'yum -y remove httpd'
nginx.yml 內容如下:
#nginx
- hosts: web7
remote_user: root
tasks:
- name: package
yum: name=nginx
- name: conf
template: src=nginx.j2 dest=/etc/nginx/nginx.conf
notify: restart service
- name: service
service: name=nginx state=started enabled=yes
handlers:
- name: restart service
service: name=nginx state=restarted
nginx配置進程個數:
worker_processes {{ansible_processor_vcpus*2+2}};
引用模版:
- name: config
template: src=模版文件名稱 dest=配置文件存放位置
when:
系統主版本:ansible_distribution_major_version 6或者7
#install httpd
- hosts: web
remote_user: root
tasks:
- name: install httpd
yum: name=httpd
- name: copy conf 7
template: src=templates/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
when: ansible_distribution_major_version == "7"
notify: restart service
- name: copy conf 6
template: src=templates/httpd6.conf.j2 dest=/etc/httpd/conf/httpd.conf
when: ansible_distribution_major_version == "6"
notify: restart service
- name: service
service: name=httpd state=started enabled=yes
handlers:
- name: restart service
service: name=httpd state=restarted
迭代:
- name: add several users
user: name={{ item }} state=present groups=wheel
with_items: - testuser1
- testuser2
新建組和用戶,組合用戶先定義,使用字典 - name: create user
user: name={{item.named}} group{{item.group}}
with items:
- {name: "alice",group: "agroup"}
- {name: "bob",group: "bgroup"}
- {name: "centos",group: "cgroup"}
Playbook中template for if
vim test.for.j2
{%for i in test_ports%}
server {
listen {{i}}
servername www.a.com
root /app/websitea
}
{%endfor%}
vim test.for.jml
- host: web
remote_user: root
vars:
test_ports:
- 81
- 82
- 83
tasks:
- name: template
template: src=test.for.j2 dest=/data/test.conf
vim test.for.jml
- host: web
remote_user: root
vars:
test_ports:
- 81
- 82
- 83
tasks:
- name: template
template: src=test.for.j2 dest=/data/test.conf
vim test2.for.jml
- host: web
remote_user: root
vars:
vhosts:
- web1:
port: 81
name:www.a.com
dir: /data/websitea
- web2:
port: 82
name:www.b.com
dir: /data/websiteb
- web3
port: 83
name:www.c.com
dir: /data/websiteac
tasks:
- name: template
template: src=test2.for.j2 dest=/data/test2.conf
vim test2.for.j2
{%for i in vhosts%}
server {
listen {{i.port}}
servername {{i.name}}
root {{i.dir}}
}
{%endfor%}