Kong Service

---
- name: Create Services with Service Paths and Routes in Kong API Gateway
  hosts: localhost
  tasks:

    # Define a list of services, their service paths, and routes
    - name: Define a list of services, service paths, and routes
      set_fact:
        services:
          - { name: service1, service_url: http://example-service1.com:8080/service1, route_name: route1, route_path: /service1 }
          - { name: service2, service_url: http://example-service2.com:8080/service2, route_name: route2, route_path: /service2 }
          - { name: service3, service_url: http://example-service3.com:8080/service3, route_name: route3, route_path: /service3 }

    # Create a Service in Kong for each service defined, including service path
    - name: Create Service in Kong
      uri:
        url: http://localhost:8001/services
        method: POST
        body_format: json
        body:
          name: "{{ item.name }}"
          url: "{{ item.service_url }}"  # Service URL (including the service path)
        status_code: 201
      loop: "{{ services }}"
      register: service_creation

# Create a Route for each Service
    - name: Create Route for the Service
      uri:
        url: http://localhost:8001/routes
        method: POST
        body_format: json
        body:
          service:
            name: "{{ item.name }}"
          name: "{{ item.route_name }}"  # Route name
          paths:
            - "{{ item.route_path }}"  # Route path (external access path)
        status_code: 201
      loop: "{{ services }}"
      when: service_creation is succeeded

    # Optionally verify that services and routes were created
    - name: Verify Service and Route creation
      uri:
        url: http://localhost:8001/services/{{ item.name }}
        method: GET
        status_code: 200
      loop: "{{ services }}"

Leave a comment