
    Vhfa                         d dl mZmZmZ eZdZdZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlmZ d dlmZmZ d Zd Zd	 Zd
 Z	 	 	 ddZd Zedk(  r e        yy)    )absolute_importdivisionprint_functionaq  
module: ini_file
short_description: Tweak settings in INI files
extends_documentation_fragment:
  - files
  - community.general.attributes
description:
  - Manage (add, remove, change) individual settings in an INI-style file without having to manage the file as a whole with,
    say, M(ansible.builtin.template) or M(ansible.builtin.assemble).
  - Adds missing sections if they do not exist.
  - This module adds missing ending newlines to files to keep in line with the POSIX standard, even when no other modifications
    need to be applied.
attributes:
  check_mode:
    support: full
  diff_mode:
    support: full
options:
  path:
    description:
      - Path to the INI-style file; this file is created if required.
    type: path
    required: true
    aliases: [dest]
  section:
    description:
      - Section name in INI file. This is added if O(state=present) automatically when a single value is being set.
      - If being omitted, the O(option) will be placed before the first O(section).
      - Omitting O(section) is also required if the config format does not support sections.
    type: str
  section_has_values:
    type: list
    elements: dict
    required: false
    suboptions:
      option:
        type: str
        description: Matching O(section) must contain this option.
        required: true
      value:
        type: str
        description: Matching O(section_has_values[].option) must have this specific value.
      values:
        description:
          - The string value to be associated with an O(section_has_values[].option).
          - Mutually exclusive with O(section_has_values[].value).
          - O(section_has_values[].value=v) is equivalent to O(section_has_values[].values=[v]).
        type: list
        elements: str
    description:
      - Among possibly multiple sections of the same name, select the first one that contains matching options and values.
      - With O(state=present), if a suitable section is not found, a new section will be added, including the required options.
      - With O(state=absent), at most one O(section) is removed if it contains the values.
    version_added: 8.6.0
  option:
    description:
      - If set (required for changing a O(value)), this is the name of the option.
      - May be omitted if adding/removing a whole O(section).
    type: str
  value:
    description:
      - The string value to be associated with an O(option).
      - May be omitted when removing an O(option).
      - Mutually exclusive with O(values).
      - O(value=v) is equivalent to O(values=[v]).
    type: str
  values:
    description:
      - The string value to be associated with an O(option).
      - May be omitted when removing an O(option).
      - Mutually exclusive with O(value).
      - O(value=v) is equivalent to O(values=[v]).
    type: list
    elements: str
    version_added: 3.6.0
  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: false
  state:
    description:
      - If set to V(absent) and O(exclusive) set to V(true) all matching O(option) lines are removed.
      - If set to V(absent) and O(exclusive) set to V(false) the specified O(option=value) lines are removed, but the other
        O(option)s with the same name are not touched.
      - If set to V(present) and O(exclusive) set to V(false) the specified O(option=values) lines are added, but the other
        O(option)s with the same name are not touched.
      - If set to V(present) and O(exclusive) set to V(true) all given O(option=values) lines will be added and the other
        O(option)s with the same name are removed.
    type: str
    choices: [absent, present]
    default: present
  exclusive:
    description:
      - If set to V(true) (default), all matching O(option) lines are removed when O(state=absent), or replaced when O(state=present).
      - If set to V(false), only the specified O(value)/O(values) are added when O(state=present), or removed when O(state=absent),
        and existing ones are not modified.
    type: bool
    default: true
    version_added: 3.6.0
  no_extra_spaces:
    description:
      - Do not insert spaces before and after '=' symbol.
    type: bool
    default: false
  ignore_spaces:
    description:
      - Do not change a line if doing so would only add or remove spaces before or after the V(=) symbol.
    type: bool
    default: false
    version_added: 7.5.0
  create:
    description:
      - If set to V(false), the module will fail if the file does not already exist.
      - By default it will create the file if it is missing.
    type: bool
    default: true
  allow_no_value:
    description:
      - Allow option without value and without '=' symbol.
    type: bool
    default: false
  modify_inactive_option:
    description:
      - By default the module replaces a commented line that matches the given option.
      - Set this option to V(false) to avoid this. This is useful when you want to keep commented example C(key=value) pairs
        for documentation purposes.
    type: bool
    default: true
    version_added: 8.0.0
  follow:
    description:
      - This flag indicates that filesystem links, if they exist, should be followed.
      - O(follow=true) can modify O(path) when combined with parameters such as O(mode).
    type: bool
    default: false
    version_added: 7.1.0
notes:
  - While it is possible to add an O(option) without specifying a O(value), this makes no sense.
  - As of community.general 3.2.0, UTF-8 BOM markers are discarded when reading files.
