1 安裝與目錄組織
安裝略。目錄大概如下:
ansible.cfg
hosts
host_vars/
include_tasks.yml
main.yml
ansible.cfg
可以這這樣:
[defaults]
inventory = ./hosts
library = /usr/share/ansible
forks = 30
remote_user = tom
sudo_user = root
remote_port = 22
host_key_checking = False
timeout = 60
log_path = ./ansible.log
log無(wú)法自動(dòng)分日,得寫(xiě)腳本。
2 主機(jī)信息
編輯hosts:
[mygroup_servers]
192.168.1.10 ansible_user=tom
192.168.1.11 ansible_user=tom
也可以寫(xiě)下密碼庶香,但最好提前免密登陸。
3 配置循環(huán)任務(wù)參數(shù)
比如vim host_vars/192.168.1.10.yml
:
params:
- dir: /abc/abc1
name: tom
- dir: /abc/abc2
name: jerry
4 配置具體操作
block
不支持循環(huán)简识,只能這樣赶掖,vim include_tasks.yml
:
---
- name: print something
debug:
msg: "your self define params: {{ tmp_param }}"
- name: check file
stat:
path: "{{ item.dir }}/myfile.txt"
register: result
- name: if not exists, exit
fail:
msg: "nothing, exit"
when: not result.stat.exists
- name: remove files
ansible.builtin.shell:
cmd: rm {{ item.name }}
chdir: "{{ item.dir }}/filepath/filename"
register: result
ignore_errors: yes
- name: print result
debug:
var: result.stdout_lines
5 入口
vim main.yml
:
---
- name: main task
hosts: mygroup_servers
tasks:
- name: my task name
include_tasks: "include_tasks.yml"
loop: "{{ params }}"
vars:
tmp_param: "{{ tmp_param }}"
6 開(kāi)始運(yùn)行
ansible-playbook -i hosts main.yml -e "tmp_param=foobar" --limit 192.168.1.10
其它臨時(shí)操作:
ansible all -i hosts -m command -a "ls -lrht"
夠用了。