我必须处理包含 crontab 指令的给定文件:
##Batch IdRef2Virtuoso
*/1 * * * * /home/batch/autorites/current/bin/exportAutorites2TS.sh > /dev/null 2>&1
*/1 * * * * /home/batch/autorites/current/bin/exportBiblio2TS.sh > /dev/null 2>&1
我想剪切它以获得一个包含项目列表的 yaml 文件,然后继续进行 ansible。 我可以用普通的 awk 来做这样的事情:
while read -r line; do printf '%s\n' "$line"| awk '{ split($0, ip, /'\ '/); printf("- title1: \"%s\"\n title2: \"%s\"\n minute: \"%s\"\n hour: \"%s\"\n day_month: \"%s\"\n month: \"%s\"\n day_week: \"%s\"\n day: \"%s\"\n", ip[1], ip[2], ip[3], ip[4], ip[5], ip[6], ip[7], ip[8]);}'; done <"/tmp/crontab-DEV.txt"
结果:
{
"msg": [
{
"day_month": "*",
"day_week": "*",
"hour": "*",
"job": "/home/batch/autorites/current/bin/exportAutorites2TS.sh",
"minute": "*/1",
"month": "*"
},
{
"day_month": "*",
"day_week": "*",
"hour": "*",
"job": "/home/batch/autorites/current/bin/exportBiblio2TS.sh",
"minute": "*/1",
"month": "*"
}
]
}
它可以工作,但不是很“可靠”,我怎样才能获得相同的结果?
最佳答案
给定文件
shell> cat crontab
*/1 * * * * /home/batch/autorites/current/bin/exportAutorites2TS.sh > /dev/null 2>&1
*/1 * * * * /home/batch/autorites/current/bin/exportBiblio2TS.sh > /dev/null 2>&1
下面的任务
- command: cat crontab
register: result
- set_fact:
cron_conf: "{{ cron_conf|default([]) + [dict(keys|zip(vals[0:6]))] }}"
loop: "{{ result.stdout_lines }}"
vars:
vals: "{{ item.split() }}"
keys: [minute, hour, day_month, month, day_week, job]
创建列表
cron_conf:
- day_month: '*'
day_week: '*'
hour: '*'
job: /home/batch/autorites/current/bin/exportAutorites2TS.sh
minute: '*/1'
month: '*'
- day_month: '*'
day_week: '*'
hour: '*'
job: /home/batch/autorites/current/bin/exportBiblio2TS.sh
minute: '*/1'
month: '*'
更新 09/2022
您可以使用过滤器 community.general.dict并避免迭代。例如,下面的声明给出相同的结果。
cron_keys: [minute, hour, day_month, month, day_week, job]
cron_conf: "{{ result.stdout_lines|
map('split')|
map('zip', cron_keys)|
map('map', 'reverse')|
map('community.general.dict') }}"
关于ansible - 将文件的行转换为项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66127127/