## playbook中變量將優先級
* playbook的yml文件中使用var定義
* 通過--extra-vars命令行給變量賦值
* 在vars/vars_files文件中定義變量
* 注冊變量
## 注冊變量 [debug][1] [register][2]
debug的具體用法參見debug模塊
~~~
- name: show return value of cmd
hosts: test
tasks:
- name: capture output of cmd
command: id -un
register: login
- debug: var=login # 此處debug中賦值,可以查看到詳細信息
- debug: msg="{{ login.stdout }}"
~~~
## fact
~~~
# 不收集客戶端狀態信息
gather_facts: false
~~~
### 查看與某臺服務器關聯的所有fact
Ansible使用setup模塊來收集fact,在playbook可以直接使用setup收集的變量,也可以在命令行手動調用。
~~~
ansible test -m setup
ansible test -m setup -a "filter=ansible_eth*"
~~~
~~~
- name: show return value of cmd
hosts: localhost
- debug:
msg: "{{ hostvars[inventory_hostname] }}"
~~~
### 本地fact
可以在/etc/ansible/facts.d目錄中定義本地fact文件
#### 定義
/etc/ansible/facts.d/example.fact
~~~
[book]
title=Ansible Up and Running
author=Lorin
~~~
#### 調用
測試未通過
~~~
- debug: var=ansible_local
- debug: msg="The book is {{ ansible_local.example.book.title }}"
~~~
### [set_fact][3]定義新變量
~~~
- name: show return value of cmd
hosts: test
tasks:
- name: capture output of cmd
command: id -un
register: login
- set_fact: new_var={{ login.stdout }}
- debug: var=new_var
~~~
## 內置變量
在playbook中永遠可以訪問的變量
~~~
inventory_hostname # 被ansible所識別的當前主機的名稱,如果定義過別名,則是別名
hostvars # 字典, key為主機名,value為對應主機的參數,如 {{ hostvars['db.example.com'].ansible_eth1.ipv4.address }}
group_names # 當前主機所屬群列表
groups # 字典, key為群組名,value為群成員組成的主機名列表,包括all和ungrouped分組,如{"all": [...], "web": [...], "ungrouped": [...]}
play_hosts # 當前play涉及的主機的invetory主機名
ansible_version # ansible的版本信息
~~~
### 示例
~~~
- debug: msg={{ hostvars['testserver'].ansible_ens33.ipv4.address }}
~~~
使用在templates中
~~~
{% for host in groups.web %}
server {{ host.inventory_hostname }} {{ host.ansible_ens33.ipv4.address }}:80
{% endfor %}
~~~
## 在命令行設置變量
在命令行中使用`-e key=value`。
[1]:http://docs.ansible.com/ansible/latest/debug_module.html
[3]:http://docs.ansible.com/ansible/latest/set_fact_module.html
- 目錄
- ansible基礎
- ansible簡介
- ansible安裝和測試
- ansible配置文件
- 常用命令
- yaml在ansible中的用法
- inventory
- 變量與facts
- when語句
- handler模塊
- 大雜燴
- ansible模塊
- assert 模塊
- copy模塊
- cron模塊
- debug模塊
- django_manage模塊
- file模塊
- filesystem模塊
- git模塊
- hostname模塊
- lineinfile模塊
- mount模塊
- mysql_user模塊
- mysql_db模塊
- pip模塊
- selinux
- setup模塊
- shell 和 command 模塊
- stat模塊
- supervisorctl
- systemd
- timezone
- unarchive模塊
- user模塊
- wait_for
- yum和service模塊
- 其他模塊或者方法
- setup模塊
- url模塊
- slack 模塊
- pause 模塊
- 其他
- 報錯處理
- playbooks
- 復雜的playbook
- 循環
- roles
- YAML
- jinja2