繁体   English   中英

使用 Ansible 从 Jinja2 模板向本地文件添加行

[英]Add lines to a local file from a Jinja2 Template with Ansible

我是 ansible 的新手,遇到了这个任务的问题。 我想从各种主机获取一些数据。 想法是,使用 jinja2 模板,从主机获取数据并将此数据添加到 Ansible 机器上的本地文件中。

如何在本地机器上的一个文件中获取所有数据? 我尝试这样做的方式给我带来了来自一台主机的结果。 感谢您的帮助!

---
- name: "Server Report"
  hosts: all
  tasks:
    - name: "check packages"
      package_facts:
        manager: auto
    - name: "get PHP info"
      shell: "php -v | grep -E ^PHP | awk '{print $2}'"
      register: php_version
      when: "'php-common' in ansible_facts.packages"

    - name: "get MySQL info"
      shell: "mysql -V | awk '{print $5}' | sed 's/,//g'"
      register: mysql_version
      when: "'mysql-common' in ansible_facts.packages"

    - name: "Use Template to create File"
      template:
        src: vrsn.j2
        dest: /opt/data.txt
      delegate_to: localhost

这是 Jinjer2 代码:

{% if ansible_facts['hostname'] is defined %}{{ ansible_facts['hostname'] }},{% else %}NoINstalled,{% endif %}
{% if ansible_facts['distribution'] is defined %}{{ ansible_facts['distribution'] }} {{ ansible_facts['distribution_version'] }},{% else %}NotInstalled,{% endif %}
{% if php_version.stdout is defined %}{{ php_version.stdout }},{% else %}NotInstalled,{% endif %}
{% if mysql_version.stdout is defined %}{{ mysql_version.stdout }},{% else %}NotInstalled,{% endif %}
{% if ansible_facts.packages['apache2'][0].version is defined %}
apache2-version {{ ansible_facts.packages['apache2'][0].version }},
{% elif ansible_facts.packages['apache'][0].version is defined %}
apache-version {{ ansible_facts.packages['apache'][0].version }},
{% elif ansible_facts.packages['nginx-common'][0].version is defined %}
nginx-version {{ ansible_facts.packages['nginx-common'][0].version }},
{% else %}NotInstalled{% endif %}

我不确定我是否完全理解您的 output 格式,但以下示例应该为您提供有关 go 的线索: vrsn.j2

{% for h in groups['all'] %}
Inventory host: {{ h }}
hostname: {{ hostvars[h].ansible_hostname | default('N/A') }}
distribution: {{ hostvars[h].ansible_distribution | default('N/A') }}
php: {{ hostvars[h].php_version.stdout | default('N/A') }}
# add more here now you got the concept

---
{% endfor %}

你应该在你的剧本中这样称呼你的模板:

    - name: "Dump all host info to local machine"
      template:
        src: vrsn.j2
        dest: /opt/data.txt
      delegate_to: localhost
      run_once: true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM