Ansible主配置文件:/etc/ansible/ansible.cfg
Inventory配置文件:/etc/ansible/hosts
定義主機(jī)多種方式:
ip:10.155.55.10
name:linux1
主機(jī)組:
[test]
compute1
compute2
compute[2:5]
密鑰生成配置
生成:ssh-keygen -t rsa
復(fù)制到被管理主機(jī): ssh-copy-id -i /root/.ssh/id_rsa.pub root@ip
測試:ssh root@172.16.100.8 'date'
時間同步:ntpdate 172.16.0.1
ansible-doc -l #查看支持的命令
ansible-doc -s yum #查看具體的用法
ansible語法:ansible <host-pattern> [-f forks] [-m module] [-a args]
-f:啟動的線程數(shù)
-m:使用的模塊
-a:使用的命令
常見模塊:
command:命令模塊,默認(rèn)模塊
ansible all -a 'date'
cron:
ansible web -m cron -a 'minute="/10" job="/bin/echo hello" name="test cron job"'
ansible web -m cron -a 'minute="/10"
sate:present 安裝 absent 移除
user:
ansible web -m user -a 'name=mysql uid=306 system=yes group=mysql'
group:
ansible web -m group -a 'name=mysql gid=306 system=yes'
copy:
ansible all -m copy -a 'src=/ect/fstab dest=/tmp/fstab.ansible owner=root mode=640'
ansible all -m copy -a 'content="Hello Ansible\nHi Mageedu" dest=/tmp/test.ansible'
file:設(shè)定文件屬性,創(chuàng)建鏈接文件
ansible all -m file -a 'path=/tmp/fstab.link src=/tmp/fstab.ansible state=link'
ping:測試連通
ansible all -m ping
service: 管理服務(wù)
ansible web -m service -a 'enabled=true name=httpd state=started'
shell: 相比command支持管道變量等復(fù)雜命令
ansible all -m user -a 'name=user1'
ansible all -m shell -a 'echo mageedu | passwd --stdin user1'
script:將本地腳本復(fù)制到遠(yuǎn)程主機(jī),并運(yùn)行
ansible all -m script -a "test.sh" #僅支持相對路徑
yum: 安裝程序包
ansible all -m yum -a "name=zsh state=present"
setup: 收集遠(yuǎn)程主機(jī)的facts,在jinja2模板中可以調(diào)用
ansible all -m setup -a 'filter=ansible_ec2_instance_id'
- name: node1
command: echo "ok!"
when: ansible_default_ipv4.address == "{{ HA_node1 }}"
tags:- node1
- name: node2
command: echo "no!"
when: ansible_default_ipv4.address == "{{ HA_node2 }}"
tags:- node2
YAML: http://www.yaml.org
鍵值對:
序列-
字典{,,}
register:將任務(wù)的輸出作為變量,然后用于其他任務(wù)。
傳遞變量:ansible-playbook test.yml --extra-vars "hosts=www user=mageedu"
[web:vars] #組變量
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com
delegate_to: 委派
委派另一個主機(jī)也執(zhí)行任務(wù)
tag:打上標(biāo)記,執(zhí)行命令時可以只執(zhí)行標(biāo)記部分 #ansible-playbook apache.yml --tags="conf"
wait_for:等待 #默認(rèn)等待300秒,默認(rèn)檢查是否started
search_regex:是否包含某個字符串
dist_sort:去重分類
set_fact:定義變量,但是不能跨playbooks
迭代:重復(fù)性執(zhí)行任務(wù)。調(diào)用使用item,定義循環(huán)列表使用with_items。
handler:發(fā)生改變用notify觸發(fā)執(zhí)行handler.
when:條件語句
templates:模板調(diào)用
roles:使代碼段反復(fù)調(diào)用
目錄名同角色名
目錄結(jié)構(gòu)固定:
files靜態(tài)文件
templates jinjia2模板文件
tasks 至少有main.yml文件,定義各tasks
handlers至少有main.yml文件,定義各handlers
vars至少有main.yml文件,定義變量
meta定義依賴關(guān)系等信息
ansible官方文檔:http://docs.ansible.com/ansible
ansible-playbook 例子:https://galaxy.ansible.com/list#/roles?page=1&page_size=10