How to specify case insensitive mode in ansible lineinfile regexp? - regex

Simple question.
I'm trying to match "UseDns", "usedns" and other variations.
- name: Disable DNS checking on login (huge speedup)
sudo: true
lineinfile:
dest: "/etc/ssh/sshd_config"
regexp: "^[# \t]*[Uu][Ss][Ee][Dd][Nn][Ss] "
# how does one specify case insensitive regexp in lineinfile?
line: "UseDNS no"
state: "present"
create: true
insertafter: EOF
notify:
- sshd restart

Ansible uses Python re module. You can use inline modifiers, such as (?ism) in your pattern. Use the i for case-insensitive matching:
regexp: "(?i)^[# \t]*usedns "
Inline modifiers apply to the part of the regular experssion to the right of the modifier, and can be disabled with a - e.g. (?-i). This can be applied to implement case-insensitivity to only a part of a regular expression.
For example, the regex (?i)use(?-i)DNS should match useDNS and UseDNS, but not useDns or USEdns.

Related

Ansible "replace" regexp (one OR the other)

I'm trying to replace a value in a config file, using the replace module.
However, I was wondering if there is an OR function or similar.
Currently, I have the following play:
- name: Replace "DebugLevel" variable-value"
become: yes
replace:
path: /etc/zabbix/zabbix_proxy.conf
regexp: '^# DebugLevel=3'
replace: 'DebugLevel=3'
This play uncomments DebugLevel=3, but when the playbook is run a second time the replace wont work because the regex does not match (value already uncommeted).
I want to always replace the value even if DebugLevel=3 already was uncommented.
This will make any manual changes made by a person to be overwritten and the Ansible playbook sets it back to original config.
By creating a new play with a regex that is using the value that is already uncommented, I can accomplish this, but is there a shorter version by using an "OR" after the first regex value or something similar?
Example of what I mean:
- name: Replace "DebugLevel" variable-value"
become: yes
replace:
path: /etc/zabbix/zabbix_proxy.conf
regexp: '^# DebugLevel=3' OR '^DebugLevel=.*'
replace: 'DebugLevel=3'
if you want to use regex the or is |
- name: Replace "DebugLevel" variable-value"
replace:
path: /etc/zabbix/zabbix_proxy.conf
regexp: '^# DebugLevel=3|^DebugLevel=.*'
replace: 'DebugLevel=3'
If the configuration file should contain every time a certain debug level you could probably declare just that the line exists independent of comment and value. To do so
- name: Replace "DebugLevel" variable-value"
lineinfile:
path: /etc/zabbix/zabbix_proxy.conf
regexp: 'DebugLevel'
line: 'DebugLevel=3'
It will make sure that the debug level is set with the given value and active.
Documentation
lineinfile module – Manage lines in text files

How to update new hostname in a file using ansible?

I am using below code to replace old hostname with new one, it is working except for hostnames starting with numbers.(OLD_HOSTNAME and NEW_HOSTNAME are vars)
tasks:
- name: "Updating file"
replace:
name: /tmp/interfaces
backup: yes
regexp: '(\s+){{ OLD_HOSTNAME }}(\s+)'
replace: '\1{{ NEW_HOSTNAME }}\2'
If I replace \1 with \g<1>, the hostnames starting with numbers will also get placed. But as per the ansible doc, \1 is used ambiguously, and \g<1> used explicitly.
Question: Will this change impact any other format of hostname?
No, using the explicit form will not affect other hostname formats.
The reason why you have a problem when NEW_HOSTNAME begins with a number is that the replace string would become something like \123-server\2 if NEW_HOSTNAME was 23-server and there is no backreference \123. Using the explicit form preserves your original intent. In my example, replace would become \g<1>23-server\g<2>.

Ansible: Insert word in GRUB cmdline

