Linux
Ansible with_dicts group_vars 劇本
我的要求是在文件中獲取以下輸出
- targets: [ 'host1:port1', 'host2:port1' , 'host3:port1' ] job : hostgroup1 - targets: [ 'host1:port2', 'host2:port2' , 'host3:port3' ] job : hostgroup2
我有如下輸入文件,它應該從變數或組變數中獲取數據。在 Hostgroup1 下我可能有 n 台主機,在 Hostgroup2 下我可能有 n 台主機
Hostgroup1 : host1,host2,host3....n Hostgroup2 : host1,host2,host3....n
我很困惑如何創建 jinja 模板和任務來獲得這個輸出
好吧,我在劇本的“vars”部分定義了類似你的數據的東西。你可以把它放在一個 vars 文件中,或者你可以在你的 hostvars/groupvars 或其他東西中定義這些 vars。這可能不是您想要的,但您可以根據自己的需要進行調整。
- hosts: localhost gather_facts: no vars: data: - { "name": "hostgroup1", "port": 80, "hosts": ["host1", "host2", "host3"] } - { "name": "hostgroup2", "port": 443, "hosts": ["host5", "host6", "host7"] } tasks: - debug: msg: | {% for item in data %} - job: {{ item.name }} targets: [ {%- for host in item.hosts -%} "{{ host }}:{{ item.port }}", {%- endfor -%}] {% endfor %}
輸出
# ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook 20190404_sf_961529.yml PLAY [localhost] ************************************************************************************ TASK [debug] **************************************************************************************** ok: [localhost] => {} MSG: - job: hostgroup1 targets: ["host1:80","host2:80","host3:80",] - job: hostgroup2 targets: ["host5:443","host6:443","host7:443",] PLAY RECAP ****************************************************************************************** localhost : ok=1 changed=0 unreachable=0 failed=0
對於文件的輸出,您可以使用這樣的任務。
- copy: dest: outputpath content: | {% for item in data %} - job: {{ item.name }} targets: [ {%- for host in item.hosts -%} "{{ host }}:{{ item.port }}", {%- endfor -%}] {% endfor %}