Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Filter 从Ansible中的字符串中删除最后n个字符_Filter_Ansible_Formatting_Trim_Ansible Facts - Fatal编程技术网

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
过滤器来完成工作。