author:
  - Jan-Piet Mens (@jpmens)
  - Ales Nosek (@noseka1)
a	  
- name: Ensure "fav=lemonade is in section "[drinks]" in specified file
  community.general.ini_file:
    path: /etc/conf
    section: drinks
    option: fav
    value: lemonade
    mode: '0600'
    backup: true

- name: Ensure "temperature=cold is in section "[drinks]" in specified file
  community.general.ini_file:
    path: /etc/anotherconf
    section: drinks
    option: temperature
    value: cold
    backup: true

- name: Add "beverage=lemon juice" is in section "[drinks]" in specified file
  community.general.ini_file:
    path: /etc/conf
    section: drinks
    option: beverage
    value: lemon juice
    mode: '0600'
    state: present
    exclusive: false

- name: Ensure multiple values "beverage=coke" and "beverage=pepsi" are in section "[drinks]" in specified file
  community.general.ini_file:
    path: /etc/conf
    section: drinks
    option: beverage
    values:
      - coke
      - pepsi
    mode: '0600'
    state: present

- name: Add "beverage=lemon juice" outside a section in specified file
  community.general.ini_file:
    path: /etc/conf
    option: beverage
    value: lemon juice
    state: present

- name: Remove the peer configuration for 10.128.0.11/32
  community.general.ini_file:
    path: /etc/wireguard/wg0.conf
    section: Peer
    section_has_values:
      - option: AllowedIps
        value: 10.128.0.11/32
    mode: '0600'
    state: absent

- name: Add "beverage=lemon juice" outside a section in specified file
  community.general.ini_file:
    path: /etc/conf
    option: beverage
    value: lemon juice
    state: present

- name: Update the public key for peer 10.128.0.12/32
  community.general.ini_file:
    path: /etc/wireguard/wg0.conf
    section: Peer
    section_has_values:
      - option: AllowedIps
        value: 10.128.0.12/32
    option: PublicKey
    value: xxxxxxxxxxxxxxxxxxxx
    mode: '0600'
    state: present

- name: Remove the peer configuration for 10.128.0.11/32
  community.general.ini_file:
    path: /etc/wireguard/wg0.conf
    section: Peer
    section_has_values:
      - option: AllowedIps
        value: 10.4.0.11/32
    mode: '0600'
    state: absent

- name: Update the public key for peer 10.128.0.12/32
  community.general.ini_file:
    path: /etc/wireguard/wg0.conf
    section: Peer
    section_has_values:
      - option: AllowedIps
        value: 10.4.0.12/32
    option: PublicKey
    value: xxxxxxxxxxxxxxxxxxxx
    mode: '0600'
    state: present
N)AnsibleModule)to_bytesto_textc                 ^    t        j                  |       } t        j                  d| z  |      S )Nz,( |	)*([#;]?)( |	)*(%s)( |	)*(=|$)( |	)*(.*)reescapematchoptionlines     n/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/ini_file.py	match_optr     s(    YYvF88FOQUVV    c                 ^    t        j                  |       } t        j                  d| z  |      S )Nz#()()( |	)*(%s)( |	)*(=|$)( |	)*(.*)r
   r   s     r   match_active_optr     s'    YYvF88<vEtLLr   c                     d }|rOt        | ||         }	|	j                  d      s/t        | |      }
|	j                  d      |
j                  d      k7  }|||   |k7  }|r|||<   |xs |}|rd}d||<   ||fS )N      option changed   )r   group)r   changedsection_linesindexchanged_linesignore_spacesnewlinemsgoption_changed	old_match	new_matchs              r   update_section_liner&     s    NfmE&:;	q!!&'2I&__Q/9??13EEN&u-8&e'GM%S>r   c                     | J| D ]E  }|D ]=  }t        |d   |      }|st        |d         dk(  s|j                  d      |d   v s= D  y y)Nr   valuesr   r   FT)r   lenr   )section_has_valuesr   	conditionr   r   s        r   check_section_has_valuesr,   )  sn    %+ 	I% !)H"5t<c)H"56!;u{{1~QZ[cQd?d
 	 r   c                 B   |t        |      }|t        |      }g }|D cg c]$  }||vs||j                  t        |            & c} |}t        ddd|z  d|z        }|r?t        j                  j                  |      r t        j                  j                  |      }n|}t        j                  j                  |      sz|s| j                  dd|z         t        j                  j                  |      }t        j                  j                  |      s!| j                  st        j                  |       g }nGt        j                  |dd	      5 }|j                         D cg c]  }t        |       }}d d d        | j                  rdj!                        |d
