ansible可使用template,設定變量,根據不同的環境,批量更新配置。
比如ip位址,每個部署環境可能都不同,不能寫成固定值,
可使用如下方式,為每個機器自動更新配置,比如某個config.j2檔案:
ipaddress={{ template_ip }}
通常,變量“template_ip”在執行ansible之前,就預先知道的,一般放在group_vars檔案夾裡面,
但是,對于某些值,是預先不知道的,或者是每台機器都不一樣的,不能通過一個單一變量事先設定好,
比如某個配置檔案要求寫網卡的MAC位址,
第1,每個機器的每個網卡都不一樣;
第2,ip位址可以人為配置設定,MAC位址取決于硬體,最好不要寫死;
可以這樣:
---
- hosts: sled-mcn0
gather_facts: no
tasks:
- name: "test shell command result registe to be var"
shell: ifconfig eth0 | grep ether | awk {'print $2'}
register: macaddr_res
- name: "show the mac addr"
debug: var=macaddr_res.stdout
- name: "template the config file"
template: src=config.j2 dest=/etc/config.ini
在每台機器上執行一條shell指令,将結果取回來,作為變量macaddr_res,
再使用template更新本地config.j2的值,與mac位址相關的定義:
macaddr={{ macaddr_res.stdout }}
最後将配置檔案更新到遠端部署機上的/etc/config.ini
這隻是一個最簡單的"hello world"例子,
其實上面的shell指令中的"eth0"最好是通過group_vars變量設定,而不是固定寫死為"eth0".