ansible-playbook实例

一、ansible-playbook简单的应用

1、nginx.yml

---
- hosts: webservers
  vars:
    worker_processes: 4
    num_cpus: 4
    max_open_file: 65535
    root: /data
#  remote_user: root
  tasks:
  - name: ensure apache is at the latest version
    yum: pkg=nginx state=latest
  - name: write the nginx config file
    template: src=/home/zxw/pyauto/第九章/ansible/playbooks/nginx2.conf dest=/etc/nginx/nginx.conf
    notify:
    - restart nginx
  - name: ensure nginx is running
    service: name=nginx state=started
  handlers:
    - include: handlers.yml
  • hosts:指定调用执行的组或者ip。组定义文件:/etc/ansible/hosts
  • vars:定义变量及值,变量会替换配置文件中的变量等
  • tasks:定义任务,按照顺序执行,报错停止。如果需要忽律错误,加语句ignore_errors:True
  • notify检测配置文件是否发生改变,并通知相应的handlers,没有通知的handlers不会执行。notify中的名字,要与handlers下的名字一致

2、执行playbook

ansible-playbook /home/zxw/pyauto/第九章/ansible/playbooks/nginx.yml -f 10

 

二、ansible-playbook角色的应用

1、文件结构

  • sity.yml为调用入口,定义角色及所对应的组
  • hosts定义分组
  • group_vars对应的是用户组变量,all文件代表所有角色的变量, webservers代表webservers组的变量
  • roles下面的角色对应的handles、tasks、templates等应相应角色的任务、模板、变量等

2、hosts

定义用户组

3、sity.yml

---
- name: apply common configuration to all nodes
  hosts: all
  roles:
    - common

- name: configure and deploy the webservers and application code
  hosts: webservers
  roles:
    - web
  • hosts:定义该组是那些用户组,其中,all代表所有的用户组
  • roles:角色。名字对应roles下的文件夹。执行文件夹下的任务、上传模板等

4、group_vars

对应的文件名代表对应的用户组的变量名

 all对应的就是site.yml文件里面对应的all组所对应的角色变量

webserver对应的就是siteyml下的所对应组的变量

5、roles

角色下,角色名对应文件夹下的handles、tasks、templates等对应的就是该角色执行的任务脚本等

handlers下main.yml

- name: restart ntp
  service: name=ntpd state=restarted

tasks下的main.yml

- name: Install ntp 
  yum: name=ntp state=present
#  tags: ntp

- name: Configure ntp file
  template: src=ntp.conf.j2 dest=/etc/ntp.conf
#  tags: ntp
  notify: restart ntp

- name: Start the ntp service
  service: name=ntpd state=started enabled=true
#  tags: ntp

- name: test to see if selinux is running
  command: getenforce
  register: sestatus
  changed_when: false

templates下的ntp.conf.j2

driftfile /var/lib/ntp/drift
restrict 127.0.0.1 
restrict -6 ::1

server {{ ntpserver }}

includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys

注意:变量 {{ ntpserver }}会被group_vars下的变量替换

6、运行

ansible-playbook -i hosts site.yml -f 10

猜你喜欢

转载自www.cnblogs.com/zxw-xxcsl/p/11353192.html