首页 文章

查找ansible中docker卷列表的卷装入点

提问于
浏览
0

遗憾的是,目前没有API可以让我们使用docker卷 . 目前,如果我需要将数据复制到docker卷(NB:不是docker容器),我必须首先确保某个容器可以访问该卷,然后使用ansible运行 docker cp . 但是对于这些类型的任务,甚至可能没有装有卷的docker容器 . 这不是幂等的 . 这直接不允许绝大多数的ansible 's generally awesome API. This complicates the process by adding many extra steps. This is not the ansible way. What if we could simply find the mountpoints for each volume we are interested in, and then have ansible talk to the host'文件系统?

所以,假设我们有一些我们将要使用的docker卷名称的列表 . 对于列表中的每个项目,我们希望使用docker守护程序检查它,然后使用ansible设置有关其mountpoint的事实 . 这是我到目前为止:

- name: Get docker volume information
  command: "docker volume inspect {{ item }}"
  register: output
  with_items: "{{ volumes }}"

NB:Command返回如下内容:

[
    {
        "Name": "docker_sites-enabled",
        "Driver": "local",
        "Mountpoint": "/var/lib/docker/volumes/docker_sites-enabled/_data",
        "Labels": null,
        "Scope": "local"
    }
]

Playbook继续:

- name: Set volume facts
  set_fact:
    "{{ item.stdout|from_json|json_query('Name') }}": "{{ item.stdout|from_json|json_query('Mountpoint') }}"
  with_items: "{{ output.results }}"

- name: The following facts are now set
  debug:
    var: "{{ item }}"
  with_items:
    - "{{ volumes }}"

但是,这不起作用,因为我期望它作为ansible报告错误 "The variable name '' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores. It 's probably because of the syntax of the JSON query filter I' m使用,但我找不到任何关于我应该如何使用它的文档 .

1 回答

  • 1

    不确定为什么要为每个卷生成根级变量 .

    你可以这样做:

    - hosts: docker_host
      become: true
      gather_facts: false
      vars:
        volumes:
          - vol1
          - vol2
          - vol4
      tasks:
        - shell: docker volume inspect {{ volumes | join(' ') }}
          register: vlm_res
    
        - set_fact: mountpoints={{ dict(vlm_res.stdout | from_json | json_query('[].[Name,Mountpoint]')) }}
    
        - debug: var=mountpoints['vol2']
    

    mountpoints 是一个字典,所以我们可以访问 mountpoints['vol2'] 来访问 vol2 的mountpoint .

相关问题