以下均学习于朱双印先生博客
ansible playbook初步
工作场景,三条命令组成,下载nginx,并运行
[root@self1-centos7-2 20:50:12 ~]#ansible self1-1 -m yum_repository -a 'name=aliepel description="aliyum" file=aliyum baseurl=https://mirrors.aliyun.com/epel/$releasever\Server/$basearch/'
[root@self1-centos7-2 20:54:15 ~]#ansible self1-1 -m yum -a 'name=nginx disable_gpg_check=yes enablerepo=aliepel'
[root@self1-centos7-2 19:05:45 ~]#ansible self1-1 -m service -a "name=nginx state=started"
编排成剧本playbook
简单的示例:
ansible self1-1 -m ping
ansible self1-1 -m file -a 'path=/test/filetest state=directory'
探测主机是否开机,开机就创建一个目录
编写相应的playbook,test.yaml或test.yml文件
---
- hosts: self1-1
remote_user: root
task:
- name: Ping the host
ping:
- name: make directory test
file:
path: /test/filetest
state: directory
—表示文档开始
- 表示一个块序列的节点
: 之间是一个键值对,冒号后必须有一个空格
ansible-playbook test.yml
…
playbook执行时都会先执行一个收集基础信息的默认任务’Gathering Facts’
playbook执行完毕后,’PLAY RECAP’中对所有目标主机执行情况进行回顾
上面只有一个play,下面的示例有多个play
---
- hosts: self1-1,
remote_user: root
task:
- name: Ping the host
ping:
- name: make directory test
file:
path: /test/filetest
state: directory
- hosts:
self1-1
self2-1
remote_user: root
task:
- name: ping the host
ping:
- name: touch test.txt
file:
path: /test
state: touch
mode: 0700
- hosts: web
remote_user: root
task:
- name: ping the host
ping:
- name: create user
user:
name: nginx
对编写好的剧本进行语法检查:
ansible-playbook --syntax-check ~/test.yml
模拟运行
ansible-playbook --check test.yml
回顾执行剧本
ansible-playbook test.yml