首页 > 解决方案 > 使用 Ansible 计算磁盘空间

问题描述

我需要超过 100 台机器并获得 /var 的总大小。然后汇总所有机器的空间并打印。我多次尝试获取我的数据但没有成功,我正在寻求帮助。

我不确定使用事实是正确的方法,并且可能还有其他我不知道的模块可以完成这项工作。这是我到目前为止所尝试的。

---
- hosts: servers
  remote_user: ansible
  become: true
  gather_facts: no
  tasks:
  - name: Initialize an empty list for our strings
    set_fact:
      my_strings: []
  - name: fetching
    shell: du -sh /var 
    register: var
  - name: Append string to list
    set_fact:
      my_strings: "{{ my_strings + [ var.stdout ] }}"
  - name: print output
    debug: 
      msg: "-> {{ my_strings }}"

标签: ansible

解决方案


你可以使用事实,但你使用它们的方式是错误的。你要明白的是:

  • 事实对于特定主机来说是本地的。
  • 任务一次在特定主机上运行(最终并行)并使用来自该主机的事实。

因此,像您尝试做的那样将磁盘空间添加为列表元素基本上只会在每台机器的单个元素列表中添加单独的计算空间。

您可以做的是在每台机器上收集各个事实,然后对其进行操作,如果它们具有兼容的类型,甚至对它们进行求和...这可以使用魔法变量hostvars和一些您必须熟悉的过滤器来完成以下操作文件:

这是一个示例剧本,您无需连接任何地方即可运行。为此,我创建了 3 个连接到本地计算机的假主机。用您自己的库存替换/调整,您应该没问题。我试图在 ansible 中演示一些数据操作技术。您可以将它们以不同的方式组合起来,并使用其他的来满足您的确切需求。无论如何,我希望它有助于澄清问题。

这是我的例子inventories/demo/hosts.yml

---
all:
  vars:
    ansible_connection: local
    ansible_python_interpreter: /usr/bin/python3
  children:
    servers:
      hosts:
        demo1:
        demo2:
        demo3:

示例var_size.yml剧本:

---
- name: Get /var size on all servers hosts
  hosts: servers
  gather_facts: false

  tasks:
    - name: Fetching /var size on hosts
      command: du -s /var
      register: du_var
      become: true
      changed_when: false

    # This is absolutely needed as registers don't survive current play
    # See next play on localhost only
    - name: Store actual size for hosts in a fact
      vars:
        size_regex: >-
          ^(\d+)\s*/var
        replace: >-
          \g<1>
      set_fact:
        var_size_bytes: "{{ du_var.stdout | regex_replace(size_regex, replace) }}"

    # As a first example, demonstrate we can simply display sizes
    # with the natural play host loop
    - name: Show human readable size of /var on each host
      debug:
        msg: "/var size is: {{ var_size_bytes | int | human_readable }}"

# Now we can work on consolidating
- name: Consolidate data we gathered
  hosts: localhost
  gather_facts: false

  tasks:
    - name: Create a dict of sizes extracting all relevant hostvars
      # This fact is set on localhost as this is the only play target
      set_fact:
        var_sizes_host_dict: "{{ groups['servers'] | map('extract', hostvars) | items2dict(key_name='inventory_hostname', value_name='var_size_bytes') }}"

    - name: Show the raw dict with bytes sizes
      debug:
        var: var_sizes_host_dict

    - name: Display sizes for all hosts in human readable format
      vars:
        hostnames: "{{ var_sizes_host_dict.keys() }}"
        hr_sizes: "{{ var_sizes_host_dict.values() | map('int') | map('human_readable') }}"
        var_sizes_host_dict_hr: "{{ hostnames | zip(hr_sizes) | items2dict(key_name=0, value_name=1) }}"
      debug:
        msg: "{{ var_sizes_host_dict_hr }}"

    - name: Sum all /var sizes
      vars:
        host_number: "{{ var_sizes_host_dict | length }}"
        total_space: "{{ var_sizes_host_dict.values() | map('int') | sum }}"
        raw_message: |-
          The total number of host is: {{ host_number }}
          The total /var space used is: {{ total_space | int | human_readable }}
      debug:
        msg: "{{ raw_message.split('\n') }}"

这使:

$ ansible-playbook -i inventories/demo var_size.yml 

PLAY [Get /var size on all demo hosts] *************************************************************************************************************************************************************************************************

TASK [Fetching /var size on hosts] *****************************************************************************************************************************************************************************************************
ok: [demo3]
ok: [demo1]
ok: [demo2]

TASK [Store actual size for hosts in a fact] *******************************************************************************************************************************************************************************************
ok: [demo2]
ok: [demo1]
ok: [demo3]

TASK [Show human readable size of /var on each host] ***********************************************************************************************************************************************************************************
ok: [demo1] => {
    "msg": "/var size is: 4.31 MB"
}
ok: [demo3] => {
    "msg": "/var size is: 4.31 MB"
}
ok: [demo2] => {
    "msg": "/var size is: 4.31 MB"
}

PLAY [Consolidate data we gathered] ****************************************************************************************************************************************************************************************************

TASK [Create a dict of sizes extracting all relevant hostvars] *************************************************************************************************************************************************************************
ok: [localhost]

TASK [Show the raw dict with bytes sizes] **********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "var_sizes_host_dict": {
        "demo1": "4518993",
        "demo2": "4518993",
        "demo3": "4518993"
    }
}

TASK [Display sizes for all hosts in human readable format] ****************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": {
        "demo1": "4.31 MB",
        "demo2": "4.31 MB",
        "demo3": "4.31 MB"
    }
}

TASK [Sum all /var sizes] **************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "The total number of host is: 3",
        "The total /var space used is: 12.93 MB"
    ]
}

PLAY RECAP *****************************************************************************************************************************************************************************************************************************
demo1                      : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
demo2                      : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
demo3                      : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
localhost                  : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

推荐阅读