简体   繁体   中英

Ansible lineinfile Regex

I have this text

[john]
age=20
group=wheel
[doe]
age=30
group=wheel
[stack]
age=undefined
group=wheel
color=white
[overflow]
age=undefined

and i want to capture with first regex:

age=20

and group=wheel of [stack] with the second one

You're trying to use regex for a well defined text file format; the ini lookup is what you are actually after:

# assuming the ini file is /tmp/foo.ini
tasks:
- set_fact:
    john_age: '{{ lookup("ini", "age section=john file=/tmp/foo.ini") }}'
    stack_group: '{{ lookup("ini", "group section=stack file=/tmp/foo.ini") }}'

then, in the case where your content isn't actually in a file, it seems the lookup only works with files so you'd need to temporarily write it out to a file:

tasks:
- copy:
    dest: /tmp/foo.ini
    content: '{{ the_ini_from_your_question_goes_here }}'
- set_fact:
    john_age: '{{ lookup("ini", "age section=john file=/tmp/foo.ini") }}'
    stack_group: '{{ lookup("ini", "group section=stack file=/tmp/foo.ini") }}'
- file:
    path: /tmp/foo.ini
    state: absent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM