代码之家  ›  专栏  ›  技术社区  ›  Jéan

基于变量的ansible docker装载卷

  •  0
  • Jéan  · 技术社区  · 7 年前

    是否有方法在下面装载卷 volumes: ansible docker\u服务模块中的指令?

    我想写一个docker\u compose,并有一个变量来选择要装载的正确卷。

    - name: Add docker_service for the Ansible Container
        docker_service:
          project_name: jro
          definition:
            version: '3'
            services:
              ansible:  
                image: python:3.7.0a3-alpine3.7
                volumes:
                  - {CONDITION xxx} then "xxx:ccc"
                  - {CONDITION yyy} then "yyy:ccc:
    2 回复  |  直到 7 年前
        1
  •  4
  •   larsks    7 年前

    这不是Ansible剧本中通常处理条件的方式。您没有告诉我们您的情况,因此很难直接回答您的问题,但您可以这样做:

    - set_fact:
        volume_to_mount: foo
      when: condition1
    
    - set_fact:
        volume_to_mount: bar
      when: condition2
    
    - name: Add docker_service for the Ansible Container
      docker_service:
        project_name: jro
        definition:
          version: '3'
          services:
            ansible:  
              image: python:3.7.0a3-alpine3.7
              volumes:
                - "{{volume_to_mount}}:/mountpoint"
    

    如果您的条件是主机名或组,通常会通过使用组或主机vars文件来处理。E、 例如,如果要为“foo\u group”主机组中的所有主机装载卷“foo”,并为“bar\u group”主机组中的所有主机装载卷“bar”,则需要创建 group_vars/foo_group.yml 使用:

    volume_to_mount: foo
    

    groups_vars/bar_group.yml 使用:

    volume_to_mount: bar
    

    如果需要安装 倍数 卷,您可以执行与上述类似的操作,但使用列表而不是单个值,例如:

    volumes_to_mount:
      - "bar:/mount_for_bar"
      - "foo:/mount_for_foo"
    

    然后在你的 docker_service 任务:

    - name: Add docker_service for the Ansible Container
      docker_service:
        project_name: jro
        definition:
          version: '3'
          services:
            ansible:  
              image: python:3.7.0a3-alpine3.7
              volumes: "{{ volumes_to_mount }}"
    

    希望这里有一些东西能为你指明正确的方向。如果您想要一个更有针对性的答案,请随时提供有关您正在尝试做什么的更多详细信息。

        2
  •  3
  •   techraf    7 年前

    对于问题中定义的问题:

    volumes:
       - "{{ 'xxx:ccc' if xxx else omit }}" 
       - "{{ 'yyy:ccc' if yyy else omit }}"
    

    我现在无法验证,如果 omit 在这种特殊模式下会起作用

    或者(猜猜你实际上在找什么):

    volumes:
       - "{{ 'xxx:ccc' if my_condition else 'yyy:ccc' }}"