从主机获取值并写入本地文件的 Ansible 问题,使用 ansible 从节点收集数据

问题描述 投票:0回答:1

我有这个简单的剧本,可以读取文件内容 => 获取值 => 将其附加到本地文件中, 我想获取存储在本地文件中的不同主机的配置值。

---
- name: Check file content
  hosts: all
  become: true

  tasks:
    - name: Check if file exists
      ansible.builtin.stat:
        path: /mydir/myfile.ini
      register: file_stat

    - name: Fetch values and write to a local file
      when: file_stat.stat.exists
      block:
        - name: Read file if it exists
          ansible.builtin.slurp:
            src: /mydir/myfile.ini
          register: file_content

        - name: Set value as a fact
          ansible.builtin.set_fact:
            my_setting: "{{ file_content.content | \
              b64decode | regex_search('^setting_key\\s*?=\\s*?(.*)$', \
              '\\1', multiline=True) | first | trim }}"

        - name: Debug file content
          ansible.builtin.debug:
            msg: '{{ my_setting }}'

        - name: Write fetch value to a file
          become: false
          ansible.builtin.lineinfile:
            path: my_settings.txt
            line: '{{ inventory_hostname }} - {{ my_setting }}'
            create: true
            mode: '644'
            insertafter: 'EOF'
          delegate_to: localhost
          # when: >
          #   my_setting is defined and
          #   my_setting != "MY_SETT_VALUE"
          # with_items: '{{ my_setting }}'

但是,这个剧本的行为不一致。如果我针对两台主机运行它,有时输出文件中会有两行

my_settings.txt
,每个主机各一行,正如预期的那样。 但有时会只有一行或一个主机信息(大多数时候),而另一台主机的值缺失。

这是由于某种竞争条件造成的吗?我该如何解决这个问题?

调试行始终显示不同主机的正确值,因此问题不在于读取或获取值。

注意:源文件位于远程节点,

编辑:我写了这个快速播放来从不同节点收集设置文件的值(当需要时我会想到ansible)。然而,正如答案所指出的,剧本存在几个问题,我也意识到了这一点。

这种方法有可能导致文件锁定失败和数据覆盖。所以,我的问题是:Ansible 是否打算这样使用,即从不同节点收集数据并将其存储在本地文件或数据库中?如果是,最好的方法是什么?

例如,如果我需要准备一份比较我的节点的报告,如何检查来自不同节点的数据并将其存储在中心节点中?

ansible ansible-2.x
1个回答
1
投票

前面只是一些注释

基于您当前的方法既不简单也不推荐。


我需要检查INI文件中所有节点是否包含完全相同的值

一个最小的示例手册

---
- hosts: test
  become: false
  gather_facts: false

  tasks:

  - name: Make sure that custom settings file is in Desired State
    ini_file:
      path: "./custom.setting"
      section: Nodes
      option: SameValue
      value: "True"
      create: true
    diff: true
    register: result

将生成所需的文件

custom.setting

[Nodes]
SameValue = True

和输出

TASK [Make sure that custom settings file is in Desired State] ******
--- before: ./custom.setting (content)
+++ after: ./custom.setting (content)
@@ -1,3 +1,3 @@

 [Nodes]
-SameValue = False
+SameValue = True

可用于审计和检查

  - name: Audit and report custom settings file
    ini_file:
      path: "./custom.setting"
      section: Nodes
      option: SameValue
      value: "True"
    check_mode: true
    register: result

  - debug:
      var: result.changed

产生

的输出
TASK [Audit and report custom settings file] ******
ok: [test.example.com]

TASK [debug] **************************************
ok: [test.example.com] =>
  result.changed: false

更多文档

开箱即用的还有

以及维护配置状态作为一种

© www.soinside.com 2019 - 2024. All rights reserved.