从Ansible中的字符串中删除最后n个字符

问题描述 投票:0回答:1

下面是我的构成字符串的剧本。

   - 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个字符。

你能建议吗?

filter ansible formatting trim ansible-facts
1个回答
0
投票
- 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"
}
© www.soinside.com 2019 - 2024. All rights reserved.