How to simplify a repetitive pattern?

I have several services on different machines that are available though HTTP and I wanted to merge them under a consistent URL: https://syncthing.XXX/<name of service>. To do so, I created a config file with the following content:

http:
  routers:
    syncthing-srv:
      rule: Host(`syncthing.XXX`) && Path(`/srv`)
      service: syncthing-srv
  services:
    syncthing-srv:
      loadBalancer:
        servers:
          - url: http://100.79.184.103:8384

This is a repetitive pattern for all my services where only the service name and the target URL will be different.

Is there a way to template such a config file by iterating a list of tuples (name and URL) and building the configuration accordingly?

I imagine something like (in pseudocode)

for service in [('srv', 'http://klsjdlskj'), ('hello', 'http://uiyeiuryieu')):
'''
http:
  routers:
    syncthing-{{service[0]}}:
      rule: Host(`syncthing.XXX`) && Path(`/{{service[0]}}`)
      service: syncthing-{{service[0]}}
  services:
    syncthing-{{service[0]}}:
      loadBalancer:
        servers:
          - url: {{service[1]}}
'''

I don’t think there is native/integrated templating like that. Maybe check jinja2 or ansible for pre-processing.

Note 1: you probably want to use PathPrefix(), not Path()

Note 2: most webapps don’t like to be placed under a path, they usually prefer /, unless some kind of "base path" can be set. Use sub-domains instead.

1 Like

I don’t think there is native/integrated templating like that. Maybe check jinja2 or ansible for pre-processing.

This is a one-shot kind of config - it is more the readability I was not happy with. I will generate the configuration anyway.

Note 1: you probably want to use PathPrefix(), not Path()
Note 2: most webapps don’t like to be placed under a path, they usually prefer /, unless some kind of "base path" can be set. Use sub-domains instead.

I ended up with the sub-domain approach as I could not make either Path() or PathPrefix() work for some reason. I will open a question about that for the sake of understanding.

Thanks for your answer!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.