【问题标题】:Ansible multiple facts in Jinja templateJinja 模板中的 Ansible 多个事实
【发布时间】:2019-03-14 14:30:17
【问题描述】:

我想从主机中提取所有接口名称,然后打印该接口的所有信息。

--- # Fetches network interfaces with IPs
- hosts: hta
  gather_facts: yes
  become: yes
  tasks
- debug: msg=" {{ ansible_interfaces|length }}"
  register: num
- name: moving template over to server
  template: src=templates/network.j2 dest=/root/network_info.txt

还有network.j2文件

{% for int in ansible_interfaces %}
Interfaces: Interface-{{ int }}
Data: ansible_{{ int }}
{% endfor %}

到目前为止,我无法打印信息,Ansible 将我的输入 ansible_{{ int }} 作为文字。

【问题讨论】:

    标签: linux ansible jinja2


    【解决方案1】:

    下面的戏

    - command: "ifconfig {{ item }}"
      register: result
      loop: "{{ ansible_interfaces }}"
    - template:
        src: template.j2
        dest: int.txt
      delegate_to: localhost
    

    使用这个模板

    {% for int in result.results %}
    Interfaces: Interface-{{ int.item }}
    Data: {{ int.stdout }}
    {% endfor %}
    

    在 localhost 上创建带有接口数据的文件 int.txt。

    【讨论】:

    • 我收到以下错误“AnsibleError:运行查找插件 'pipe' 时发生未处理的异常。错误是 ,原始消息:lookup_plugin.pipe( ifconfig eth1) 返回 1"}
    • 对不起,我没明白你想说什么。
    • 像所有查找一样,管道将在 ansible 控制器主机上运行,​​因此它永远不会从远程主机获取信息
    【解决方案2】:

    我真正没有得到的是,您正在调用服务器以收集有关其接口的信息并将文件发送回同一台服务器,其中包含您可以随时再次收集的信息。我真的不明白这一点,但我们开始吧。

    应用 KISS 原则:调用ifconfig,它将返回有关所有接口的详细信息并将结果存储在远程主机上的文件中

    playbook.yml

    - name: Simple interface info dump on hosts
      hosts: whatevergroup_you_need
      become: true
      gather_facts: false
      
      tasks:
        - name: dump ifconfig result to /root/network_interface.txt
          shell: ifconfig > /root/network_interfaces.txt
    

    注意事项:

    • become: true 只需要,因为您想将文件写入根目录。如果您在其他任何地方以适当的权限写入文件,ifconfig 本身就可以被任何人执行
    • 由于不需要从主机收集任何其他信息,gather_facts: false 将加快这一简单任务的剧本。
    • shell 模块对于将输出重定向到文件是必需的。如果您担心安全性,您可以改用command 模块(没有文件重定向),使用register 捕获输出并将内容写入下一个任务中的文件
    • 我假设您正在调用 linux 主机,并且 ifconfig 正在输出您需要的信息。如果不是这种情况,您需要重写您的问题,并更准确地了解您想要实现的目标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多