标准playbook(剧本):
--- 标准开头
- name: 剧本描述
hosts:主机对象
remote_user: 执行用户
gather_facts: 是否使用默认主机变量
tasks:剧本任务
- name: 第一个任务描述
模块名:
a: b 模块参数
- name: 第二个任务描述
模块名:
c: d 模块参数
- 任务触发器:
- tasks: 触发器任务
... 标准结尾
----------------------------------------------------------------
任务:创建abc组,将andy用户加入abc组
用ansible命令实现:
ansible 192.168.10.10 -m group -a "name=abc state=present"
ansible 192.168.10.10 -m user -a "name=andy group=abc“
将以上任务,转换成playbook
vi user.yml
- hosts: 192.168.10.10
gather_facts: no
tasks:
- name: create group abc
group:
name: abc
state: present
- name: create andy and join in group abc
user:
name: andy
group: abc
运行剧本:
ansible-playbook user.yml
------------------------------------------------------------------------
思考:如何远程为受管主机安装zabbix-agent,并启动服务,加入开机自启
提示所涉及模块:
copy,yum,service
-------------------------------------------------
ansible all -m copy -a 'src=/root/zabbix.repo dest=/etc/yum.repos.d'
ansible all -m yum -a 'name=zabbix-agent state=installed'
ansible all -m service -a 'name=zabbix-agent state=started enabled=true'
将以上任务转换成剧本:
---
- name: zabbix playbook
hosts: 192.168.10.10
gather_facts: no
remote_user: root
tasks:
- name: copy repo to host
copy:
src: /root/zabbix.repo
dest: /etc/yum.repos.d
- name: install zabbix-agent
yum:
name: zabbix-agent
state: installed
- name: start zabbix-agent and enable
service:
name: zabbix-agent
state: started
enabled: true
...
------------------------------------------------------------
mount 模块:
ansible 192.168.10.10 -m mount -a 'path=/mnt scr=/dev/cdrom state=mounted fstype=iso9660'
思考:为远程主机配置光碟源,写一个playbook
1)准备光碟源文件
vi /root/cdrom.repo
[cdrom]
name=cdrom
baseurl=file:///mnt
enable=1
gpgcheck=0
2)准备ansible命令
ansible 192.168.10.10 -m shell -a 'rm -f /etc/yum.repos.d/*'
ansible 192.168.10.10 -m copy -a 'src=/root/cdrom.repo dest=/etc/yum.repos.d'
ansible 192.168.10.10 -m mount -a 'path=/mnt scr=/dev/cdrom state=mounted fstype=iso9660'
3)转换成剧本
vim mount.yml
- hosts: 192.168.10.10
gather_facts: no
tasks:
- name: clean all repo
shell: rm -f /etc/yum.repos.d/*
- name: copy repo to hosts
copy:
src: /root/cdrom.repo
dest: /etc/yum.repos.d'
- name: mount hosts
mount:
path: /mnt
scr: /dev/cdrom
state: mounted
fstype: iso9660
4)测试:安装光碟自带的软件,比如vim,elinks,httpd