在Ansible中,可以使用split
过滤器将字符串分割为列表,并使用[n]
来获取列表中的第n个项目。
以下是一个示例代码:
- hosts: localhost
gather_facts: False
vars:
my_string: "hello,world,how,are,you"
my_list: "{{ my_string.split(',') }}"
nth_item: "{{ my_list[2] }}"
tasks:
- debug:
var: nth_item
在上述示例中,我们将字符串"hello,world,how,are,you"
使用逗号分隔符进行拆分,并将结果存储在变量my_list
中。然后,我们可以使用索引[2]
来获取列表中的第三个项目,并将其存储在变量nth_item
中。
最后,通过使用debug
模块,我们可以打印出nth_item
的值。
运行以上代码将输出:
TASK [debug] ********************************************************************
ok: [localhost] => {
"nth_item": "how"
}
这表明我们成功地从分割字符串后的列表中获取了第三个项目。