Filter 从Ansible中的字符串中删除最后n个字符
下面是我构建字符串的剧本Filter 从Ansible中的字符串中删除最后n个字符,filter,ansible,formatting,trim,ansible-facts,Filter,Ansible,Formatting,Trim,Ansible Facts,下面是我构建字符串的剧本 - name: Construct command for all paths on a particular IP set_fact: allcmd: "{{ allcmd | default('') + '\"ls -lrt ' + item.path + ' | tail -57 &&' }}" loop: "{{ user1[inventory_hostname] }}" - debug:
- name: Construct command for all paths on a particular IP
set_fact:
allcmd: "{{ allcmd | default('') + '\"ls -lrt ' + item.path + ' | tail -57 &&' }}"
loop: "{{ user1[inventory_hostname] }}"
- debug:
msg: "allcmd is:{{ allcmd }}"
输出:
ok: [10.9.9.11] => (item={u'path': u'/tmp/scripts', u'name': u'SCRIPT'}) => {
"ansible_facts": {
"allcmd": "ls -lrt /tmp/scripts | tail -57 &&"
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"name": "SCRIPT",
"path": "/tmp/scripts"
}
}
ok: [10.9.9.11] => (item={u'path': u'/tmp/MON', u'name': u'MON'}) => {
"ansible_facts": {
"allcmd": " ls -lrt /tmp/scripts | tail -57 && ls -lrt /tmp/MON | tail -57 &&"
},
"ansible_loop_var": "item",
"changed": false,
"item": {
"name": "MON",
"path": "/tmp/MON"
}
}
循环完成后,我得到了所需的字符串,除了在末尾留下了尾随的&
,即“allcmd”:“ls-lrt/tmp/scripts | tail-57&&ls-lrt/tmp/MON | tail-57&&”
我希望从allcmd变量中删除最后3个字符,即&&
。期望输出:
“allcmd”:“ls-lrt/tmp/scripts|tail-57&&ls-lrt/tmp/MON|tail-57”
找不到任何筛选器或函数来删除ansible中的最后n个字符
你能推荐一下吗
- hosts: localhost
vars:
foo:
- {"name": "SCRIPT", "path": "/tmp/scripts"}
- {"name": "MON", "path": "/tmp/MON"}
tasks:
- debug:
var: foo
- set_fact:
cmds: "{{ [ 'ls -lrt ' + item.path + ' | tail -57' ] + cmds | default([]) }}"
loop: "{{ foo }}"
- set_fact:
allcmd: "{{ cmds | join(' && ')}}"
- debug:
var: allcmd
输出:
ok: [localhost] => {
"allcmd": "ls -lrt /tmp/MON | tail -57 && ls -lrt /tmp/scripts | tail -57"
}
您可以将命令添加到列表中(不带
&&
),并加入('&&')
最终列表。非常优雅的解决方案@Zeitounator。同时,我使用rstrip
过滤器来完成工作。