39. ansible的剧本模式¶
1. playbook介绍¶
#1. 使用yaml格式编写,
#2. 包含2部分内容:hosts和tasks
2. hosts部分¶
#1. 前提:被管理的IP都在hosts配置文件中: /etc/ansible/hosts
#2. 使用方法:
- hosts: 192.168.178.123 #1.直接跟IP:
- hosts: chupenggroup #2.跟主机组:
- hosts: 192.168.178.121,192.168.178.122 #3.跟多个IP:
- hosts: all #4.跟all:
3. tasks部分¶
1. 变量形式¶
tasks:
-name: make sure apache is running # 说明内容
service: name=httpd state=running # 模块及其参数
-nam: copy file # 说明内容
copy:src=/etc/ansible/hosts dest=/etc/ansible/hosts owner=cp1 group=cp1 mode=0644 # 使用的模块及其参数
2. 字典形式¶
# 当传入参数列表过长时使用
tasks:
- name: copy file to client ...
copy:
src: /etc/ansible/hosts
dest: /etc/ansible/hosts
owner: root
group: root
mode: 0644
4. 剧本命令¶
1. 查看帮助¶
ansible-playbook -h
2. 查看剧本执行的详细输出¶
ansible-playbook nginx.yaml --verbose
3. 查看剧本影响的主机¶
ansible-playbook nginx.yaml --list-hosts
4. 加载指定的主机清单文件执行剧本¶
ansible-playbook nginx.yaml -l /etc/my_ansible/hosts
5. 执行剧本并检查语法¶
ansible-playbook nginx.yaml --syntax-check
6. 调试剧本,不执行¶
ansible-playbook nginx.yaml -C
5. 案例1:编写批量安装nginx的剧本¶
1. 创建yaml文件目录¶
#1.
mkdir /myyaml
2. 编写yaml剧本¶
#2.
vim /myyaml/install_nginx.yaml
- hosts: all
tasks:
- name: install nginx
yum: name=nginx state=present
- name: copy nginx.conf
copy: src=./nginx.conf dest=/etc/nginx/conf/nginx.conf mode=0644
3. 检查剧本语法¶
ansible-playbook /myyaml/install_nginx.yaml --syntax-check
4. 调试剧本¶
ansible-playbook /myyaml/install_nginx.yaml -C
5. 执行剧本¶
ansible-playbook /myyaml/install_nginx.yaml
6. 查看安装结果¶
ansible chupenggroup -m shell -a "rpm -qa nginx"
6. 案例2:批量部署rsync服务¶
1. 编写剧本文件¶
vim /myyaml/install_rsync.yaml
- hosts: all
tasks:
- name: step01,install rsync
yum: name=rsync state=installed
- name: step02,edit rsync conf file
copy: src=/etc/ansible/rsync_conf/rsyncd.conf dest=/etc/rsync/conf/
- name: step03,create user rsync
user: name=rsync state=present createhome=no shell=/sbin/nologin
- name: step04,create user auth file
copy: src=/etc/ansible/rsync_conf/rsync.password dest=/etc/rsync/conf/ mode=600
- name: step05,create backup dir
file: dest=/data_backup/ state=directory owner=rsync group=rsync
- name: step06,run rsync server
shell: rsync --daemon creates=/var/run/rsync.pid
2. 执行剧本¶
ansible-playbook install_rsync.yaml
最后更新:
2022-02-18 11:26:47