1、hosts 文件中定义变量

hosts 文件中定义变量,参考:Ansible 主机列表(Inventory)

2、group_vars 和 host_vars

group_varshost_vars 目录下变量文件使用,参考:Ansible 主机列表(Inventory)

3、vars_files

vars_files 指令导入变量文件,参考:Ansible 条件判断

4、setup 模块:facts

setup 模块收集主机信息,参考:Ansible 条件判断

5、register 注册变量

register 指令注册的变量,参考:Ansible 条件判断Ansible 循环语句(Loops)

6、命令行传递变量

ansible-playbook release.yml --extra-vars "version=1.23.45 other_variable=foo"

也可以向 playbooks 传递主机组和连接的远程用户

ansible-playbook release.yml --extra-vars "hosts=vipers user=starbuck"
---
- hosts: '{{ hosts }}'
remote_user: '{{ user }}'

ansible1.2 中,可以以 JSON 格式传递变量

--extra-vars '{"pacman":"mrs","ghosts":["inky","pinky","clyde","sue"]}'

ansible1.3 中可以使用 JSON 文件传递变量

--extra-vars "@some_file.json"

上面的方式也可以传递一个 YAML 格式的变量文件

Ansible技术问答:http://linux.xyz/topic/Ansible

7、变量过滤处理

jinja2 过滤器和 ansible 独有的过滤器可以对变量进行某些处理,请参考 jinjia2 模板设计说明文档Ansible 条件判断

8、复杂变量定义

---
## file:roles/xxx/vars/main.yml
users:
 - name: alice
 authorized:
 - /tmp/alice/onekey.pub
 - /tmp/alice/twokey.pub
 mysql:
 password: mysql-password
 hosts:
 - "%"
 - "127.0.0.1"
 - "::1"
 - "localhost"
 privs:
 - "*.*:SELECT"
 - "DB1.*:ALL"
 - name: bob
 authorized:
 - /tmp/bob/id_rsa.pub
 mysql:
 password: other-mysql-password
 hosts:
 - "db1"
 privs:
 - "*.*:SELECT"
 - "DB2.*:ALL" 

类似于 python 的变量定义:

users=[
 {'name':'alice',
'authorized':['/tmp/alice/onekey.pub','/tmp/alice/twokey.pub'],
'mysql':{'password':'mysql-password',
'hosts':["%","127.0.0.1","::1","localhost"]},
'privs':["*.*:SELECT","DB1.*:ALL"]
},

{'name':' bob',
'authorized':['/tmp/bob/id_rsa.pub'],
'mysql':{'password':'other-mysql-password',
'hosts':["db1",]},
'privs':["*.*:SELECT","DB2.*:ALL"]
}
]