我在远程服务器上验证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文件中的键值?
首先从远程主机获取文件。例如,给定以下用于测试的文件
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中创建目录configs,并将文件从远程主机获取到此目录中。请参阅参数dest,了解如何创建路径
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