如何在Ansible中移除字符串前缀并避免生成数组?
Ansible字符串解析问题解决方法
问题分析
你当前的代码中,使用item.split('reindex-')会将带前缀的索引名拆分为包含空字符串和目标字符串的数组,再通过to_nice_json过滤器把数组转换成了JSON格式的字符串,最终导致dest.index的值是一个字符串形式的数组(如"[\n \"\",\n \"abc-def-ghi-2020-08-31\"\n]"),而非预期的纯索引名字符串。
解决方案
有两种简单的方式可以直接获取目标字符串:
方法1:取split数组的第二个元素
因为split('reindex-')返回的数组中,索引1对应的就是去掉前缀后的目标字符串,直接提取该元素即可:
- name: "Reindexing {{item}} to local server " ignore_errors: yes uri: url: "{{proto}}://{{new_server}}:{{es_api_port}}/_reindex?wait_for_completion=false" method: POST headers: Authorization: 'Basic auth==' body: source : index: "{{ item }}" dest: index: "{{ item.split('reindex-')[1] }}" body_format: json with_items: - reindex-abc-def-ghi--2020-08-31 - reindex-abc-def-ghi--2020-08-30
方法2:使用replace过滤器直接移除前缀
这种方式更直观,直接将字符串开头的reindex-替换为空字符串:
- name: "Reindexing {{item}} to local server " ignore_errors: yes uri: url: "{{proto}}://{{new_server}}:{{es_api_port}}/_reindex?wait_for_completion=false" method: POST headers: Authorization: 'Basic auth==' body: source : index: "{{ item }}" dest: index: "{{ item | replace('reindex-', '') }}" body_format: json with_items: - reindex-abc-def-ghi--2020-08-31 - reindex-abc-def-ghi--2020-08-30
修改后效果
修改后dest.index会直接输出纯字符串形式的索引名,比如abc-def-ghi--2020-08-31,符合预期需求。
内容的提问来源于stack exchange,提问作者nonoob
相关产品推荐
相关产品推荐

