Deploy routes and plugins in Kong Gateway

Here’s a minimal yet flexible Ansible playbook to deploy routes in Kong Gateway using the uri module to interact with the Admin API. This example assumes:

  • Kong Admin API is accessible (e.g. http://localhost:8001).
  • A service is already defined (or you can create one using Ansible).
  • You’re deploying a route for an existing service.

✅ Example Directory Layout

kong_routes/
├── playbook.yml
└── vars/
    └── routes.yml


📄 vars/routes.yml

kong_admin_url: "http://localhost:8001"

kong_routes:
  - name: route1
    service: example-service
    paths: ["/example"]
    methods: ["GET"]
    strip_path: true


📄 playbook.yml

- name: Deploy Routes to Kong
  hosts: localhost
  connection: local
  vars_files:
    - vars/routes.yml
  tasks:
    - name: Ensure route exists in Kong
      uri:
        url: "{{ kong_admin_url }}/routes"
        method: POST
        body_format: json
        headers:
          Content-Type: "application/json"
        body: >-
          {
            "name": "{{ item.name }}",
            "paths": {{ item.paths | to_json }},
            "methods": {{ item.methods | to_json }},
            "strip_path": {{ item.strip_path }},
            "service": { "name": "{{ item.service }}" }
          }
        status_code: 201
      loop: "{{ kong_routes }}"
      ignore_errors: true  # optional: prevents failure if route exists


✅ Optional: Create Service First

Add this before the route task if needed:

    - name: Ensure service exists
      uri:
        url: "{{ kong_admin_url }}/services"
        method: POST
        body_format: json
        headers:
          Content-Type: "application/json"
        body: >-
          {
            "name": "{{ item.service }}",
            "url": "http://mockbin.org"  # change to your backend URL
          }
        status_code: 201
      loop: "{{ kong_routes }}"
      ignore_errors: true


Would you like this to support idempotency (check if the route already exists and update it), or include support for Kong Konnect or authentication headers (e.g. RBAC tokens)?

headers:
Content-Type: “application/json”
Authorization: “Bearer {{ kong_admin_token }}”

Leave a comment