How to Render Network Configuration with NetBox and Ansible

How to Render Network Configuration with NetBox and Ansible

Ansible + NetBox Tip: Rather than using Ansible to render your Jinja templates, have NetBox render them directly using its Config Template feature!

Here's an example of how to use Ansible to trigger NetBox to render the config and then save the configuration locally 👇

---
- name: Render Jinja template within NetBox and return the result.
  gather_facts: false
  hosts: all

  vars:
    - NETBOX_ENDPOINT: "{{ lookup('env', 'NETBOX_ENDPOINT') }}"
    - NETBOX_TOKEN: "{{ lookup('env', 'NETBOX_TOKEN') }}"
    - OUTPUT_DIR: "output"

  pre_tasks:
    - name: Set local connection for all hosts
      ansible.builtin.set_fact:
        ansible_connection: local
      tags:
        - always

  tasks:
    - name: Get device ID
      ansible.builtin.uri:
        url: "{{ NETBOX_ENDPOINT }}/graphql/"
        method: POST
        headers:
          Authorization: "Token {{ NETBOX_TOKEN}}"
          Content-Type: "application/json"
          Accept: "application/json"
        body:
          query: |
            {
              device_list(name: "{{ inventory_hostname }}") {
                name
                id
              }
            }
        body_format: json
        return_content: yes
        status_code: 200
      delegate_to: localhost
      register: response

    - name: Set fact
      set_fact:
        device_id: "{{ response.json.data.device_list[0].id }}"
      delegate_to: localhost

    - name: Trigger NetBox to return rendered configuration
      ansible.builtin.uri:
        url: "https://packetcoders.cloud.netboxapp.com/api/dcim/devices/{{ device_id }}/render-config/"
        method: POST
        headers:
          Authorization: "Token {{ NETBOX_TOKEN}}"
          Content-Type: "application/json"
          Accept: "text/plain" 
        body:
          {
            "format" : "txt"
          }
        body_format: json
        return_content: yes
        status_code: 200
      delegate_to: localhost
      register: response
      tags:
        - build

    - name: Save rendered config to file
      ansible.builtin.copy:
        content: "{{ response.content }}"
        dest: "{{ OUTPUT_DIR }}/{{ inventory_hostname }}.txt"
      delegate_to: localhost
      tags:
        - build

Subscribe to our newsletter to keep updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox.
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!