检查 JSON 文件中的键值

Checking the key value in a JSON file

我无法验证远程服务器上 json 文件的值。我必须从模板 (j2) 覆盖远程机器上的文件一次。之后,我启动一项服务,将附加值写入此文件。 但是当重新启动ansible-playbook时,这个文件被覆盖了,因为它与模板不同。在开始从模板写入文件的任务之前,我想检查文件的唯一值。

为了在本地机器上进行测试,我这样做并且一切正常:

- name: Check file
  hosts: localhost
  vars:
    config: "{{ lookup('file','config.json') | from_json }}"

tasks:
  - name: Check info 
    set_fact:
      info: "{{ config.Settings.TimeStartUP }}"

  - name: Print info
    debug:
      var: info

  - name: Create directory
    when: interfaces | length != 0
    ansible.builtin.file:
      ...

但是当我尝试在远程机器上的任务中执行相同操作时,出于某种原因 ansible 正在本地机器上寻找文件

all.yml

---
config_file: "{{ lookup('file','/opt/my_project/config.json') | from_json }}"

site.yml

---
- name: Install My_project
  hosts: server
  tasks:
    - name: Checking if a value exists
      set_fact:
        info: "{{ config_file.Settings.TimeStartUP }}"
    - name: Print info
      debug:
        var: info

错误:

fatal: [server]: FAILED! => {"msg": "An unhandled exception occurred while templating '{{ lookup('file','/opt/my_project/config.json') | from_json }}'. Error was a <class 'ansible.errors.AnsibleError'>, original message: An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /opt/my_project/config.json. could not locate file in lookup: /opt/my_project/config.json"}

请告诉我如何正确检查远程服务器上 JSON 文件中的键值?

fetch 首先是远程主机的文件。例如,给定以下用于测试的文件

shell> ssh admin@test_11 cat /tmp/config.json
{"Settings": {"TimeStartUP": "today"}}
shell> ssh admin@test_12 cat /tmp/config.json
{"Settings": {"TimeStartUP": "yesterday"}}

下面的剧本

- hosts: test_11,test_12
  gather_facts: false
  tasks:
    - file:
        state: directory
        path: "{{ playbook_dir }}/configs"
      delegate_to: localhost
      run_once: true
    - fetch:
        src: /tmp/config.json
        dest: "{{ playbook_dir }}/configs"
    - include_vars:
        file: "{{ config_path }}"
        name: config
      vars:
        config_path: "{{ playbook_dir }}/configs/{{ inventory_hostname }}/tmp/config.json"
    - debug:
        var: config.Settings.TimeStartUP

将在 playbook_dir on the controller and will fetch the files from the remote hosts into this directory. See the parameter dest 中创建目录 configs 关于如何创建路径

shell> cat configs/test_11/tmp/config.json
{"Settings": {"TimeStartUP": "today"}}
shell> cat configs/test_12/tmp/config.json
{"Settings": {"TimeStartUP": "yesterday"}}

然后include_vars并将字典存入变量config

ok: [test_11] => 
  config.Settings.TimeStartUP: today
ok: [test_12] => 
  config.Settings.TimeStartUP: yesterday