後來發現其實有個內置的變量,直接用就行了:
{{ ansible_eth0[‘ipv4’][‘address’] }}
那下邊的方法可以用來獲取shell的返回結果
shell的返回需要使用register獲取,如下邊代碼的info變量,他獲取的是json格式的key:value。要想獲取ip地址,還需要指定key,也就是{{info.stdout}}。這樣就可以在後邊的task中使用這個變量了。
---
- hosts: aler_nodes
tasks:
- name: get localhost ip
shell: ip addr show eth0|grep 'inet\b'|awk '{print $2}'|awk -F '/' '{print $1}'
register: info
- name: output info
debug: msg="{{info}}"
- name: output localhost ip
debug: msg="{{info.stdout}}"