Ansible with_dicts group_vars 剧本

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 模板和任务来获得这个输出

答案1

好吧,我在剧本的“vars”部分中定义了类似您的数据的内容。您可以将其放在 vars 文件中,或者您可以在 hostvars/groupvars 等文件中定义这些 var。这可能不是您想要的,但您可以根据需要进行调整。

- 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 %}

相关内容