YAML
YAML简介
YAML是一个可读性高,并用来表达资料序列的格式。YAML参考了其它多种语言,包括:XML、C语言、Python、Perl以及电子邮件格式RFC2822等
它是一种直观的能够被电脑识别的数据序列化格式,是一个可读性高并且容易被人类阅读,容易和脚本语言交互,用来表达资料序列的编程语言
YAML特性
YAML的可读性好
YAML和脚本语言的交互性好
YAML使用实现语言的数据类型
YAML有一个一致的信息模型
YAML易于实现
YAML可以基于流来处理
YAML表达能力强、扩展性好
YAML语法
YAML的语法与其他高级语言类似,并且可以简单表达清单、散列表、标量等数据结构,其结构通过空格来展示,序列里的每一项开头用"-"来代表,Map里的键值对应":"分隔
name: chen qian age: 18 gender: Male brother: name: LAG age: 88 gender: Male parent: - name: Father age: xx gender: Male - name: Mother age: xx gender: Female
文件命名
xxx.yml
官方文档
http://www.yaml.org
http://docs.ansible.com
Ansible基础元素
变量
变量命名
和其它高级语言命名相同
facts 由正在通信的远程目标主机发回的信息,这些信息被保存在ansible变量中,可直接引用
facts变量使用
- hosts: webserver remote_user: root tasks: - name: copy file copy: content="{{ ansible_all_ipv4_addresses }}" dest=/tmp/vars.ans
register
把任务的输出定义为变量,然后用于其它任务
tasks: - name: register - shell: /usr/bin/foo register: foo_result ignore_error: True
通过命令行传递的变量
在运行playbook的时候也可以出传递一些变量供playbook使用
ansible-playbook test.yml --extra-vars "hosts=www domain=example.com"
通过roles传递的变量
当给一个主机应用角色的时候可以传递变量,然后在角色内使用这些变量
- hosts: webserver roles: - common - { role: foo_app_instence, dir: '/web/htdocs/a.com', port: 8000 }
vars变量
vars: - command=/sbin/shutdown tasks: - name: "shutdown Debian flavored systems" command: {{ command }} -h now when ansible_os_family == "Debian"
Inventory
ansible的主要功能在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory file中将其分组命名
默认file文件路径 /etc/ansible/hosts
inventory file可以有多个,且也可以通过Dynamic Inventory来动态生成
inventory文件格式
遵循INI文件风格,中括号中的字符为组名,可以将同一个主机同时归并到多个不同的组中,如果目标主机适用非默认的SSH端口,还可以追加[:PORT]标明
[webserver]
192.168.180.130:54321
192.168.180.131:54321
[dbserver]
192.168.180.132:54321
如果主机名称遵循相似的命名模式,还可以适用列表的方式标识各主机
[appserver]
www[01:50].example.com
[databases]
db-[a:f].exmaple.com
inventory参数
ansible_ssh_host ansible_ssh_port ansible_ssh_user ansible_ssh_pass ansible_sudo_pass ansible_connection ansible_ssh_private_key_file ansible_shell_type ansible_python_interpreter ansible\_\*\_interpreter 使用 [webserver] www.example.com ansible_ssh_user=root ansible_ssh_pass=123546