playbook

本文介绍如何使用Ansible的Playbook安装Apache和通过Role部署Nginx,包括配置文件模板化、服务开机启动及重启操作等高级特性。

(1)playbook基本用法:安装apache

playbook语法:注意空格,不能是tab键

#vim nginx.yml
- hosts: 192.168.1.31
  tasks:
  - name: Install Apache Package
    yum: name=httpd state=latest

  - name: Copy Apache Conf
    copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/httpd.conf
    notify: Restart Apache Service

  - name: Start Apache
    service: name=httpd state=started enabled=yes

  handlers:
  - name: Restart Apache Service
    service: name=httpd state=restarted
说明:
目标主机是:192.168.1.31
安装httpd,把本地/tmp/httpd.conf文件拷贝到目标主机指定目录
启动httpd和开机启动
handlers:处理方式(重启httpd)
notify动作:当copy文件改变的时候,会触发处理方式handlers(重启httpd)
ansible-playbook  nginx.yml --syntax-check        //检测语法
ansible-playbook  nginx.yml        //执行

(2)role用法

1195071-20180509201235336-167063770.png

1)主配置文件:定义主机的角色是nginx
#vim /root/roles/site.yml
- hosts: 192.168.1.32
  roles:
  - nginx
2)定义nginx的首页文件,这个目录可以放置一些不改变的文件
#vim /root/roles/nginx/files/index.html 
Hello World
3)定义任务文件: yum安装epel源和nginx包,复制配置文件和首页文件(不需要加目录结构),当配置文件修改触发动作,服务启动和开机启动
# cat /root/roles/nginx/tasks/main.yml 
- name: Install Nginx Package
  yum: name={{ item }} state=latest
  with_items:
  - epel-release
  - nginx 
- name: Copy nginx.conf Template
  template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
  notify: restart nginx
- name: Copy index.html
  copy: src=index.html dest=/usr/share/nginx/html/index.html
- name: make sure nginx service running 
  service: name=nginx state=started enabled=yes
4)定义默认配置文件:注意这里配置文件使用了变量,注意这里其中一个变量 ansible_processor_cores 是使用setup模块收集自动引用的
# grep "{{" /root/roles/nginx/templates/nginx.conf.j2 
worker_processes {{ ansible_processor_cores }};
    worker_connections {{ worker_connections }};
5)定义变量:引用配置文件中的变量
# cat nginx/vars/main.yml 
worker_connections: 10240
6)定义动作:当模板中的配置文件变动会触发重启nginx动作
# cat /root/roles/nginx/handlers/main.yml 
- name: restart nginx
  service: name=nginx state=restarted
ansible-playbook  site.yml --syntax-check        //检测语法
ansible-playbook  site.yml        //执行

转载于:https://www.cnblogs.com/lovelinux199075/p/9014709.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值