首页 » 翻译 » Ansible 入门 » 正文

ansible 入门教程07 自带的系统变量facts

除了我们自己定义的变量外,系统的一些变量如:hostname,ip等,我们是不需要定义的,可以通过facts直接获取

我们可以通过
ansible localhost -m setup

查看本机有哪些预设变量可以让我们使用

“sda”: {
“holders”: [],
“host”: “SCSI storage controller: LSI Logic / Symbios Logic 53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI (rev 01)”,
“model”: “VMware Virtual S”,
“partitions”: {
“sda1″: {
“sectors”: “39843840”,
“sectorsize”: 512,
“size”: “19.00 GB”,
“start”: “2048”
},
“sda2″: {
“sectors”: “2”,
“sectorsize”: 512,
“size”: “1.00 KB”,
“start”: “39847934”
},
“sda5″: {
“sectors”: “2093056”,
“sectorsize”: 512,
“size”: “1022.00 MB”,
“start”: “39847936”
}
},

….

我们可以通过{{ ansible_devices.sda.model }}来调用某一特殊值:VMware Virtual S

{{ ansible_hostname }} 主机名称

当然,也可以手动关闭facts

– hosts: whatever
gather_facts: no

也可以自定义facts,在目标主机上,
/etc/ansible/facts.d 目录下,任何以.fact结尾的的文件内容,都可以通过local facts的形式在服务器端获取

例如:

/etc/ansible/facts.d/preferences.fact

[general]

asdf=1

bar=2

然后获取他们的话通过:

ansible <hostname> -m setup -a “filter=ansible_local”

就会得到如下结果:

“ansible_local”: {
“preferences”: {
“general”: {
“asdf” : “1”,
“bar” : “2”
}
}
}

然后如果在模板中直接使用的话:

{{ ansible_local.preferences.general.asdf }}

这里有一个自动拷贝相关文件到目标主机的例子

– hosts: webservers
tasks:
– name: create directory for ansible custom facts
file: state=directory recurse=yes path=/etc/ansible/facts.d
– name: install custom impi fact
copy: src=ipmi.fact dest=/etc/ansible/facts.d
– name: re-read facts after adding custom fact
setup: filter=ansible_local
创建目录,拷贝文件,重新读取facts变量

另:一个目标主机是可以调取另外一台主机的facts变量的,例如:

{{ hostvars[‘asdf.example.com’][‘ansible_os_family’] }}

当然,如果想成功调取数值需要额外配置,这个暂留
欢迎转载,转载请注明出处:http://www.503error.com/

Zhiming Zhang

Senior devops at Appannie
一个奔跑在运维路上的胖子
Zhiming Zhang

Latest posts by Zhiming Zhang (see all)