1

Below is my playbook that constructs a string.

   - 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 }}"

Output:

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"
    }
}

After the loop completes I get the desired string except the fact that I'm left with the trailing && at the end i.e "allcmd": " ls -lrt /tmp/scripts | tail -57 && ls -lrt /tmp/MON | tail -57 &&".

I wish to remove the last 3 charecters i.e && from allcmd variable. Desired output:

"allcmd": " ls -lrt /tmp/scripts | tail -57 && ls -lrt /tmp/MON | tail -57"

Could not find any filters or fuction to remove last n charecters in ansible.

Can you please suggest ?

Ashar
  • 2,942
  • 10
  • 58
  • 122

2 Answers2

5

there is a much easier way outlined in this link

http://www.freekb.net/Article?id=2884

  debug: 
    msg: "{{ 'Hello World'[:-3] }}"
Jon Alexandar
  • 131
  • 1
  • 10
1
- 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

output:

ok: [localhost] => {
    "allcmd": "ls -lrt /tmp/MON | tail -57 && ls -lrt /tmp/scripts | tail -57"
}
Ben Tse
  • 649
  • 5
  • 7