<   d}s|j                  d       |d   dk(  s|d   d   dk7  r|dxx   dz  cc<   d}d}|j#                  dd|z         |j                  d       |s|}| }dx}}d}|	rd}nd}d}t%        j&                  t        d            }g x} }!g }"t%        j&                  t        dt%        j(                  |j+                               z              }#t-        |      D ]G  \  }$}|r*|j/                  d      rt1        ||||$       r|$} nd}dx}}|#j3                  |      sDd}|$}I |d| } ||| }"||t5        |       }!dgt5        |"      z  }%|rt6        }&nt8        }&|dk(  r|rt-        |"      D ]  \  }$} |&||      s |&||      }'|r^|'j;                  d      |v rK|'j;                  d      }(|(s
|rd|z  })d}n|||(fz  })t=        |||"|$|%|
|)|      \  }}|j?                  |(       y|r||sd|z  })t=        |||"|$|%|
|)|      \  }}d} n |dk(  r|r|st5        |      dkD  r^t-        |"      D ]P  \  }$}|%|$   r |&||      s|||jA                  d      fz  })t=        |||"|$|%|
|)|      \  }}t5        |      dk(  sP n tC        t5        |"      dz
  dd      D ]  }$|%|$   r	 |&||"|$         s|"|$= |%|$= d}d}! |dk(  rtC        t5        |"      dd      D ]  }$|j3                  |"|$dz
           r|rM|rK|d d d   D ]?  }*|*|"j#                  |$|||*fz         d}d}!|*$|s'|"j#                  |$d|z         d}d}A n!|r|s|r|s|"j#                  |$d|z         d}d} n |dk(  r|r|r(|"D cg c]  }t9        ||      r| }+}|"|+k7  rdd}d}|+}"n]|s[t5        |      dkD  rM|"D ,cg c].  },t9        ||,      rt9        ||,      j;                  d      |v r-|,0 }+},|"|+k7  rd}d}|+}"n|"rg }"d}d}| |"z   |!z   }|d= |dd = |s|dk(  r|j                  d |z         d!}|r|D ]}  }-|-d"   |k7  rPt5        |-d#         dkD  r$|-d#   D ]  }|j                  ||-d"   |fz          @|sC|j                  d|-d"   z         [|r^|-d#   D ]  }||vs|j                  |         |r |r|D ]  }|j                  |||fz          n|r|s|r|j                  d|z         nd$}d}| j                  rdj!                  |      |d%<   d }.|r| j                  s|r| jE                  |      }.|D cg c]  }tG        |       }/}	 tI        jJ                  | jL                  &      \  }0}1t        jN                  |0d'      }2|2jQ                  |/       |2jS                          	 | j[                  1t        j                  j]                  |             ||.||fS c c}w c c}w # 1 sw Y   xY wc c}w c c},w c c}w # tT        $ r( | j                  d(tW        jX                         )       Y w xY w# tT        $ r9 | j^                  j                  d*1d+|d,tW        jX                         )       Y w xY w)-N z%s (content))beforeafterbefore_headerafter_headeri  zDestination %s does not exist!)rcr"   rz	utf-8-sig)encodingr/   F
