Ansible
playbook 的核心元素:
tasks: 任务
variables: 变量
templates: 模板
handlers: 处理器
roles: 角色
变量:
- facts
- --extra-vars "name=value name=value"
role 定义
Inventory 中的变量:
主机变量
hostname name=value name=value
组变量
- [groupname:vars]
- name=value
- name=value
Inventory 的高级用法:
- Playbook:
- - host:
- vars:
- remote_user:
- tasks:
- -
- -
- -
- variables:
- -
- -
- -
- handlers:
- -
- -
- - host:
- - host:
迭代: 重复同类 task 时使用
调用: item
定义循环列表: with_items
- - apache
- - PHP
- - MySQL-server
注意: with_items 中的列表值也可以使字典, 但引用时要使用 item.KEY
- - {name: apache, conf: conffiles/httpd.conf}
- - {name: PHP, conf: conffiles/PHP.INI}
- - {name: MySQL-server, conf: conffiles/my.cnf}
tags: 在 playbook 可以为某个或某些任务定义一个 "标签", 在执行此 playbkook 时, 通过为 ansible-playbook 命令使用 --tags 选项能实现仅运行指定的 tasks 而非所有的;
- - name: install configuration file for httpd
- template: src=/root/templates/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf
- tags:
- - conf
特殊 tags:always
roles:
(1) 目录名同角色名;
(2) 目录结构有固定格式:
files: 静态文件
templates:Jinjia2 模板文件
tasks: 至少有 main.YAML 文件, 定义各 tasks;
handlers: 至少有 main.YAML 文件, 定义各 handlers;
vars: 至少有一个 main.YAML 文件, 定义变量;
meta: 定义依赖关系等信息
(3)
site.YAML 中定义 playbook, 额外也可以有其他的 YAML 文件;
简单示例 1:
- - hosts:websrvs
- remote_user:root
- tasks:
- - name:create nginx group
- group:name=nginx system=yes gid=208
- - name:create nginx user
- user:name=nginx uid=208 group=nginx system=yes
- - hosts:dbsrvs
- remote_user:root
- tasks:
- - name: copy file to dbsrvs
- copy: src=/etc/inittab dest=/tmp/inittab.ans
简单示例 2:ansible-playbook apache.YAML
- - hosts:websrvs
- remote_user:root
- tasks:
- - name: install httpd package
- yum: nmae=httpd state=latest
- - name: install configuration file for httpd
- copy: src=/root/conf/httpd.conf dest=/etc/httpd/conf/httpd.conf
- - nmae: start httpd service
- service: enabled-true name=httpd state=started
简单示例 3:
- - host: all
- remote_user: root
- vars:
- - username: user10
- tasks:
- - name: create {{ username }} user
- user: name={{ username }}
- when: ansible_fqdn == "zhanx.wang"
来源: http://www.bubuko.com/infodetail-2928604.html