首页 > 解决方案 > 使用 regex_replace 删除 ansible playbook 中的字符

问题描述

我在 ansible 中运行一个剧本,它采用 shell 模块输出的 stdout_lines 并给我这种格式:

StackNames.stdout_lines:
- "["
- '    "SHSD-CZWV-ami-automation-WIN2012R2-NONPROD-ramirja-119",'
- '    "SHSD-CZWV-ami-automation-WIN2012R2-NONPROD-ramirja-118",'
- '    "SHSD-CZWV-ami-automation-WIN2012R2-NONPROD-ramirja-117"'
- "]"

我正在尝试获取可以在循环中使用的这些值的列表,以便可以删除堆栈,但首先我需要删除所有引号、dbl 引号和空格,以便为 cloudformation ansible 模块正确格式化接受 stack_name 参数值。

我尝试使用正确的格式设置一个新变量,例如:

     - set_fact:
         stack_list: "{{ StackNames.stdout_lines | replace('"','') |trim }}"

但到目前为止我还没有运气。

任何帮助是极大的赞赏

标签: regexreplaceansibleamazon-cloudformation

解决方案


从您的示例中,您的 shell 命令返回一个 json 可解析结果。只需使用过滤器解析stdout变量内的全局输出 ( )即可:from_json

- set_fact:
    stack_list: "{{ StackNames.stdout | from_json }}"

- name: Make sure the above is working with your specific output
  debug:
    var: item
  loop: "{{ stack_list }}"

推荐阅读