I'd like to use Ansible's lineinfile or replace module in order to add the word splash to the cmdline in GRUB.
It should work for all the following examples:
Example 1:
Before: GRUB_CMDLINE_DEFAULT=""
After: GRUB_CMDLINE_DEFAULT="splash"
Example 2:
Before: GRUB_CMDLINE_DEFAULT="quiet"
After: GRUB_CMDLINE_DEFAULT="quiet splash"
Example 3:
Before: GRUB_CMDLINE_DEFAULT="quiet nomodeset"
After: GRUB_CMDLINE_DEFAULT="quiet nomodeset splash"
The post Ansible: insert a single word on an existing line in a file explained well how this could be done without quotes. However, I can't get it to insert the word within the quotes.
What is the required entry in the Ansible role or playbook in order to add the word splash to the cmdline as shown?
You can do this without a shell output, with 2 lineinfiles modules.
In your example you're searching for splash:
- name: check if splash is configured in the boot command
lineinfile:
backup: true
path: /etc/default/grub
regexp: '^GRUB_CMDLINE_LINUX=".*splash'
state: absent
check_mode: true
register: grub_cmdline_check
changed_when: false
- name: insert splash if missing
lineinfile:
backrefs: true
path: /etc/default/grub
regexp: "^(GRUB_CMDLINE_LINUX=\".*)\"$"
line: '\1 splash"'
when: grub_cmdline_check.found == 0
notify: update grub
The trick is to try to remove the line if we can find splash somewhere, but doing a check only check_mode: true. If the term was found (found > 0) then we don't need to update the line. If it's not found, it means we need to insert it. We append it at the end with the backrefs.
Inspired by Adam's answer, I use this one to enable IOMMU:
- name: Enable IOMMU
ansible.builtin.lineinfile:
path: /etc/default/grub
regexp: '^GRUB_CMDLINE_LINUX_DEFAULT="((:?(?!intel_iommu=on).)*?)"$'
line: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 intel_iommu=on"'
backup: true
backrefs: true
notify: update-grub
Please note I've had to set backrefs to true in order to \1 reference to work otherwise the captured group was not replaced.
Idempotency works fine as well.
EDIT: Please note this snippet only works with an Intel CPU and might to be updated to fit your platform.
A possible solution is the definition of two entries as follows:
- name: "Checking GRUB cmdline"
shell: "grep 'GRUB_CMDLINE_LINUX_DEFAULT=.*splash.*' /etc/default/grub"
register: grub_cfg_grep
changed_when: false
failed_when: false
- name: "Configuring GRUB cmdline"
replace:
path: '/etc/default/grub'
regexp: '^GRUB_CMDLINE_LINUX_DEFAULT="((\w.?)*)"$'
replace: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 splash"'
when: '"splash" not in grub_cfg_grep'
Explanation: We first check if the splash keyword is present in the required line using grep. Since grep gives a negative return code when a string is not found, we suppress the errors using failed_when: false. The output of grep is saved to the grub_cfg_grep variable.
Next, we bind the replace module to the condition that the keyword splash is in the standard output of grep. The regular expression takes the old content in the quotes and adds the splash keyword behind it.
Note: In the case of an empty string before the execution, the result reads " splash" (with a space in front) but it is still a valid cmdline.
The difficulty is this line in the replace module page: "It is up to the user to maintain idempotence by ensuring that the same pattern would never match any replacements made."https://docs.ansible.com/ansible/latest/modules/replace_module.html#id4 It's easy to insert the item but actually quite tricky to make it idempotent, so the target file doesn't grow every time you run the task.
I found a way to do it in one shot with the replace module. You should be able to adapt this. My task checks the GRUB_CMDLINE_LINUX_DEFAULT line for "vt.default_red" and inserts some colour codes if not found.
My method was to copy-and-paste various nearly-there examples into the regex tester website and fiddle until it worked. I still don't grok the result, but it worked in my tests at https://www.regextester.com/ and it works in my playbook.
One problem I had was that Ansible's regex implementation apparently doesn't support conditionals, which gave me odd errors for a while.
- name: colours | configured grub command
replace:
path: /etc/default/grub
regexp: '^GRUB_CMDLINE_LINUX_DEFAULT="((:?(?!vt\.default_red).)*?)"$'
replace: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 vt.default_red=0xee,..."'
The regex matches the literal string ("GRUB_CMDLINE_LINUX_DEFAULT=" and a double quote mark) at the start and the double quote mark at the end. Deconstructing the rest...
( - open capture group #1 (creates backref #1)
(:? - open a non-capturing group (not sure what the question mark is here)
(?! - negative lookahead (ie. don't match if the following string comes next)
vt\.default_red - the string to look for, literal dot is escaped
) - close negative lookahead
.) - match a single char (why?) and close the non-capturing group
* - try to match the non-capturing group zero or more times
? - ... lazily (ie. get the smallest possible match)
) - close capture group #1
What about doing this in Ansible, use perl to address your need.
- name: Change items in the file
ansible.builtin.command:
command: perl -i pe 's/DEFAULT="/DEFAULT="splash"/'
Another way of looking at it. This is an old conversation, but it is still relevant.

Ansible lineinfile duplication using insertafter

I am trying to add an entry into my /etc/hosts file using ansibles lineinfile. I want the logic to be if it finds the entry 127.0.0.1 mysite.local then do nothing otherwise insert it after the line 127.0.1.1
127.0.0.1 localhost
127.0.1.1 mypc
127.0.0.1 mysite.local
I have the insert after part working but it appears the actual regex search is failing to find the existing entry so I keep getting duplication of the insertion of 127.0.0.1 mysite.local
The docs do say;
When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement by line to ensure idempotence.
But I'm not sure how that applies to my regex. Currently my play is;
- name: Add the site to hosts
lineinfile:
path: /etc/hosts
# Escape special chars
regex: "^{{ domain|regex_escape() }}"
line: "127.0.0.1 {{ domain }}"
insertafter: '127\.0\.1\.1'
firstmatch: yes
become: yes
where domain is mysite.local.
I have looked at this answer but I'm pretty sure I cannot use backrefs since the docs state;
This flag changes the operation of the module slightly; insertbefore and insertafter will be ignored, and if the regexp doesn't match anywhere in the file, the file will be left unchanged.
I have tried;
regex: '127\.0\.0\.1\s+?{{ domain|regex_escape() }}'
With no luck either
It seems that firstmatch: yes was breaking things. It work for me with following task (I replaced space with tab for fancy look but spaces work as well):
- name: Add the site to hosts
lineinfile:
path: /etc/hosts
# Escape special chars
regexp: "{{ domain|regex_escape() }}"
line: "127.0.0.1{{ '\t' }}{{ domain }}"
insertafter: '127\.0\.1\.1'
According to this link, lineinfile scans the file and applies the regex one line at a time, meaning you cannot use a regex that looks through the whole file. I am unfamiliar with the lineinfile tool, but if you can use the "replace" tool used in the link above then you can use the following Python regex to match as you need:
\A((?:(?!127\.0\.0\.1\s)[\s\S])*?)(?:\Z|127\.0\.0\.1\s+(?!{{ domain|regex_escape() }})\S+\n|(127\.0\.1\.1\s+\S+(?![\s\S]*\n127\.0\.0\.1\s)\n))
With the substitution: "\1\2127.0.0.1 {{ domain }}\n"
The non-capturing group handles three distinct cases:
Case 1: 127.0.1.1 and 127.0.0.1 don't exist so insert at end
Case 2: 127.0.0.1 exists with a different host so replace the entry
Case 3: 127.0.1.1 exists so insert after it
It is the second case that tackles idempotence by avoiding matching an entry for "127.0.0.1" if one already exists.
The doc says:
insertafter: ... If regular expressions are passed to both regexp and insertafter, insertafter is only honored if no match for regexp is found.
The regex in the task expands to
regex: ^mysite\.local
This regex is not found because there is no line that begins with "mysite.local". Hence insertafter is honored and "line" is inserted after 127.0.1.1 .

regex for Ansible replace module?

I'm trying to disable my default /etc/yum.repos.d/*.repo files by setting the line
enabled=1
to
enabled=0
Easy enough with Ansible's replace module. However, some *.repo files have
enabled=1
while some have
enabled = 1
that is, some have no space on each side of the = sign, while others have. What should the regex value be in this task to handle both?
- name: Disable the existing CentOS repos in /etc/yum.repos.d
replace:
dest: /etc/yum.repos.d/{{ item }}
regexp: "enabled = 1" ####### What should this be?? ########
replace: "enabled=0"
with_items:
- CentOS-Base.repo
- CentOS-fasttrack.repo
- CentOS-Vault.repo
- CentOS-CR.repo
The regexp parameter in the replace module uses Python regular expressions. All you need to do is add zero or more qualifiers (*) for whitespace (\s) between the equals sign.
- name: Disable the existing CentOS repos in /etc/yum.repos.d
replace:
dest: /etc/yum.repos.d/{{ item }}
regexp: 'enabled(\s)*=(\s)*1'
replace: "enabled=0"
with_items:
- CentOS-Base.repo
- CentOS-fasttrack.repo
- CentOS-Vault.repo
- CentOS-CR.repo