Generating YAML config files via Jinja2 & Ansible vars

Hello there,

I’m trying to make a role that can dynamically generate the YAML config files for my app (The app is Data Dog’s agent). Ex: I want my Jinja2 template to render valid YAML, the contents of which are coming from Ansible vars, which themselves are defined via YAML. This is equivalent to the pattern that https://github.com/jdauphant/ansible-role-nginx uses for translating Ansible vars into nginx config files.

Is there an easy way to do this? Am I thinking about this all wrong?

Sample YAML config file for Datadog that I would like to have dynamically generated from equivalent Ansible vars:


init_config:

instances:

For every instance, you have an nginx_status_url and (optionally)

a list of tags.

Thanks,
Dan

I just did something like that recently for data-dog. My role adds data-dog agent config entries.

Example usage looks like:

roles:

  • role: datadog

  • role: datadog_monitor
    monitors:
    mongodb:
    instances:

  • server: mongodb://localhost:27017/admin
    tags:

  • mongo_tag_1

  • mongo_tag_2

  • role: datadog_monitor
    monitors:
    docker:
    init_config:
    docker_root: /
    socket_timeout: 5
    instances:

  • url: unix://var/run/docker.sock
    include:

  • “docker_image:ubuntu”

  • “docker_image:ngnx”
    exclude:

  • “.*”
    new_tag_names: true
    tag_by_command: false
    collect_event: true
    collect_container_size: false
    collect_images_stats: false
    collect_all_metrics: false
    tags:

  • docker_tag_1

  • docker_tag_2

The roles tasks/main.yml selects a template based on the ‘monitors’ keys:

  • fail: msg=“Datadog must be configured. Are you missing role datadog?”
    when: datadog_etc_confd_dir is not defined

  • name: Configure datadog {{ item.monitor }} monitor
    template:
    src: “conf.d/{{item.key}}.yml.j2”
    dest: “{{datadog_etc_confd_dir}}/{{item.key}}.yaml”
    owner: “{{datadog_user}}”
    notify: restart datadog
    with_dict: monitors

These two templates:

mongodb.yml.j2

{{ ansible_managed }}

init_config:
{{ item.value | to_nice_yaml }}

docker.yml.j2

{{ ansible_managed }}

{% if item.value.init_config is not defined %}
init_config:
{% endif %}
{{ item.value | to_nice_yaml }}

My main goal was to not create complex templates that require the definition of every data-dog variable. As I have only used this a very little so far, ymmv. At some point I will create a galaxy submission.