
    Vh[<                        d dl mZ dZdZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZmZ d Zd	 Zd
 Zedk(  r e        yy)    )annotationsa  
---
module: blockinfile
short_description: Insert/update/remove a text block surrounded by marker lines
version_added: '2.0'
description:
- This module will insert/update/remove a block of multi-line text surrounded by customizable marker lines.
author:
- Yaegashi Takeshi (@yaegashi)
options:
  path:
    description:
    - The file to modify.
    - Before Ansible 2.3 this option was only usable as O(dest), O(destfile) and O(name).
    type: path
    required: yes
    aliases: [ dest, destfile, name ]
  state:
    description:
    - Whether the block should be there or not.
    type: str
    choices: [ absent, present ]
    default: present
  marker:
    description:
    - The marker line template.
    - C({mark}) will be replaced with the values in O(marker_begin) (default=C(BEGIN)) and O(marker_end) (default=C(END)).
    - Using a custom marker without the C({mark}) variable may result in the block being repeatedly inserted on subsequent playbook runs.
    - Multi-line markers are not supported and will result in the block being repeatedly inserted on subsequent playbook runs.
    - A newline is automatically appended by the module to O(marker_begin) and O(marker_end).
    type: str
    default: '# {mark} ANSIBLE MANAGED BLOCK'
  block:
    description:
    - The text to insert inside the marker lines.
    - If it is missing or an empty string, the block will be removed as if O(state) were specified to V(absent).
    type: str
    default: ''
    aliases: [ content ]
  insertafter:
    description:
    - If specified and no begin/ending O(marker) lines are found, the block will be inserted after the last match of specified regular expression.
    - A special value is available; V(EOF) for inserting the block at the end of the file.
    - If specified regular expression has no matches or no value is passed, V(EOF) will be used instead.
    - The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines.
      This behaviour was added in ansible-core 2.14.
    type: str
  insertbefore:
    description:
    - If specified and no begin/ending O(marker) lines are found, the block will be inserted before the last match of specified regular expression.
    - A special value is available; V(BOF) for inserting the block at the beginning of the file.
    - If specified regular expression has no matches, the block will be inserted at the end of the file.
    - The presence of the multiline flag (?m) in the regular expression controls whether the match is done line by line or with multiple lines.
      This behaviour was added in ansible-core 2.14.
    type: str
  create:
    description:
    - Create a new file if it does not exist.
    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
  marker_begin:
    description:
    - This will be inserted at C({mark}) in the opening ansible block O(marker).
    type: str
    default: BEGIN
    version_added: '2.5'
  marker_end:
    required: false
    description:
    - This will be inserted at C({mark}) in the closing ansible block O(marker).
    type: str
    default: END
    version_added: '2.5'
  append_newline:
    required: false
    description:
    - Append a blank line to the inserted block, if this does not appear at the end of the file.
    - Note that this attribute is not considered when C(state) is set to C(absent)
    type: bool
    default: no
    version_added: '2.16'
  prepend_newline:
    required: false
    description:
    - Prepend a blank line to the inserted block, if this does not appear at the beginning of the file.
    - Note that this attribute is not considered when C(state) is set to C(absent)
    type: bool
    default: no
    version_added: '2.16'
notes:
  - When using C(with_*) loops be aware that if you do not set a unique mark the block will be overwritten on each iteration.
  - As of Ansible 2.3, the O(dest) option has been changed to O(path) as default, but O(dest) still works as well.
  - Option O(ignore:follow) has been removed in Ansible 2.5, because this module modifies the contents of the file
    so O(ignore:follow=no) does not make sense.
  - When more than one block should be handled in one file you must change the O(marker) per task.
extends_documentation_fragment:
    - action_common_attributes
    - action_common_attributes.files
    - files
    - validate
attributes:
    check_mode:
        support: full
    diff_mode:
        support: full
    safe_file_operations:
      support: full
    platform:
      support: full
      platforms: posix
    vault:
      support: none
a6  
# Before Ansible 2.3, option 'dest' or 'name' was used instead of 'path'
- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config prepending and appending a new line
  ansible.builtin.blockinfile:
    path: /etc/ssh/sshd_config
    append_newline: true
    prepend_newline: true
    block: |
      Match User ansible-agent
      PasswordAuthentication no

- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
        (it might be better to copy files into /etc/network/interfaces.d/)
  ansible.builtin.blockinfile:
    path: /etc/network/interfaces
    block: |
      iface eth0 inet static
          address 192.0.2.23
          netmask 255.255.255.0

