1、register结果返回到变量中
- name: debug test one host
hosts: 200.200.6.53
tasks:
- debug:
msg: "System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}"
- debug:
msg: "System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }}"
when: ansible_default_ipv4.gateway is defined
- shell: /usr/bin/uptime
register: result
- debug:
var: result
verbosity: 4
- name: Display all variables/facts known for a host
debug:
var: hostvars[inventory_hostname]
verbosity: 2
2、要从系统变量中获取http_proxy的信息,使用lookup:
--- #1
- name: Downloads a file using the same proxy as the controlling machine
hosts: all
tasks:
- name: Download file
get_url: dest=/var/tmp/file.tar.gz url=http://server/file.tar.gz
environment:
http_proxy: "{{ lookup('env', 'http_proxy') }}"
3、使用外部变量:ansible-playbook release.yml --extra-vars"hosts=vipers user=starbuck"
---
-hosts: '{{ hosts }}'
remote_user: '{{ user }}'
4、变量可以在模板、playbook等所有环境下使用
-hosts: webservers
vars:
http_port: 80
5、远程节点系统上/etc/ansible/facts.d目录,这个目录下的以.fact为后缀的文件,里面的内容可以是JSON格式,或者ini格式书写;或者是一个可以返回json格式数据的可执行文件,都可以用来提供本地facts信息:
在远程节点创建一个/etc/ansible/facts.d/preferences.fact的文件,内容如下:
[general]
asdf=1
bar=2
在控制节点获取自定义的信息:
[root@web1 ~]# ansible webservers -m setup -a "filter=ansible_local"
192.168.1.65| success >> {
"ansible_facts": {
"ansible_local": {
"preferences": {
"general": {
"asdf": "1",
"bar": "2"
}
}
}
},
"changed": false
}
filter来指定一个过滤条件。
可以在playbooks或者模板中这样使用获取到的信息:
1{{ ansible_local.preferences.general.asdf }}
6、将变量定义到特定的文件中,在playbooks中使用var_files导入文件即可:
---
-hosts: all
remote_user: root
vars:
favcolor: blue
vars_files:
-/vars/external_vars.yml
tasks:
-name: this isjust a placeholder
command: /bin/echo foo
变量文件也是YMAL格式:
# in the above example, this would be vars/external_vars.yml
somevar: somevalue
password: magic