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.yml文件,定义各tasks;
handlers:至少有main.yml文件,定义各handlers;
vars:至少有一个main.yml文件,定义变量;
meta:定义依赖关系等信息
(3)
site.yml中定义playbook,额外也可以有其他的yml文件;
简单示例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.yml
- 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://blog.51cto.com/zhanx/2344689
时间: 2024-11-05 22:54:35