Ansible - Cut characters from a string using index numbers

[0] can be used to get the first character from the string "Hello World". 

- name: get the first character from string 'Hello World'
  debug: 
    msg: "{{ 'Hello World'[0] }}"

 

Which should return the following.

TASK [get the first character from string 'Hello World']
ok: [server1.example.com] => {
    "msg": [
        "H"
    ]
}

 

Or to get the first character from a variable.

- name: get the first character from variable 'foo'
  debug: 
    msg: "{{ foo[0] }}"

 

[-1] can be used to get the last character.

- name: get the last character from string 'Hello World'
  debug: 
    msg: "{{ 'Hello World'[-1] }}"

 

[:3] can be used to get the first 3 characters.

- name: get the first 3 characters from string 'Hello World'
  debug: 
    msg: "{{ 'Hello World'[:3] }}"

 

[-3:] can be used to get the last 3 characters.

- name: get the last 3 characters from string 'Hello World'
  debug: 
    msg: "{{ 'Hello World'[-3:] }}"

 

[:-3] can be used to get everything except for the last 3 characters.

- name: get everything except for the last 3 characters from string 'Hello World'
  debug: 
    msg: "{{ 'Hello World'[:-3] }}"

 

[3:] can be used to get everything except for the first 3 characters.

- name: get everything except for the first 3 characters from string 'Hello World'
  debug: 
    msg: "{{ 'Hello World'[3:] }}"

 

You may also want to use the trim filter to remove whitespace from the left and right sides of a string.

- name: output 'Hello World', trim whitespace
  debug: 
    msg: "{{ '  Hello World  ' | trim }}"

 

Which should return the following.

TASK [output 'Hello World', trim whitespace]
ok: [server1.example.com] => {
    "msg": [
        "Hello World"
    ]
}

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 8ceb3 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |