����C %# , #&')*)-0-(0%()(��C (((((((((((((((((((((((((((((((((((((((((((((((((((����"�������@�@�hC��}!���Ѱ��<"� 9iׂIIIHk�+?�c?��*Y�����!�du)b�T�9вU�$8G��I.�澬��D���Sq� q�}.<��Z�l�V!X� *x�-�\����t3i�Ũ�sNv71�ƛ\��z|t�L���$�����*f��kʮ��7�H;���~F%�'3�@�H�q�` 9mOL����/x@ @��G
d�8F�ه��Ka�Kdr�Fh.�]y4 JЛ��]�K�B�E$��$ $ �PR�����G�]��u�i$�$���'! "#031���C/Td=S�Q?���62Ccj{ ����̏d�چ/c�V�`��Wz͈�{Y`�d�h�L �]OB���l���o���mr���n��s-ڗEZ��N�_��1%b���H�ϣ������V�7):�ӷ)�}�~�(�;�!�b1�5K��[E�vϻ>��q.%� ���O���(�c�#x�$�'+��`٥v��v(�����M�"�v��B��.�a ���T�~�ϕ�hy(6nݱl��1yNɓx�������AR�8�rqv1.cS�+��_���&@�� �u�M�5Ĉ�Xm���eL�X�q��y#�9]�c�}ɄL��d�eJ몓���I1T�d��CaM�$��T�,�X �bʭ�!�%F5��X1x#���!�q��\��F��2��&Rq���C�ol~�̱�.0ϦL�d�`.������ ���m{�Y~k{C��}bv�;U��c<�r�~ɜs�1�j��]W�l��*նCr��Q�N9�-������d��E؛��nF��eړ�8(q��5UgRȱGTA��*������̆��V�珰����ezN��h�U]�T�FG�^���<��ay�,!���5.� �u�bΚ�V�J%��m�Dxn'�����6�@BPa�`��Hts� �ɮ���Ŏ�Zɬ��%B�X��d5Z���hC}�䅸�p+ k=��ʒ(�aՏFG&�%@/�{+�Yu+�ȣGѩ"O%�|vȲxF>�N(��ou�h6 &Y5��8�7�E$-��']n,@TD\��+���Ry�U��U^�Q,f>��1�����q��f��U��� ����F���ڥ��>I�����fNUw�u��#OMMQ6� N�*��_�� k� ����rS��`���1�:��!�F'<+� � b?O��2 !Q12A��� "3a������#$��?�,�7�!`yǮ(�1�6w��a���� �F�#��?*"s���v>��Ⱥ����f�v��͑���s����������]Gn��S ���ȥpG ы�E�g�)Z���x�rY�q�]�@f�_܃�pչEڎّC ����Ŝ*/ �h�O�Sv�و\��5��U��y��|o�Hm2C�S�BW����)��5��{T��W���=o*RA��<����L0g4{��쁢�ep�rw�8��7��U���t<Ԍѻ7�fGf�k}���Ê�㛆Gռz�Q@��{C��'G��8�!�S$�j��x���|���צV<��,����u�k�uu�rM�f�_dϣi ߫�ԟn�!K����mxu�=�槻�'j�X�����������%!A "1QR#Br��?�R:��R�n�b[�II?#��6<:�$gN����lGNlrr��dעMMn`ɿy�,�%B�e�W��dVS��r���� %�tT��(�ɷ��S�]�O]#�_LEMHN�M���kv���~X���O6�U�V_�����b���J�t�774����D!1AQa"2q�#3BRb����0���� 4CSr����cst�����?��^q���7�dG�U�"p��moz��'��n_x���唹e������<6��O�t���R>k��s=�Cr���e�?�i��� ����/��ں$be���o`ޮ�GHy�;fNAl�8��.�\�S������"���a�úF�YvNk�-*`v�k�ʈ2f�EE��Wa�,� �fF^#�;��[9��^~������Y$:0#W3������Z*���I�Z�ڹ�k�n--9=��G��;7F)m{T�Ɇ��=�����Ȭ5�5�B�aڞ5M����#m�5Ʀ��m�8��+Hh���$�}�:&�e�Q�[;i]С�:�:��o����$<~��5RB�?�s3�5�r��O��ֿ�w�P/��̅���(�Z6�R>)��N��4�!ʊ�wz�-�r�w+�yk���q�1�bKhƸ�4N�Ӑ�X����Q��_��})�+e1�5��n��q?��[�^�9�<�z3Fsi�8�'�)9p)�{��RP�Z+�*��p(aY��V����6l�g�9��;���d�u���Nt@�3�sTwzaŇ�GT�b�H��(#��*zc�������9K�b1�����t����Ê��
�Z?g�iD���H�R���B���^M����v���O���L�D,'d�q�C�P�����$Δ��U�֟֊=�s��F�$��J�ދZ?�N��������A�N�WP��,�� �¦�&;�x��dup�����i���Ipd���;�Dž!��ֿѮAb%�u��}j��-p��>I�[�N�bi����G�'�;4w�m]H�]����#LӘNN��R��������s�.]��en��-�8e��Ps����Q��;���ț�E�ݫ���7��g�_L��W��EZ:/��I���a�g�n�ܤ��iٹ���ŷ�T���H~i�a�����֎�~KV������ A-2m]�F"�m�9-Zbǰ�״ @����~�4�N�[�Uxč�tl>������u#r�gѐ�3���;M9�<�J�����1�vfL8����1�P�HgP�Xv��������{����O�}�n��KQ؋����7<�l�fey<�}�>�bX���4<`Y7���si��V)�s�:�{�rO�h�z �@4VW�B���&�������ɡob܋�F��4>y�s�fXWS�N�O$�,.u:�ԫ��g�yao4��$h��D#��ٸf^kh�7�#1Z�֥&���*�v-��;bޭ����Q�����h�ow�y]�ه.+�7�M�ⴻ �JY��g�f�i3q��KC��3�¹�?5�Z.N��^Z w���KF͂���7��ރ۞��wj��T�J.�q��\Sv1U����R��욽&�N����pЖ`�`у��m`v�n#z��4��>e��V�`'���h�����'�j�AҔ�-�4:H���n]9�h<��n����U�6m��2c�E�1/�Y�%���I��~ʏ�|VBƟ@����;�������%�M9M���}��1�D��d����%g���O��]��у&�r��f�7�uܲ���(!1AQaq�������0� ���?!��*��@)�Je�G��j��{�['��v+���������)���(�/����д%젍Z��kk�Lu�Rm���j.c���@Z� V�J��d��j���h6���2AO�� a;oBu���H�=���nK�W8�B�ɰ�u?��бأm,�sr����|����8˨i��qI2tZ�ۄJP��XE��������zޔj~]UMu����zv!����N�&�1�Y��zJ�ՠ��\p��o'ሸ�C؊Y��TD"HM5�Ъ��i߯a���F����A)�����ڮ����z�E���@�hg�֝8�1jk��\�M�3�8ܢ�� ������s�7����N}�ޭ������GN�Bc���L pk�;�J�δ3�e�iU�gAYW]\�>�GyگQ=��f�KA;T�a`eM+Q �� �Ln���̌]GM�����<Ħ�j���H��N�M�x�}aX{̣S� ��ԅ��n�MA�S�r�(����(�L��zo9���.�;
�ӳf������`Ӕ٢3�� IW��\9~_���saa�\ԊW�ܭX:���ӆ�38�ty*����N�qP����BI�Y��jE��>DP�!�R%-��4��'�皺;��~J�!�7m���X��h�P!曭���$�\�AYj�.lC��4��+�jD�dgC0-*���|��`ZD�+л�C"��)��s��8Kq�pq���Ms��4� ��7\U`�.��[Ey8��AH!/��,���(:M -�T䓥�~O�4-���Ԓn��}HDN7���K���$�_Ԕ䚞`�R�hB�_aX?4V��ŗ�@ه�u�a�;�{PcT+�������7YBo�?��r-ͩ{�ĎA�� ����˼n��M286��G���1���V�˜Jв"l��V5���5�C]h���̊�A���%� �'p���Ԃ���Ր��9=�d�=�e�{�'<3�_ �:^�~��4�(�n�-C�s��5m![�jmIqU�~�Tw8��`���p�H8�u�Д l m�aP�0�������9y����CM��F1G糞�.�U~�������FC�{�!e(Y�:���P����7~;�L�N^{�1r�\���ԬG(���0d�ÏO�qK�Z�⑼�T�{ 2��s��Kd�Տ?mMQ��=���6�7�i�����H+����9��d��=��;�QؤH8n�Lb�D��yS%�(�{b���Cu���p�t#C���$A"�H{���jqᶯ�:�n=E����hH�`�!�m��MA������?�v6���+MԿ⟚qK�i�D�*Q5��CZ���2�|]�:Xd+�t�:o@��M��� :�32��b����[\5=�ֵ7])�|t��Ϻ����w�B�ń�e���!`�:��I,��9:����j@/a 8����+<�u�(T^ۺ~��2oE�B�%b)��z��ݳځ�)��i�j��&��Fi`qr��w���7�@��P�� �3Z&<�m�S�C����7t�T����ƴ�q~J�e�r6�Z]�rL���ه�E17'�x���+[�ܜTc6�/�����W�`�qpMJ���N5^����x�}{l�Fm������1�oZ\�����/d�/6� �uӸ�0elXuX;M��$M�}mB��������Z%e���3f�js����O�J~2�z�86�*PB��v�Ν��e-��.�/��L�O����2����9���4}|��T5M���hÐ7�F*��l+y0����:|��=k[�d�;|�ԉe�=w�<��õ�<��'!1AQaq����� ������?��5����)�(���+>v����6&{���Ǹ@����M�����v��iA 6T'�w��h�s �E}�x��G&'g�� J~1q�f�f���&��q˘���-���vYm
�/i1 �I��6��u,)�#�,����l}*&`�$�ͬe�%�w3�x�Ѥ�Xc�D��执g�峕�5B/�|$��=���%8 a��2.l� c�@G� �\�/x[өq�]�v5?�����N|�!���\��,>��{�"r�/��?��&!1QAa�� ��ᑱ����?ĊD�肭�� nv@�yޝ (�����I ����U - ���b�m�E>,��1v!�d�&�� ���&�檔�5D�&0P��Ԕ�͒@Z��:E"� Q��`>PH:~�O�����P�3W��@hM��k�U��\�O��R�������5ʄ�,��f�|��r���}јxo)�"+h�QK���/��0�`�5�{M~�� ���'!1AQaq���0 �������?�?�k��#^�~�G��#V,������#Z�1'ܤ����������~p�O%O�O�\�q�`�~��}��E�Ű5 �輸�du����x\�$���s[�{T2t`B��gq�4Z]b� 㛪�3,(@����bAp�r)9:@|b�!r�g:N�^�Ʌ��� �x_�\��pm7I��0?>^k��������w���|.K�[sF@�]Gn*L �yO� le�P�.p��֍�j�S�=�ʨ�ןQF�"��5zʼn���k�*8�u" ����Fg��� �cSy�V������Ƈ��N��ؐ(�����48hV�A�ӎ^��^ ���jyB� ��p"�����y]�ļlU�(�7�U`3�pCGF'&yg������o��z������X��ν:�P"@�G@x[��o&MJ�$F.����hi w;}�/^͇q���n�mN�/�TQ���އ��O1\,}��bQ #¯^S!)��X���#GPȏ�t�� c^\��' }iIZ���a�)��������z��4͊�Ξy��48,��f���#�����KP!Jx�|w�ʆ�������������#��Z�������< �~K��r�p&qH/;�R���沽�+�E�R���~0v���V#ʀ�T��S(-ڝ��B�y�b�C�D������b��������8��~�= �Y�ͧ]��@n����M�k2�%�;�%,�r6�LR腻?^��;KŇ=�ք ���=`�ɥ��/����z�&�I{���#J��M���C��}�H9^UJ�,P ��pS����G�d69Ϭu���%"��ˢP��K�"k)��=��9� ����㇌,��Oli��Xzh� " � ������R��^�s����N�k��Q>�63(���� ��PQ�Py�����3����$f+W՛=4�ǁ`*��^��Eb�K�t�6��^��!�籷��ȭ��K{/;�L���p�x�����;a���Oلz�[�.NP4�]Gc�T�v����~sg'LED��]j��'�G�]�6rY����UPw�*O�İՋi�'8�۴�#g�Xx+=�eU6�R��c�"�u2��~�?n�y�;�u��3�'��6�f������b��߬M�$*��k&?6���*^1n����ێz)<��Gz� �����7����Y� ��ۃ)$A��2�L6� ե�H�<�r��#ʽ2��O��R���z�A��XW��@���������<�G� Ϥ�^�˓i�M�W���6 ��0��m){c�;ݧ�>R�a����}1�ٯ%�EY2�Q��Ep���$ ��E��qS��t#+x� *�h�UI��XM?�'//��a'�G�����q@���<��z��؟����cd��z�ˬT_u�Ѯ����&�z�k ��n ]�a%�py»�`Qd�xc������n�� ��*��oTd�;'j�<�!j���'�(~�ʹW�M� P�mȘ��@֨V+��R�`�$��`�+@��_[�kG����P���Zh9�R����&5b�v���Z���#p�&�Ա+��8�etZ7G���;��@"�e0���v7����?��z�?_���_�q1�T�"�p�ˎ/U 6_�B�>��0( ��}G#������Ȣ�p�� �9��;/& `�B&$�y��t(�*z�x���Ӕ������S�?Kȏ3���{p� b � ۍ-�z܈֦��6?<���ǬP�N�G �更� �6�/h�����0Z���������i�ua��e�*M'A� �x��v�q.>�F� oN{��Q���{gD��L��u��=|���O xN���d���q�8(��E�Uu��,��O� t�DJ ����;��G����e���C��VYZ�� ���T4{����(�Ӳ'c�t�f��w�c�jr�e�m �#7,�6��B�E4Q�P�.P�(&��^{9H-�m�o ��q�g1���=��>p�)/"p0!4�mS6ú�FN���h��D �)��XdT �FؤZ⸚�k���H�c8v� <���u�P�Հ���:��_�EN��|�ӛ��u?-�/�o�Lhk�ܸ�S�;�Rī�����T"�N����M��px7<�� j�$��`�Y)Pjh 5` K�Qf�4�C�bX"�D���;HD�Z�9R b�F)�UA����v�#��HD�!{������>I� �`�ԁ i�4�)t*�ç�Le�_���>ru�GEQg��ǔct��ō0��l6v���d�� ��GG8���v^�|�#JyZPSO�� Y�CuAߐ�"�x���OfHF@�K�V�!少Eҕ]h� ��[���)��.q����*0I<8��^�6�}p��^tho���ig�i����DK���p,��2�3�I��5����쓄OY�6s7Qs�Ow^�w�J/�A➰������0������g(Մ��y��Kԇ����QS��?H���w�X�=��ҞX�~���Q=�'���p?7�@g�~�G�}�r��g�T?���
One Hat Cyber Team
star
One Hat Cyber Team
star
Your IP :
3.135.229.106
Server IP :
50.6.170.23
Server :
Linux 50-6-170-23.bluehost.com 5.14.0-503.35.1.el9_5.x86_64 #1 SMP PREEMPT_DYNAMIC Fri Apr 4 05:23:43 EDT 2025 x86_64
Server Software :
Apache
PHP Version :
8.2.28
Buat File
|
Buat Folder
Eksekusi
Dir :
~
/
usr
/
lib
/
python3.9
/
site-packages
/
ansible
/
modules
/
View File Name :
lineinfile.py
# -*- coding: utf-8 -*- # Copyright: (c) 2012, Daniel Hokka Zakrisson <daniel@hozac.com> # Copyright: (c) 2014, Ahti Kitsik <ak@ahtik.com> # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: lineinfile short_description: Manage lines in text files description: - This module ensures a particular line is in a file, or replace an existing line using a back-referenced regular expression. - This is primarily useful when you want to change a single line in a file only. - See the M(ansible.builtin.replace) module if you want to change multiple, similar lines or check M(ansible.builtin.blockinfile) if you want to insert/update/remove a block of lines in a file. For other cases, see the M(ansible.builtin.copy) or M(ansible.builtin.template) modules. version_added: "0.7" options: path: description: - The file to modify. - Before Ansible 2.3 this option was only usable as I(dest), I(destfile) and I(name). type: path required: true aliases: [ dest, destfile, name ] regexp: description: - The regular expression to look for in every line of the file. - For C(state=present), the pattern to replace if found. Only the last line found will be replaced. - For C(state=absent), the pattern of the line(s) to remove. - If the regular expression is not matched, the line will be added to the file in keeping with C(insertbefore) or C(insertafter) settings. - When modifying a line the regexp should typically match both the initial state of the line as well as its state after replacement by C(line) to ensure idempotence. - Uses Python regular expressions. See U(https://docs.python.org/3/library/re.html). type: str aliases: [ regex ] version_added: '1.7' search_string: description: - The literal string to look for in every line of the file. This does not have to match the entire line. - For C(state=present), the line to replace if the string is found in the file. Only the last line found will be replaced. - For C(state=absent), the line(s) to remove if the string is in the line. - If the literal expression is not matched, the line will be added to the file in keeping with C(insertbefore) or C(insertafter) settings. - Mutually exclusive with C(backrefs) and C(regexp). type: str version_added: '2.11' state: description: - Whether the line should be there or not. type: str choices: [ absent, present ] default: present line: description: - The line to insert/replace into the file. - Required for C(state=present). - If C(backrefs) is set, may contain backreferences that will get expanded with the C(regexp) capture groups if the regexp matches. type: str aliases: [ value ] backrefs: description: - Used with C(state=present). - If set, C(line) can contain backreferences (both positional and named) that will get populated if the C(regexp) matches. - This parameter changes the operation of the module slightly; C(insertbefore) and C(insertafter) will be ignored, and if the C(regexp) does not match anywhere in the file, the file will be left unchanged. - If the C(regexp) does match, the last matching line will be replaced by the expanded line parameter. - Mutually exclusive with C(search_string). type: bool default: no version_added: "1.1" insertafter: description: - Used with C(state=present). - If specified, the line will be inserted after the last match of specified regular expression. - If the first match is required, use(firstmatch=yes). - A special value is available; C(EOF) for inserting the line at the end of the file. - If specified regular expression has no matches, EOF will be used instead. - If C(insertbefore) is set, default value C(EOF) will be ignored. - If regular expressions are passed to both C(regexp) and C(insertafter), C(insertafter) is only honored if no match for C(regexp) is found. - May not be used with C(backrefs) or C(insertbefore). type: str choices: [ EOF, '*regex*' ] default: EOF insertbefore: description: - Used with C(state=present). - If specified, the line will be inserted before the last match of specified regular expression. - If the first match is required, use C(firstmatch=yes). - A value is available; C(BOF) for inserting the line at the beginning of the file. - If specified regular expression has no matches, the line will be inserted at the end of the file. - If regular expressions are passed to both C(regexp) and C(insertbefore), C(insertbefore) is only honored if no match for C(regexp) is found. - May not be used with C(backrefs) or C(insertafter). type: str choices: [ BOF, '*regex*' ] version_added: "1.1" create: description: - Used with C(state=present). - If specified, the file will be created if it does not already exist. - By default it will fail if the file is missing. type: bool default: no backup: description: - Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. type: bool default: no firstmatch: description: - Used with C(insertafter) or C(insertbefore). - If set, C(insertafter) and C(insertbefore) will work with the first line that matches the given regular expression. type: bool default: no version_added: "2.5" others: description: - All arguments accepted by the M(ansible.builtin.file) module also work here. type: str extends_documentation_fragment: - action_common_attributes - action_common_attributes.files - files - validate attributes: check_mode: support: full diff_mode: support: full platform: platforms: posix safe_file_operations: support: full vault: support: none notes: - As of Ansible 2.3, the I(dest) option has been changed to I(path) as default, but I(dest) still works as well. seealso: - module: ansible.builtin.blockinfile - module: ansible.builtin.copy - module: ansible.builtin.file - module: ansible.builtin.replace - module: ansible.builtin.template - module: community.windows.win_lineinfile author: - Daniel Hokka Zakrissoni (@dhozac) - Ahti Kitsik (@ahtik) - Jose Angel Munoz (@imjoseangel) ''' EXAMPLES = r''' # NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path' - name: Ensure SELinux is set to enforcing mode ansible.builtin.lineinfile: path: /etc/selinux/config regexp: '^SELINUX=' line: SELINUX=enforcing - name: Make sure group wheel is not in the sudoers configuration ansible.builtin.lineinfile: path: /etc/sudoers state: absent regexp: '^%wheel' - name: Replace a localhost entry with our own ansible.builtin.lineinfile: path: /etc/hosts regexp: '^127\.0\.0\.1' line: 127.0.0.1 localhost owner: root group: root mode: '0644' - name: Replace a localhost entry searching for a literal string to avoid escaping ansible.builtin.lineinfile: path: /etc/hosts search_string: '127.0.0.1' line: 127.0.0.1 localhost owner: root group: root mode: '0644' - name: Ensure the default Apache port is 8080 ansible.builtin.lineinfile: path: /etc/httpd/conf/httpd.conf regexp: '^Listen ' insertafter: '^#Listen ' line: Listen 8080 - name: Ensure php extension matches new pattern ansible.builtin.lineinfile: path: /etc/httpd/conf/httpd.conf search_string: '<FilesMatch ".php[45]?$">' insertafter: '^\t<Location \/>\n' line: ' <FilesMatch ".php[34]?$">' - name: Ensure we have our own comment added to /etc/services ansible.builtin.lineinfile: path: /etc/services regexp: '^# port for http' insertbefore: '^www.*80/tcp' line: '# port for http by default' - name: Add a line to a file if the file does not exist, without passing regexp ansible.builtin.lineinfile: path: /tmp/testfile line: 192.168.1.99 foo.lab.net foo create: yes # NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes - name: Ensure the JBoss memory settings are exactly as needed ansible.builtin.lineinfile: path: /opt/jboss-as/bin/standalone.conf regexp: '^(.*)Xms(\d+)m(.*)$' line: '\1Xms${xms}m\3' backrefs: yes # NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs. - name: Validate the sudoers file before saving ansible.builtin.lineinfile: path: /etc/sudoers state: present regexp: '^%ADMIN ALL=' line: '%ADMIN ALL=(ALL) NOPASSWD: ALL' validate: /usr/sbin/visudo -cf %s # See https://docs.python.org/3/library/re.html for further details on syntax - name: Use backrefs with alternative group syntax to avoid conflicts with variable values ansible.builtin.lineinfile: path: /tmp/config regexp: ^(host=).* line: \g<1>{{ hostname }} backrefs: yes ''' RETURN = r'''#''' import os import re import tempfile # import module snippets from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native, to_text def write_changes(module, b_lines, dest): tmpfd, tmpfile = tempfile.mkstemp(dir=module.tmpdir) with os.fdopen(tmpfd, 'wb') as f: f.writelines(b_lines) validate = module.params.get('validate', None) valid = not validate if validate: if "%s" not in validate: module.fail_json(msg="validate must contain %%s: %s" % (validate)) (rc, out, err) = module.run_command(to_bytes(validate % tmpfile, errors='surrogate_or_strict')) valid = rc == 0 if rc != 0: module.fail_json(msg='failed to validate: ' 'rc:%s error:%s' % (rc, err)) if valid: module.atomic_move(tmpfile, to_native(os.path.realpath(to_bytes(dest, errors='surrogate_or_strict')), errors='surrogate_or_strict'), unsafe_writes=module.params['unsafe_writes']) def check_file_attrs(module, changed, message, diff): file_args = module.load_file_common_arguments(module.params) if module.set_fs_attributes_if_different(file_args, False, diff=diff): if changed: message += " and " changed = True message += "ownership, perms or SE linux context changed" return message, changed def present(module, dest, regexp, search_string, line, insertafter, insertbefore, create, backup, backrefs, firstmatch): diff = {'before': '', 'after': '', 'before_header': '%s (content)' % dest, 'after_header': '%s (content)' % dest} b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): if not create: module.fail_json(rc=257, msg='Destination %s does not exist !' % dest) b_destpath = os.path.dirname(b_dest) if b_destpath and not os.path.exists(b_destpath) and not module.check_mode: try: os.makedirs(b_destpath) except Exception as e: module.fail_json(msg='Error creating %s (%s)' % (to_text(b_destpath), to_text(e))) b_lines = [] else: with open(b_dest, 'rb') as f: b_lines = f.readlines() if module._diff: diff['before'] = to_native(b''.join(b_lines)) if regexp is not None: bre_m = re.compile(to_bytes(regexp, errors='surrogate_or_strict')) if insertafter not in (None, 'BOF', 'EOF'): bre_ins = re.compile(to_bytes(insertafter, errors='surrogate_or_strict')) elif insertbefore not in (None, 'BOF'): bre_ins = re.compile(to_bytes(insertbefore, errors='surrogate_or_strict')) else: bre_ins = None # index[0] is the line num where regexp has been found # index[1] is the line num where insertafter/insertbefore has been found index = [-1, -1] match = None exact_line_match = False b_line = to_bytes(line, errors='surrogate_or_strict') # The module's doc says # "If regular expressions are passed to both regexp and # insertafter, insertafter is only honored if no match for regexp is found." # Therefore: # 1. regexp or search_string was found -> ignore insertafter, replace the founded line # 2. regexp or search_string was not found -> insert the line after 'insertafter' or 'insertbefore' line # Given the above: # 1. First check that there is no match for regexp: if regexp is not None: for lineno, b_cur_line in enumerate(b_lines): match_found = bre_m.search(b_cur_line) if match_found: index[0] = lineno match = match_found if firstmatch: break # 2. Second check that there is no match for search_string: if search_string is not None: for lineno, b_cur_line in enumerate(b_lines): match_found = to_bytes(search_string, errors='surrogate_or_strict') in b_cur_line if match_found: index[0] = lineno match = match_found if firstmatch: break # 3. When no match found on the previous step, # parse for searching insertafter/insertbefore: if not match: for lineno, b_cur_line in enumerate(b_lines): if b_line == b_cur_line.rstrip(b'\r\n'): index[0] = lineno exact_line_match = True elif bre_ins is not None and bre_ins.search(b_cur_line): if insertafter: # + 1 for the next line index[1] = lineno + 1 if firstmatch: break if insertbefore: # index[1] for the previous line index[1] = lineno if firstmatch: break msg = '' changed = False b_linesep = to_bytes(os.linesep, errors='surrogate_or_strict') # Exact line or Regexp matched a line in the file if index[0] != -1: if backrefs and match: b_new_line = match.expand(b_line) else: # Don't do backref expansion if not asked. b_new_line = b_line if not b_new_line.endswith(b_linesep): b_new_line += b_linesep # If no regexp or search_string was given and no line match is found anywhere in the file, # insert the line appropriately if using insertbefore or insertafter if (regexp, search_string, match) == (None, None, None) and not exact_line_match: # Insert lines if insertafter and insertafter != 'EOF': # Ensure there is a line separator after the found string # at the end of the file. if b_lines and not b_lines[-1][-1:] in (b'\n', b'\r'): b_lines[-1] = b_lines[-1] + b_linesep # If the line to insert after is at the end of the file # use the appropriate index value. if len(b_lines) == index[1]: if b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[1]].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif insertbefore and insertbefore != 'BOF': # If the line to insert before is at the beginning of the file # use the appropriate index value. if index[1] <= 0: if b_lines[index[1]].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True elif b_lines[index[0]] != b_new_line: b_lines[index[0]] = b_new_line msg = 'line replaced' changed = True elif backrefs: # Do absolutely nothing, since it's not safe generating the line # without the regexp matching to populate the backrefs. pass # Add it to the beginning of the file elif insertbefore == 'BOF' or insertafter == 'BOF': b_lines.insert(0, b_line + b_linesep) msg = 'line added' changed = True # Add it to the end of the file if requested or # if insertafter/insertbefore didn't match anything # (so default behaviour is to add at the end) elif insertafter == 'EOF' or index[1] == -1: # If the file is not empty then ensure there's a newline before the added line if b_lines and not b_lines[-1][-1:] in (b'\n', b'\r'): b_lines.append(b_linesep) b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif insertafter and index[1] != -1: # Don't insert the line if it already matches at the index. # If the line to insert after is at the end of the file use the appropriate index value. if len(b_lines) == index[1]: if b_lines[index[1] - 1].rstrip(b'\r\n') != b_line: b_lines.append(b_line + b_linesep) msg = 'line added' changed = True elif b_line != b_lines[index[1]].rstrip(b'\n\r'): b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True # insert matched, but not the regexp or search_string else: b_lines.insert(index[1], b_line + b_linesep) msg = 'line added' changed = True if module._diff: diff['after'] = to_native(b''.join(b_lines)) backupdest = "" if changed and not module.check_mode: if backup and os.path.exists(b_dest): backupdest = module.backup_local(dest) write_changes(module, b_lines, dest) if module.check_mode and not os.path.exists(b_dest): module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=diff) attr_diff = {} msg, changed = check_file_attrs(module, changed, msg, attr_diff) attr_diff['before_header'] = '%s (file attributes)' % dest attr_diff['after_header'] = '%s (file attributes)' % dest difflist = [diff, attr_diff] module.exit_json(changed=changed, msg=msg, backup=backupdest, diff=difflist) def absent(module, dest, regexp, search_string, line, backup): b_dest = to_bytes(dest, errors='surrogate_or_strict') if not os.path.exists(b_dest): module.exit_json(changed=False, msg="file not present") msg = '' diff = {'before': '', 'after': '', 'before_header': '%s (content)' % dest, 'after_header': '%s (content)' % dest} with open(b_dest, 'rb') as f: b_lines = f.readlines() if module._diff: diff['before'] = to_native(b''.join(b_lines)) if regexp is not None: bre_c = re.compile(to_bytes(regexp, errors='surrogate_or_strict')) found = [] b_line = to_bytes(line, errors='surrogate_or_strict') def matcher(b_cur_line): if regexp is not None: match_found = bre_c.search(b_cur_line) elif search_string is not None: match_found = to_bytes(search_string, errors='surrogate_or_strict') in b_cur_line else: match_found = b_line == b_cur_line.rstrip(b'\r\n') if match_found: found.append(b_cur_line) return not match_found b_lines = [l for l in b_lines if matcher(l)] changed = len(found) > 0 if module._diff: diff['after'] = to_native(b''.join(b_lines)) backupdest = "" if changed and not module.check_mode: if backup: backupdest = module.backup_local(dest) write_changes(module, b_lines, dest) if changed: msg = "%s line(s) removed" % len(found) attr_diff = {} msg, changed = check_file_attrs(module, changed, msg, attr_diff) attr_diff['before_header'] = '%s (file attributes)' % dest attr_diff['after_header'] = '%s (file attributes)' % dest difflist = [diff, attr_diff] module.exit_json(changed=changed, found=len(found), msg=msg, backup=backupdest, diff=difflist) def main(): module = AnsibleModule( argument_spec=dict( path=dict(type='path', required=True, aliases=['dest', 'destfile', 'name']), state=dict(type='str', default='present', choices=['absent', 'present']), regexp=dict(type='str', aliases=['regex']), search_string=dict(type='str'), line=dict(type='str', aliases=['value']), insertafter=dict(type='str'), insertbefore=dict(type='str'), backrefs=dict(type='bool', default=False), create=dict(type='bool', default=False), backup=dict(type='bool', default=False), firstmatch=dict(type='bool', default=False), validate=dict(type='str'), ), mutually_exclusive=[ ['insertbefore', 'insertafter'], ['regexp', 'search_string'], ['backrefs', 'search_string']], add_file_common_args=True, supports_check_mode=True, ) params = module.params create = params['create'] backup = params['backup'] backrefs = params['backrefs'] path = params['path'] firstmatch = params['firstmatch'] regexp = params['regexp'] search_string = params['search_string'] line = params['line'] if '' in [regexp, search_string]: msg = ("The %s is an empty string, which will match every line in the file. " "This may have unintended consequences, such as replacing the last line in the file rather than appending.") param_name = 'search string' if regexp == '': param_name = 'regular expression' msg += " If this is desired, use '^' to match every line in the file and avoid this warning." module.warn(msg % param_name) b_path = to_bytes(path, errors='surrogate_or_strict') if os.path.isdir(b_path): module.fail_json(rc=256, msg='Path %s is a directory !' % path) if params['state'] == 'present': if backrefs and regexp is None: module.fail_json(msg='regexp is required with backrefs=true') if line is None: module.fail_json(msg='line is required with state=present') # Deal with the insertafter default value manually, to avoid errors # because of the mutually_exclusive mechanism. ins_bef, ins_aft = params['insertbefore'], params['insertafter'] if ins_bef is None and ins_aft is None: ins_aft = 'EOF' present(module, path, regexp, search_string, line, ins_aft, ins_bef, create, backup, backrefs, firstmatch) else: if (regexp, search_string, line) == (None, None, None): module.fail_json(msg='one of line, search_string, or regexp is required with state=absent') absent(module, path, regexp, search_string, line, backup) if __name__ == '__main__': main()