Замена строк/слов в файле через ansible в Unix/Linux
Сейчас, стало распространено использование автоматизации, и ansible хорошо справляется с некоторыми задачами, например — замена строк/слов в файлах. Для начала, установим данную службу:
Установка и настройка Ansible в Unix/Linux
Замена строк/слов в файле через ansible в Unix/Linux
При работе с ansible и файлами (конфигурационные файлы — как пример), очень просто найти и заменить нужную строку или слово чем скопировать файл на компьютер и редактировать его. В ансибле, имеется модуль lineinfile, который предоставляет функциональные возможности наподобие «sed». Конечно, можно использовать и утилиту «для джедаев» — sed, но если нужно заменить на разных серверах одну и туже строку во многих файлах — то для этой задачи хорошо подойдет ansible.
Ну а сейчас, я покажу как можно это сделать с помощью playbook-а:
- name: uncomment a line
lineinfile: dest=/etc/lighttpd/lighttpd.conf
regexp='^ include "mod_fastc gi.conf"'
insertafter='^# include "mod_fastc gi.conf"'
line=' include "mod_fastc gi.conf"'
state=present
Ниже представляет собой простой набор различных вариантов использования модуля lineinfile. Мне потребовалось некоторое время, чтобы выяснить, как работает данный модуль (InsertAfter и InsertBefore с BOF/EOF).
Создадим тестовый файл через ансибль для тестирования работы lineinfile модуля:
- name: create a complete empty file command: /usr/bin/touch /home/vagrant/tmp.txt
Чтобы создать новую, пустую строку — используем:
- name: create a new file with lineinfile
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^' line=''
state=present
create=True
Данный плейбук, создаст пустую строку. Сейчас, я покажу как можно ее заменить на что-то другое:
- name: add a string to the new file
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^'
line='This works'
state=present
Добавим 5 строк в файл:
- name: add a multiline string to the file and delete the string from before
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^'
line='#This is a 1st comment\n#The 2d comment\n#The 3d comment\n#The 4th a comment\n#The last comment'
state=present
Получаем:
$ cat tmp.txt #This is a 1st comment #The 2d comment #The 3d comment #The 4th a comment #The last comment
Сейчас, я покажу как можно вставить строку, после заданной ( например после 1-й):
- name: add a single line, in this case the same as the comment but uncommented
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^This'
insertafter='^#This'
line='This is a 1st comment'
state=present
Получаем:
$ cat tmp.txt #This is a 1st comment This is a 1st comment #The 2d comment #The 3d comment #The 4th a comment #The last comment
Удаляем определенную строку:
- name: remove the line '#This is a 1st comment'
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^#This is a 1st comment'
state=absent
Вывод:
$ cat tmp.txt This is a 1st comment #The 2d comment #The 3d comment #The 4th a comment #The last comment
Заменить строку ( в моем случае — это первая):
- name: change a str
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^This'
insertbefore=BOF
line='This is no longer a comment'
Вот что вышло:
$ cat tmp.txt This is no longer a comment #The 2d comment #The 3d comment #The 4th a comment #The last comment
Вставить строку перед указанной:
- name: add a new string before the match
lineinfile: dest=/home/vagrant/tmp.txt
regexp='^The 3d comment'
insertbefore='^#The 3d comment'
line='Another The 3d comment'
Смотрим что получилось:
$ cat tmp.txt This is no longer a comment #The 2d comment Another The 3d comment #The 3d comment #The 4th a comment #The last comment
И напоследок, вставляем строку в самый конец файла:
- name: add a new string at the end of the file
lineinfile: dest=/home/vagrant/tmp.txt
regexp=''
insertafter=EOF
line='The latest entry'
Получаем:
$ cat tmp.txt This is no longer a comment #The 2d comment Another The 3d comment #The 3d comment #The 4th a comment The latest entry
Как-то так. У меня на этом все, статья «Замена строк/слов в файле через ansible в Unix/Linux» завершена. Появятся идеи для примеров, добавлю еще 🙂