- name: Insert/Update configuration using a local file and validate it
  ansible.builtin.blockinfile:
    block: "{{ lookup('ansible.builtin.file', './local/sshd_config') }}"
    path: /etc/ssh/sshd_config
    backup: yes
    validate: /usr/sbin/sshd -T -f %s

- name: Insert/Update HTML surrounded by custom markers after <body> line
  ansible.builtin.blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    insertafter: "<body>"
    block: |
      <h1>Welcome to {{ ansible_hostname }}</h1>
      <p>Last updated on {{ ansible_date_time.iso8601 }}</p>

- name: Remove HTML as well as surrounding markers
  ansible.builtin.blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    block: ""

- name: Add mappings to /etc/hosts
  ansible.builtin.blockinfile:
    path: /etc/hosts
    block: |
      {{ item.ip }} {{ item.name }}
    marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
  loop:
    - { name: host1, ip: 10.10.1.10 }
    - { name: host2, ip: 10.10.1.11 }
    - { name: host3, ip: 10.10.1.12 }

- name: Search with a multiline search flags regex and if found insert after
  blockinfile:
    path: listener.ora
    block: "{{ listener_line | indent(width=8, first=True) }}"
    insertafter: '(?m)SID_LIST_LISTENER_DG =\n.*\(SID_LIST ='
    marker: "    <!-- {mark} ANSIBLE MANAGED BLOCK -->"

N)b)AnsibleModule)to_bytes	to_nativec                   t        j                  | j                        \  }}t        j                  |d      }|j                  |       |j                          | j                  j                  dd       }| }|rSd|vr| j                  d|z         | j                  ||z        \  }}	}
|dk(  }|dk7  r| j                  d|d	|
       |r"| j                  ||| j                  d
          y y )N)dirwbvalidatez%szvalidate must contain %%s: %smsgr   zfailed to validate: rc:z error:unsafe_writes)r   )tempfilemkstemptmpdirosfdopenwritecloseparamsget	fail_jsonrun_commandatomic_move)modulecontentspathtmpfdtmpfilefr   validrcouterrs              K/home/dcms/DCMS/lib/python3.12/site-packages/ansible/modules/blockinfile.pywrite_changesr&      s    %%&--8NE7
		%AGGHGGI}}  T2HLEx!@H!MN++Hw,>?S#a757"> ?7Do8VW     c                    | j                  | j                        }| j                  |d|      r|r|dz  }d}|dz  }||fS )NF)diffz and Tz,ownership, perms or SE linux context changed)load_file_common_argumentsr    set_file_attributes_if_different)r   changedmessager)   	file_argss        r%   check_file_attrsr/      sS    11&--@I..y%d.KwGAAGr'   c                    t        t        t        ddg d      t        ddddg      t        dd	
      t        dddg      t        d      t        d      t        dd
      t        dd
      t        d      t        dd
      t        dd
      t        dd
      t        dd
            ddggdd      } | j                  }|d   }t        j                  j                  |      r| j                  dd|z         t        j                  j                  |      }|s| j                  |d         s| j                  dd|z         t        j                  j                  |      }|rAt        j                  j                  |      s"| j                  s	 t        j                  |       d }g }n6t#        |d"      5 }|j%                         }d d d        j'                  d      }ddd#|z  d#|z  d$}	| j(                  r|r||	d%<   |d   }