T(ad01e11446efb704fcdbdb21f2c43757423d91c5r   z[%s][OKz%s=%s
z%s = %s
z^[ \t]*([#;].*)?$z^\[\s*%s\s*]presentr   z%s
r   r   zoption addedabsentzsection removedz[%s]
zsection and option addedr   r(   zonly section addedr0   )dirwbz"Unable to create temporary file %s)r"   	tracebackzAUnable to move temporary                                    file z to z	, IOError)0r   appenddictospathislinkrealpathexists	fail_jsondirname
check_modemakedirsioopen	readlines_diffjoininsertr   compiler   strip	enumerate
startswithr,   r   r)   r   r   r   r&   removepoprangebackup_localr   tempfilemkstemptmpdirfdopen
writelinescloseIOErrorr?   
format_excatomic_moveabspathansible)3modulefilenamesectionr*   r   r(   state	exclusivebackupno_extra_spacesr    createallow_no_valuemodify_inactive_optionfollowvalues_uniquevaluedifftarget_filenamedestpath	ini_linesini_filer   r   fake_section_namewithin_sectionsection_startsection_endr"   assignment_formatoption_no_value_presentnon_blank_non_comment_patternr/   r0   r   section_patternr   r   match_functionr   matched_valuer!   elementnew_section_linesir+   backup_fileencoded_ini_linestmpfdtmpfilefs3                                                      r   do_inir   5  ss	    '" M7=remA[`e`q]'%.)rF$x/#h.	D "''..*''**84"77>>/*)IO)[\77???3ww~~h'0A0AKK!	WW_cK@ 	IH3;3E3E3GH4HIH	I ||),XG  }y}R0E9" D Q"334 T # [N"##MK
C&(#$&JJw7K/L$M!FUMjj299W]]_;U)U!VWO + "tdood3'"ImE$B $ "'.//   &!N!M!"$ q'FmK8Mk#i.1E C#m,,M ") 	f$]3 	KE4fd+&vt4ekk!n6$)KKNM(^")F"226/ #4v}6M"M%8-Y^`mo|  F  HK  &LNWcMM-0N%.G%8-Y^`mo|  F  HK  &LNWc.2+'	* 	iv;?(7 t$U+vt0L/66::a=2IIG%8-Y^`mo|  F  HK  &LNWc6{a' 3}-11b9 	'E 'N6=QVCW,X!%(!%(&	' 	3}-q"5 	E066}UQY7OPf#)$B$< + #.)008IVU\L]8]^"0C&*G$_)00&8HI"0C&*G+ F~F]!((&0@A(C"G/	2 6C$ldL\]ceiLjT$l!$l $55"G*C$5M3v;?0=  %W1FVW]_`Fafvw}  @A  gB  gH  gH  IJ  gK  OU  gUQ  %W!  %W $55"G*C$5M  "' &.I 	!"#ey0W,-(/ 
1	X&&09X./!3%.x%8 _E%,,->)HBUW\A]-]^_'!((9X3F)FG"!*8!4 1 ."MM%01
1 f F  !2fe_!DEFF~Wv-.&C||+WKv(( --o>K8ABXd^BB	i%--&--@NE7		%&ALL*+GGI	{w(HI
 [$,,} s0 I	I 	I| %m %Wf C  	i!EQZQeQeQgh	i
  	{NN$$>E*Xclcwcwcy % {	{sp   	^^^^+^=^#^5^.^
^^#2A^( /_ ^^(.__?``c                     t        t        t        dddg      t        d      t        ddt        t        dd	      t        d      t        dd
            d ddgg      t        d      t        d      t        dd
      t        dd      t        ddddg      t        dd      t        dd      t        dd      t        dd      t        dd      t        dd      t        dd            ddggdd      } | j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }| j                  d   }	| j                  d   }
| j                  d   }| j                  d   }| j                  d    }| j                  d!   }| j                  d"   }|dk(  r|s||s| j                  d#$       ||g}n|g }|r!|D ]  }|d   
|d   g|d<   |d   g |d<    t	        | ||||||||	|
|||||      \  }}}}| j
                  sLt        j                  j                  |      r-| j                  | j                        }| j                  ||      }t        ||||%      }|||d&<    | j                  d'i | y )(NrC   Tdest)typerequiredaliasesstr)r   listrA   )r   r   )r   elements)r   rp   r(   rp   r(   )r   r   optionsdefaultmutually_exclusiveboolF)r   r   r;   r<   )r   r   choices)rC   rf   r*   r   rp   r(   ri   rg   rh   rj   r    rl   rm   rk   rn   )argument_specr   add_file_common_argssupports_check_moderf   r*   r   rg   rh   ri   rj   r    rl   rm   rk   rn   zOParameter 'value(s)' must be defined if state=present and allow_no_value=False.)r"   )r   rq   r"   rC   r    )r   rA   paramsrG   r   rI   rB   rC   rF   load_file_common_argumentsset_fs_attributes_if_different	exit_json)rd   rC   rf   r*   r   rp   r(   rg   rh   ri   rj   r    rl   rm   rk   rn   r+   r   r   rq   r"   	file_argsresultss                          r   mainr   A  s   6D6(Ce$#&$6&%8K '81D0E	 G
 U#E"Ve4VU3E9x>ST5 fe<FE:VU;#'VT#BVT2VU3'
, h
 " 5F: == DmmI&G';<]]8$FMM'"E]]8$FMM'"Ek*I]]8$Fmm$56OMM/2M]]#34N#]]+CD]]8$F]]8$F	.U]6no	+ 	)I!-'0'9&:	(#8$,&(	(#		) )/g1665)U[@VX^)`%Wk4 !555fmmD	77	7K	G !, Fwr   __main__)NNNNr;   TFFFTFTF)
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESrK   rB   r   rY   r?   ansible.module_utils.basicr   +ansible.module_utils.common.text.convertersr   r   r   r   r&   r,   r   r   __name__r   r   r   <module>r      s    A @Pd`D 
 	 	   4 IW
M
$	 Y]JOglI-XQ h zF r   