1

I have a variable in my playbook that has a number of values separated by commas. At this point I am not sure if the variable is a string or a list. I believe from the output below the "[]" indicate a list.

Variable populated

-set_fact:
    snap_master_01: "{{ ec2_snapshot_facts.snapshots | 
selectattr(tags.HostName, equalto, ICINGA2_MASTER_1.tag_value) |
 sort(attribute=start_time) | reverse | map(attribute=snapshot_id) | list }}"

- name: Print snapshot ID's
   debug:
     msg:
        - "{{ snap_master_01 }}"`  

Gives the following output:

`TASK [Print snapshot ID's]     ********************************************************************************    ***********************
task path: /home/r_ansible/playbooks/backup_aws.yml:252
ok: [172.16.1.58] => {
    "changed": false,
    "msg": [
        [
            "snap-04c88ef6XXXXXXXXX",
            "snap-0bd5785fXXXXXXXXX",
            "snap-045e0f4bXXXXXXXXX",
            "snap-055fda51XXXXXXXXX",
            "snap-03759206XXXXXXXXX"
        ]
    ]
}`

I would like to delete the last 3 values. What is the best way of achieving this in Ansible?

alexis
  • 1,022
  • 3
  • 16
  • 44

1 Answers1

2

To manipulate lists in Ansible, you can use Python slices.

In your case snap_master_01[:-3] will give you all but last three elements.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • thanks for the help. `- name: Cut the list by our COUNT variable. set_fact: snaps_cut: "{{ snap_master_02[COUNT:] }}" ` – alexis Jun 14 '17 at 07:46
  • thanks for the help. I tried the following but get an error. `- name: Cut the list by our COUNT variable. set_fact: snaps_cut: "{{ snap_master_02[COUNT:] }}" ` but i get the following error: `fatal: [172.16.1.58]: FAILED! => {"failed": true, "msg": "Unexpected templating type error occurred on ({{ [snap_master_02][COUNT:] }}): slice indices must be integers or None or have an __index__ method"} to retry, use: --limit @/home/r_ansible/playbooks/backup_aws.retry` Sorry I got the 5 minute timeout and couldn't finish my last comment. – alexis Jun 14 '17 at 07:52
  • 1
    use `[COUNT|int:]`. – Konstantin Suvorov Jun 14 '17 at 07:53
  • thanks !! that did it. :-) Is there somewhere this is documented? I have been struggling with this for a day and i couldn't find any documentation – alexis Jun 14 '17 at 07:58
  • @alexis type casting? Yes, see Jinja2 filters. – Konstantin Suvorov Jun 14 '17 at 08:00