簡體   English   中英

ansible 用於替換空格引號或注釋的正則表達式

[英]ansible regexp for replace space quotes or comment

我有一個包含多行的文件。 其中一行可能如下所示:

item = 1000 or item = "1000" or item='1000' #with comment same line 
or item = "1000'

或有關等號周圍空格的所有可能組合,或帶有單引號或雙引號或不帶引號,或者同樣,在同一行上有或沒有注釋。

簡而言之,我只需要獲取數字並使用 set fact 設置一個變量。 這件事快把我逼瘋了。

對不起,但我沒有把我所做的所有嘗試都放在一起,因為它們太多了。

myfile.conf:  
 start = 'before'
 stop=after  
 item =100  #changed  
 bool= "yes"
 class = 'first"
 author = "Scott"

or item = 1000 or item = "1000" or item='1000' #blalala or item = "1000'
如上所述。

這是放棄前的最后一次嘗試:

- name: QUERY- read the myfile.conf
  ansible.builtin.shell: cat "{{ './myfile.conf' }}"
  register: resultline
  
- name: regex
  ansible.builtin.set_fact:
    mynumber: |-
      {{
          resultline.stdout |
          regex_search("^item *=*.*", multiline=True) |
          regex_replace(".*=*['\"](.*)['\"]*$", '\1')
      }}

而且,當然,這行不通......

Expected result is: 
mynumber = 1000 
給定以下文件。 (我修復了 *class* 值的引用。)
    - command: cat myfile.conf
      register: resultline

問: “在以item開頭的行的=之后帶有數字的 var mynumber 。”

A:讀取文件

conf_list:
  - ' start = ''before'''
  - ' stop=after  '
  - ' item =100  '
  - ' bool= "yes"'
  - ' class = "first"'
  - ' author = "Scott"'

刪除評論並創建列表

conf_dict: "{{ conf_list|
               map('regex_replace', '=', ': ')|
               join('\n')|
               from_yaml }}"

conf_dict:
  author: Scott
  bool: 'yes'
  class: first
  item: 100
  start: before
  stop: after

將 '=' 替換為 ': ' 並創建字典

my_number: "{{ conf_dict.item }}"

my_number: '100'

設置變量

    - debug:
        var: my_number|int + 1

my_number|int + 1: '101'

"{{ }}"的計算結果始終是一個字符串。 您可以將其轉換為 integer。例如,

 - debug: var: my_number|int + 1

my_number|int + 1: '101'

筆記

  • 完整劇本的示例
- hosts: localhost vars: conf_list: "{{ resultline.stdout_lines| map('regex_replace', conf_regex, conf_replace)| list }}" conf_regex: '^(.*)#.*$' conf_replace: '\1' conf_dict: "{{ conf_list| map('regex_replace', '=', ': ')| join('\n')| from_yaml }}" my_number: "{{ conf_dict.item }}" tasks: - command: cat myfile.conf register: resultline - debug: var: my_number - debug: var: my_number|int + 1
  • 屬性的值為一個integer
 - debug: var: conf_dict.item|type_debug

conf_dict.item|type_debug: int

您可以在不進行轉換的情況下將其用於算術運算。 例如,

 - debug: var: conf_dict.item + 1

conf_dict.item + 1: '101'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM