【问题标题】:Finding the volume mount points for a list of docker volumes in ansible在 ansible 中查找 docker 卷列表的卷挂载点
【发布时间】:2017-02-07 02:30:04
【问题描述】:

很遗憾,当前没有允许我们使用 docker 卷的 API。目前如果我需要将数据复制到 docker 卷中(注意:不是 docker container)我必须首先确保某些容器可以访问该卷,然后使用 ansible 运行docker cp。但是对于这类任务,甚至可能没有安装了卷的 docker 容器。这不是幂等的。这不允许绝大多数 ansible 通常很棒的 AP​​I。这通过添加许多额外的步骤使过程复杂化。这不是可靠的方式。如果我们可以简单地找到我们感兴趣的每个卷的挂载点,然后直接与主机的文件系统进行 ansible 对话呢?

假设我们有一些我们将要使用的 docker 卷的名称列表。对于列表中的每个项目,我们希望使用 docker 守护进程对其进行检查,然后使用 ansible 设置有关其挂载点的事实。这是我目前所拥有的:

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

注意:命令返回如下内容:

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

剧本继续:

- 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. 这可能是因为我正在使用的 JSON 查询过滤器的语法,但我找不到任何关于我如何应该使用它。

【问题讨论】:

  • 你能确切地显示output变量中的内容,而不是“类似这样的东西”吗?你知道如何使用debug 模块...
  • 还有volumes的值是多少?哪个任务失败了?你包括The following facts are now set——我应该假设它是给出错误的那个吗?如果前一个失败,那么在问题中包含最后一个的目的是什么?

标签: ansible docker-volume ansible-facts


【解决方案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 的挂载点。

【讨论】:

  • 是的,严格来说并不需要变量是根级别的。感谢您的回复!
猜你喜欢
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2015-10-01
  • 2016-08-18
  • 2021-07-16
  • 2020-06-05
  • 2020-01-20
相关资源
最近更新 更多