【问题标题】:Remove special characters using regex on list item with Ansible使用 Ansible 列表项上的正则表达式删除特殊字符
【发布时间】:2019-10-10 10:10:41
【问题描述】:

我想不通。

如何删除任何特殊字符和空格,只在下面的 item.0 变量中留下文本?

例如,show 命令会这样转换。

show running-config >> show_running_config

show ip interface brief | include up >> show_ip_interface_brief_include_up

输出保存到与命令同名的文件中。所以像|/\ 这样的特殊字符会导致问题。

我尝试过使用它,但我得到了错误。

dest: "/media/share/ansible_out/{{ inventory_hostname }}/{{ item.0 | regex_replace('@?\+(.*)', '_') }}.bck"

这是在尝试写入文件名中带有| 的文件时出现错误的ansible 代码。

---
- name: Create show command list
  set_fact:
    command_list:
      - show running-config
      - show ip interface brief | include up

- name: Execute commands on device
  ios_command:
    commands: "{{ command_list }}"
  register: output
  when: ansible_network_os == 'ios'

- name: Copy show command output to file
  copy:
    content: '{{ item.1 }}'
    force: yes
    dest: "/media/share/ansible_out/{{ inventory_hostname }}/{{ item.0 }}.bck"
  loop: "{{ command_list|zip(output.stdout)|list }}"
  when: ansible_network_os == 'ios'

【问题讨论】:

  • 嗨,詹姆斯,不确定您要的是什么。使用正则表达式,您只能过滤 ascii。

标签: regex ansible


【解决方案1】:

问:“如何删除任何特殊字符和空格,只在变量中留下文本?”

A:可以使用 map 和 regex_replace 的组合,因为 YAML 中的字符串是一个字符数组。比如戏

- hosts: localhost
  vars:
    regex: '[^A-Za-z0-9._-]'
    replace: '_'
    command_list:
      - show running-config
      - show ip interface brief | include up
  tasks:
    - debug:
        msg: "{{ item|map('regex_replace', regex, replace)|list|join() }}"
      loop: "{{ command_list }}"

给予

"msg": "show_running-config"
"msg": "show_ip_interface_brief___include_up"

【讨论】:

  • 这看起来很棒。我要到星期一才能测试。会回到你身边。非常感谢
猜你喜欢
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 2017-12-07
  • 1970-01-01
  • 2018-10-11
相关资源
最近更新 更多