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无法自动分日,得写脚本。
2 主机信息
编辑hosts:
[mygroup_servers]
192.168.1.10 ansible_user=tom
192.168.1.11 ansible_user=tom
也可以写下密码,但最好提前免密登陆。
3 配置循环任务参数
比如vim host_vars/192.168.1.10.yml
:
params:
- dir: /abc/abc1
name: tom
- dir: /abc/abc2
name: jerry
4 配置具体操作
block
不支持循环,只能这样,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 开始运行
ansible-playbook -i hosts main.yml -e "tmp_param=foobar" --limit 192.168.1.10
其它临时操作:
ansible all -i hosts -m command -a "ls -lrht"
够用了。