【问题标题】:How would I configure a dictionary which requires variables in a loop?如何配置需要循环变量的字典?
【发布时间】:2021-10-25 01:40:19
【问题描述】:

我有一个 docker_container 我想为多个用户部署它并在用户之后命名 traefik 路由。但我对如何实现这一点感到困惑。

这是我所拥有的:

- name: Run syncthing
  docker_container:
    name: "{{ item.name }}-syncthing"
    image: "lscr.io/linuxserver/syncthing"
    state: started
    restart_policy: "always"
    env:
      PUID: "1000"
      PGID: "1000"
    volumes:
      - "{{ item.data_dir }}:/data"
... other volumes
    labels:
      traefik.enable: true
      "traefik.http.routers.{{ item.name }}-syncthing.entrypoints": websecure
      "traefik.http.routers.{{ item.name }}-syncthing.rule": Host(`{{ item.name }}.{{ fqdn_real }}`)
      "traefik.http.routers.{{ item.name }}-syncthing.tls": true
      "traefik.http.routers.{{ item.name }}-syncthing.tls.certresolver": le 
      "traefik.http.routers.{{ item.name }}-syncthing.service": "{{ item.name }}-syncthing"
      "traefik.http.routers.{{ item.name }}-syncthing.middlewares": "{{ item.name }}-basicauth"
      "traefik.http.services.{{ item.name }}-syncthing.loadbalancer.server.port": 8080
      "traefik.http.middlewares.{{ item.name }}-syncthing-basicauth.basicauth.users": "{{ item.auth }}"
  with_items: "{{ syncthing_containers_info }}"

还有一个像这样的syncthing_config_info

syncthing_containers_info:
  - { name: "c1", data_dir: "/mnt/data/c1/data", auth: "..." }
  - { name: "c2", data_dir: "/mnt/data/c2/data", auth: "..." }
  - { name: "c3", data_dir: "/mnt/data/c3/data", auth: "..." }

那个 sn-p 不起作用,因为 ansible 不喜欢这种语法,所以我尝试了 thiswith_nested 但我在尝试 set_fact 时遇到了类似的嵌套循环问题在示例中,因为标签集取决于syncthing_containers_info。我有更好的方法吗?

【问题讨论】:

    标签: ansible jinja2


    【解决方案1】:

    听起来您需要 labels: 成为实际的 dict,因为 yaml 键不受 jinja2 插值的影响

        labels: >-
          {%- set key_prefix = "traefik.http.routers." ~ item.name ~"-syncthing" -%}
          {{ {
          "traefik.enable": True,
          key_prefix ~ ".entrypoints": "websecure",
          key_prefix ~ ".rule": "Host(`" ~ item.name ~"."~ fqdn_real ~"`)",
          key_prefix ~ ".tls": True,
          key_prefix ~ ".tls.certresolver": "le",
          key_prefix ~ ".service": item.name ~ "-syncthing",
          key_prefix ~ ".middlewares": item.name ~ "-basicauth",
          "traefik.http.services." ~ item.name ~ "-syncthing.loadbalancer.server.port": 8080,
          "traefik.http.middlewares." ~ item.name ~"-syncthing-basicauth.basicauth.users": item.auth,
          } }}
    

    (请注意,我没有对此进行测试,只是从您的问题中观察到它,但这是一般的想法)

    【讨论】:

    • 效果很好,谢谢!我只需要将True 更新为"true" 就可以了。你能告诉我这个语法叫什么或指向我的文档吗?
    • 啊,是的,因为标签是字符串-字符串对;对于那个很抱歉!那是jinja2,ansible 附带的模板/脚本语言。它主要是 python语法,但肯定有一些奇怪的差异会导致很多SO问题:-(
    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多