|d   }t+        |d&         }t+        |d'         }|d(   dk(  }t-        t        j.                        g}|s|s| j1                  dd)|z  *       |
|d+}|d,vr!t3        j4                  t+        |d-.            }n'|
d/vr!t3        j4                  t+        |
d-.            }nd }t3        j6                  t-        d0      t-        |d1         |      t-        t        j.                        z   }t3        j6                  t-        d0      t-        |d2         |      t-        t        j.                        z   }|r`|r^|j9                  t-        t        j.                              s|t-        t        j.                        z  }|g|j'                  d      z   |gz   }ng }d x}}t;        |      D ]  \  }}||k(  r|}||k(  s|} d ||fv rd }||j<                  t2        j>                  z  rm|jA                  |      }|r|r+t!        |      jC                  d3d4|jE                               }nT|
rRt!        |      jC                  d3d4|jG                               }n't;        |      D ]  \  }}|jA                  |      s|} |tI        |      }n1|/|d5z  }n)|
d4}n$tI        |      }n||k  r	g |||d5z    n
g |||d5z    |}|d4kD  rU||d5z
     j9                  t-        t        j.                              s'||d5z
  xx   t-        t        j.                        z  cc<   |d6   r3|r1|d4k7  r,||d5z
     t-        t        j.                        k7  r
|||| |d5z  }|||| |d7   rB|r@|tI        |      z   }|tI        |      k  r$||   t-        t        j.                        k7  r|||| |rd8jK                  |      }nd8}| j(                  r||	d9<   ||k(  rd}d}n|d:}d}n|sd;}d}nd<}d}d }|rb| j                  sV| j                  |d=         r|r| jM                  |      }t        j                  jO                  |d         }tQ        | ||       | j                  r|s| j1                  |||	>       i }tS        | |||      \  }}d?|z  |d@<   d?|z  |dA<   |	|g} || j1                  ||| >       y | j1                  ||| |B       y # t        $ r:}| j                  d|d|j                  d|j                          Y d }~Zd }~wt        $ r,}| j                  d|d!t!        |              Y d }~d }~ww xY w# 1 sw Y   uxY w)CNr   T)destdestfilename)typerequiredaliasesstrpresentabsent)r4   defaultchoicesz# {mark} ANSIBLE MANAGED BLOCK)r4   r:    content)r4   r:   r6   )r4   boolFBEGINEND)r   statemarkerblockinsertafterinsertbeforecreatebackupr   marker_begin
marker_endappend_newlineprepend_newlinerE   rD   )argument_specmutually_exclusiveadd_file_common_argssupports_check_mode   zPath %s is a directory !)r"   r   rF   i  zPath %s does not exist !zError creating z Error code: z Error description: r   z Error: rbz%s (content))beforeafterbefore_headerafter_headerrR   rC   rB   rA   zFile %s not present)r,   r   EOF)NrV   surrogate_or_strict)errors)NBOFz{mark}rH   rI   
r      rK   rJ   r'   rS   zFile createdzBlock removedzBlock insertedrG   )r,   r   r)   z%s (file attributes)rT   rU   )r,   r   r)   backup_file)*r   dictr   r   r   isdirr   existsbooleandirname
check_modemakedirsOSErrorerrnostrerror	Exceptionr   openread
splitlines_diffr   r   linesep	exit_jsonrecompilesubendswith	enumerateflags	MULTILINEsearchcountendstartlenjoinbackup_localrealpathr&   r/   )!r   r   r   path_existsdestpatheoriginallinesr    r)   rE   rD   rC   rB   r8   
blank_lineinsertremarker0marker1
blocklinesn0n1ilinematchline_after_blockresultr   r,   r\   	real_path	attr_diffdifflists!                                    r%   mainr      s$   6D:VWE9x>STU,LME2	{C%(5)VU3VU3u%5':6VU; fe<
 ,];<! %F( ]]F&>D	ww}}TC7$> 	 	@ ''..&K~~fX./!;d!B  D77??4(BGGNN84V=N=N_H%
 $ 	 vvxH	 ##D)+d2*T13D
 ||!X.)L'KVG_%EfX&'FWo*GBJJ-J;,AD,HI 3-'::h{;PQR	]	*::h|<QRSffQy\1VN%;#<fE"**UGffQy\1VL%9#:FCa

mSG5~~a

m,Qrzz]"EY!1!1$!777)C

NBU# 47?B7?B	 Bx~~, 1"&x066tQ		L%&x066tQN(/ GAtt, zZ(a%BUB	bbaba 
AvR!V}%%a

m4"q&MQrzz]*M  W7uR!V}"**5%E"RL!GB E"RL
 GJ/c%j(U3C-D"**-U7AE"#34%||W6		Kv((>>&*+ --d3KGG$$VF^4	ffi0c=I#FGS)DLC!7$!>Io 6 =Ini HcAckZo  A  aiklkrkrtut~t~%   A  A _  hPYZ[P\%] ^^_
	  	 s0   [ ]	]/\

]!\==]]__main__)
__future__r   DOCUMENTATIONEXAMPLESrn   r   r   ansible.module_utils.sixr   ansible.module_utils.basicr   +ansible.module_utils.common.text.convertersr   r   r&   r/   r   __name__ r'   r%   <module>r      sV    #vp<| 
 	  & 4 KX*
|[~ zF r'   