迭代脚本的输出并创建字典



这是我的可靠策略:

---
- hosts: all
remote_user: root
gather_facts: no
tasks:
- name: Execute script in remote machine
script: sysget.sh
register: output
- debug:
var: output.stdout_lines

输出:

TASK [debug] ******************************************************************************************************************************
ok: [xx.xx.xx.xx] => {
"output.stdout_lines": [
"OS type: Red Hat",
"Product Version: 1.11.0-2.el7",
"No of CPU: 4",
"CPU Clock Freq: 2394.454 MHz",
"IP-Address:  xx.xx.xx.xx",
"RAM:  7.6377 GB",
"Hostname:  dummy",
"OS Version: CentOS Linux 7.7.1908 (Core)"
]
}

我想迭代这个输出,并创建一个键值对的字典,如下所示:

{"OS type":"Red Hat","RAM":"7.6377 GB"}

下面的任务完成的工作

- set_fact:
sysget_dict: "{{ dict(my_keys2|zip(my_vals)) }}"
vars:
my_keys: "{{ output.stdout_lines|
map('regex_replace','^(.*)\s*:\s*(.*)$', '\1')|
list }}"
my_vals: "{{ output.stdout_lines|
map('regex_replace','^(.*)\s*:\s*(.*)$', '\2')|
list }}"
my_keys2: "{{ my_keys|
map('regex_replace', '[^_a-zA-Z0-9]', '_')|
list }}"
- debug:
var: sysget_dict
- debug:
var: sysget_dict.OS_type
- debug:
var: sysget_dict.RAM

给出

"sysget_dict": {
"CPU_Clock_Freq": "2394.454 MHz", 
"Hostname": "dummy", 
"IP_Address": "xx.xx.xx.xx", 
"No_of_CPU": "4", 
"OS_Version": "CentOS Linux 7.7.1908 (Core)", 
"OS_type": "Red Hat", 
"Product_Version": "1.11.0-2.el7", 
"RAM": "7.6377 GB"
}
"sysget_dict.OS_type": "Red Hat"
"sysget_dict.RAM": "7.6377 GB"

Q:"如何使用此变量"sysget_dict"作为脚本的输入,该脚本需要字典作为输入?">

A:将变量"sysget_dict"写入文件。例如,使用template

shell> cat sysget.json.j2
{{ sysget_dict|to_nice_json }}

任务

- template:
src: sysget.json.j2
dest: sysget.json

给出

shell> cat sysget.json 
{
"CPU_Clock_Freq": "2394.454 MHz",
"Hostname": "dummy",
"IP_Address": "xx.xx.xx.xx",
"No_of_CPU": "4",
"OS_Version": "CentOS Linux 7.7.1908 (Core)",
"OS_type": "Red Hat",
"Product_Version": "1.11.0-2.el7",
"RAM": "7.6377 GB"
}

可以将此文件用作脚本的输入。例如

shell> cat test.sh 
#!/usr/bin/sh
jq '.' $1

给出

shell> ./test.sh sysget.json 
{
"CPU_Clock_Freq": "2394.454 MHz",
"Hostname": "dummy",
"IP_Address": "xx.xx.xx.xx",
"No_of_CPU": "4",
"OS_Version": "CentOS Linux 7.7.1908 (Core)",
"OS_type": "Red Hat",
"Product_Version": "1.11.0-2.el7",
"RAM": "7.6377 GB"
}

最新更新