Bootstrap FreeKB - Ansible - Cut characters from a string using index numbers
Ansible - Cut characters from a string using index numbers

Updated:   |  Ansible articles

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

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


July 23 2022 by no one
your example is bad, you don't show the final result (not everyone know python), have to try each and every of your example, that is just wasting everyone time.

July 23 2022 by Jeremy (moderator)
I guess I should take this as a bit of constructive criticism, but to be honest, when I read this comment, it made me laugh. It made me remember a comment from one of my favorite musicians, "if you don't like it, don't listen to it."

February 10 2023 by Khorem
how do I substring an ansible_host var?

Add a Comment


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