3 ansible-playbook 條件語句-外部變量使用

外部變量指的是從playbook文件以外獲取的數值python

lookups file

file是咱們常用的一種lookups的方式,它的原理就是使用python的codecs.open打開文件而後把結果返回給變量,請看例子redis

[root@LeoDevops playb]# cat lookups_file.yaml 
- hosts: u12
  gather_facts: False
  vars: 
    contents: "{{ lookup('file','/etc/sysconfig/network') }}"
  tasks:
    - name: debug file lookup
      debug: msg="the content is {% for i in contents.split('\n')  %} ,{{ i }} {% endfor  %} "

執行結果以下:數據庫

[root@LeoDevops playb]# ansible-playbook lookups_file.yaml 

PLAY [u12] ************************************************************************************************************************************************************************************

TASK [debug file lookup] **********************************************************************************************************************************************************************
ok: [192.168.93.137] => {
    "msg": "the content is  ,NETWORKING=yes  ,HOSTNAME=LeoDevops  "
}

PLAY RECAP ************************************************************************************************************************************************************************************
192.168.93.137             : ok=1    changed=0    unreachable=0    failed=0

lookup password

對傳入的內容加密處理加密

[root@LeoDevops playb]# cat lookup_passwd.yaml 
- hosts: u12
  gather_facts: False
  vars: 
    contents: "{{ lookup('password','ansible_book')  }}"
  tasks:
    - name: debug lookups
      debug: msg="true contents is {{ contents }}"

lookups pipe

pipe lookups的實現原理很簡單,其實調用的是subprocess.Popen執行的debug

[root@LeoDevops playb]# cat  lookup_pipe.yaml 
- hosts: u12
  gather_facts: False
  vars: 
    contents: "{{ lookup('pipe','date +%F') }}"
  tasks:
    - name: debug lookups
      debug: msg="the content is {% for i in contents.split('\n')  %} -- {{ i }} {% endfor  %}"

lookups redis_kv

redis_kv是從redis數據庫中get數據,依賴於python的redis庫,code

[root@LeoDevops playb]# cat redis_k.yaml
- hosts: u12
  gather_facts: False
  vars:
    contents: "{{ lookup('redis_kv','redis://localhost:6379,resource_usage_rate') }}"
  tasks:
    - name: get_redis_k
      debug: msg="the content is {% for i in contents.split('\n') %} --->{{ i }}{% endfor %}"

lookups template

template 跟file方式有點相似,都是讀取文件,可是template在讀取文件以前須要把jinja模板渲染完成後再讀取,ip

[root@LeoDevops playb]# cat lookup_template.yaml 
- hosts: u12
  gather_facts: True
  vars:
    contents: "{ lookup('template','./hehe.conf'  }"
  tasks:
    - name: debug lookup
      #debug: msg="teht contents is {% for i in contents.split('\n') %} -->{{ i }} {% endfor  %}"     
      debug: msg="teht contents is {{ contents }}" 

[root@LeoDevops playb]# cat hehe.conf 
work_process: {{ ansible_processor_cores  }}
ip_addr: {{ ansible_default_ipv4.address  }}
相關文章
相關標籤/搜索