
    VhG                         d dl mZmZmZ eZdZdZd dlZ	 d dl	Z	dZ
d dlmZ d dlmZmZ d d	lmZ  G d
 d      Zd Zedk(  r e        yy# e$ r dZ
Y 8w xY w)    )absolute_importdivisionprint_functiona'  
module: podman_play
author:
  - "Sagi Shnaidman (@sshnaidm)"
short_description: Play kubernetes YAML file using podman
notes: []
description:
  - The module reads in a structured file of Kubernetes YAML.
    It will then recreate the pod and containers described in the YAML.
requirements:
  - "Podman installed on host"
options:
  executable:
    description:
      - Name of executable to run, by default 'podman'
    type: str
    default: podman
  kube_file:
    description:
      - Path to file with YAML configuration for a Pod.
    type: path
  kube_file_content:
    description:
      - Content of the kube file.
    type: str
  annotation:
    description:
      - Add an annotation to the container or pod.
    type: dict
    aliases:
      - annotations
  authfile:
    description:
      - Path of the authentication file. Default is ${XDG_RUNTIME_DIR}/containers/auth.json,
        which is set using podman login. If the authorization state is not found there,
        $HOME/.docker/config.json is checked, which is set using docker login.
        Note - You can also override the default path of the authentication file
        by setting the REGISTRY_AUTH_FILE environment variable. export REGISTRY_AUTH_FILE=path
    type: path
  build:
    description:
      - Build images even if they are found in the local storage.
      - It is required to exist subdirectories matching the image names to be build.
    type: bool
  cert_dir:
    description:
      - Use certificates at path (*.crt, *.cert, *.key) to connect to the registry.
        Default certificates directory is /etc/containers/certs.d.
        (This option is not available with the remote Podman client)
    type: path
  configmap:
    description:
      - Use Kubernetes configmap YAML at path to provide a source for environment
        variable values within the containers of the pod.
        Note - The configmap option can be used multiple times to pass multiple
        Kubernetes configmap YAMLs
    type: list
    elements: path
  context_dir:
    description:
      - Use path as the build context directory for each image.
        Requires build option be true.
    type: path
  seccomp_profile_root:
    description:
      - Directory path for seccomp profiles (default is "/var/lib/kubelet/seccomp").
        This option is not available with the remote Podman client
    type: path
  username:
    description:
      - The username and password to use to authenticate with the registry if required.
    type: str
  password:
    description:
      - The username and password to use to authenticate with the registry if required.
    type: str
  log_driver:
    description:
      - Set logging driver for all created containers.
    type: str
  log_opt:
    description:
      - Logging driver specific options. Set custom logging configuration.
    type: dict
    aliases:
      - log_options
    suboptions:
      path:
        description:
          - specify a path to the log file (e.g. /var/log/container/mycontainer.json).
        type: str
        required: false
      max_size:
        description:
          - Specify a max size of the log file (e.g 10mb).
        type: str
        required: false
      tag:
        description:
          - Specify a custom log tag for the container.
            This option is currently supported only by the journald log driver in Podman.
        type: str
        required: false
  log_level:
    description:
      - Set logging level for podman calls. Log messages above specified level
        ("debug"|"info"|"warn"|"error"|"fatal"|"panic") (default "error")
    type: str
    choices:
      - debug
      - info
      - warn
      - error
      - fatal
      - panic
  network:
    description:
      - List of the names of CNI networks the pod should join.
    type: list
    elements: str
  state:
    description:
      - Start the pod after creating it, or to leave it created only.
    type: str
    choices:
      - created
      - started
      - absent
      - quadlet
    required: True
  tls_verify:
    description:
      - Require HTTPS and verify certificates when contacting registries (default is true).
        If explicitly set to true, then TLS verification will be used. If set to false,
        then TLS verification will not be used. If not specified, TLS verification will be
        used unless the target registry is listed as an insecure registry in registries.conf.
    type: bool
  debug:
    description:
      - Enable debug for the module.
    type: bool
  recreate:
    description:
      - If pod already exists, delete it and run the new one.
    type: bool
  quiet:
    description:
      - Hide image pulls logs from output.
    type: bool
  userns:
    description:
    - Set the user namespace mode for all the containers in a pod.
      It defaults to the PODMAN_USERNS environment variable.
      An empty value ("") means user namespaces are disabled.
    required: false
    type: str
  quadlet_dir:
    description:
      - Path to the directory to write quadlet file in.
        By default, it will be set as C(/etc/containers/systemd/) for root user,
        C(~/.config/containers/systemd/) for non-root users.
    type: path
    required: false
  quadlet_filename:
    description:
      - Name of quadlet file to write. Must be specified if state is quadlet.
    type: str
  quadlet_file_mode:
    description:
      - The permissions of the quadlet file.
      - The O(quadlet_file_mode) can be specied as octal numbers or as a symbolic mode (for example, V(u+rwx) or V(u=rw,g=r,o=r)).
        For octal numbers format, you must either add a leading zero so that Ansible's YAML parser knows it is an
        octal number (like V(0644) or V(01777)) or quote it (like V('644') or V('1777')) so Ansible receives a string
        and can do its own conversion from string into number. Giving Ansible a number without following one of these
        rules will end up with a decimal number which will have unexpected results.
      - If O(quadlet_file_mode) is not specified and the quadlet file B(does not) exist, the default V('0640') mask will be used
        when setting the mode for the newly created file.
      - If O(quadlet_file_mode) is not specified and the quadlet file B(does) exist, the mode of the existing file will be used.
      - Specifying O(quadlet_file_mode) is the best way to ensure files are created with the correct permissions.
    type: raw
    required: false
  quadlet_options:
    description:
      - Options for the quadlet file. Provide missing in usual network args
        options as a list of lines to add.
    type: list
    elements: str
    required: false
a  
- name: Play kube file
  containers.podman.podman_play:
    kube_file: ~/kube.yaml
    state: started

- name: Recreate pod from a kube file with options
  containers.podman.podman_play:
    kube_file: ~/kube.yaml
    state: started
    recreate: true
    annotations:
      greeting: hello
      greet_to: world
    userns: host
    log_opt:
      path: /tmp/my-container.log
      max_size: 10mb

- name: Create a Quadlet file
  containers.podman.podman_play:
    kube_file: ~/kube.yaml
    state: quadlet
    annotations:
      greeting: hello
      greet_to: world
    userns: host
    quadlet_filename: kube-pod
    quadlet_file_mode: '0640'
    quadlet_options:
      - "SetWorkingDirectory=yaml"
      - "ExitCodePropagation=any"
NTF)AnsibleModule)LooseVersionget_podman_version)create_quadlet_statec                   <    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
y	)
PodmanKubeManagementc                    || _         g | _        || _        | j                  ddg| _        t	        |      | _        g }| j                   j                  d   r]| j                   j                  d   j                         D ]3  \  }}| j                  j                  ddj                  ||      g       5 | j                   j                  d   r|| j                   j                  d   gz  }| j                   j                  d   r|| j                   j                  d   gz  }d	j                  |      }| j                  j                  d
|z  g       | j                   j                  d   rGdj                  | j                   j                  d         }| j                  j                  d|z  g       | j                   j                  d   rGdj                  | j                   j                  d         }| j                  j                  d|z  g       | j                   j                  d   rm| j                   j                  d   j                         D ]C  \  }}| j                  j                  ddj                  |j                  dd      |      g       E | j                   j                  d   dk(  }| j                  j                  dt        |      j                         z  g       dddddddddd d!
j                         D ]Q  \  }	}
| j                   j                  |
    | xj                  |	d"| j                   j                  |
   gz  c_        S | j                   j                  d#   r.| xj                  | j                   j                  d#   gz  c_        y | j                   j                  d$   r| xj                  dgz  c_        y y )%Nplaykube
annotationz--annotationz{k}={v})kvusernamepassword:z
--creds=%snetwork,z--network=%s	configmapz--configmap=%slog_optz	--log-opt_-statestartedz
--start=%sauthfilebuildcert_dircontext_dir
log_driverseccomp_profile_root
tls_verify	log_levelusernsquiet)
z
--authfilez--buildz
--cert-dirz--context-dirz--log-driverz--seccomp-profile-rootz--tls-verifyz--log-levelz--usernsz--quiet=	kube_filekube_file_content)moduleactions
executablecommandr   versionparamsitemsextendformatjoinreplacestrlower)selfr*   r,   credsr   r   networks
configmapsstartargparams              q/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/containers/podman/plugins/modules/podman_play.py__init__zPodmanKubeManagement.__init__   s?   $8)&1;;l+**<8>>@ R1##^Y5E5EQ5E5O$PQR;;j)dkk((455E{{!!*-$++,,Z899HHUOELL!5 67;;i(xx 2 29 =>HLL(!: ;<;;k*$++"4"4["ABJLL!1J!> ?@;;i(**95;;= a1##[)2B2BQYYsTWEX\]2B2^$_`a""7+y8\CJ,<,<,>>?@$$*(&<(& 
 %'	MJC {{!!%(4C1C1CE1J!K LL	M ;;k*LLT[[//<==L[[ 34LLSE!L 5    c                    | j                   j                  d   r9| j                   j                  || j                   j                  d         \  }}}n| j                   j                  |      \  }}}| j                  j	                  dj                  |             | j                   j                  d   r| j                   j                  ddj                  |      z         | j                   j                  d|z         | j                   j                  d|z         | j                   j                  d|z         |||fS )	Nr)   )data debugzPODMAN-PLAY-KUBE command: %szPODMAN-PLAY-KUBE stdout: %szPODMAN-PLAY-KUBE stderr: %szPODMAN-PLAY-KUBE rc: %s)r*   r/   run_commandr+   appendr3   log)r7   cmdrcouterrs        r>   _command_runz!PodmanKubeManagement._command_run&  s    ;;12;;223T[[=O=OPc=d2eLBS;;2237LBSCHHSM*;;g&KKOO:SXXc]JKKKOO9C?@KKOO9C?@KKOO5:;3|r@   c                    d}| j                   j                  d   }| j                   j                  d   }|r%| j                  | j                  ddd|g      \  }}}n&|r$| j                  | j                  ddddg      \  }}}dk7  rd	v rd}||fS |dk7  r)| j                   j	                  d
|r|nddd       j                         D ]  }|s|j                  d      rd} n ||fS )z
        Tear down the pod and contaiers by using --down option in kube play
        which is supported since Podman 3.4.0
        Fr(   r)   r   r   z--downr   r   zno such podzFailed to delete Pod with zYAML contentz: rC   msgr   T)r*   r/   rL   r,   	fail_json
splitlinesendswith)r7   changedr(   r)   rI   rJ   rK   lines           r>   tear_down_podsz#PodmanKubeManagement.tear_down_pods3  s   
 KK&&{3	 KK../BC,,doovvxYb-cdLBS,,doovvxY\-]^LBS7}+GC$$7KK!!&	N:C'F! G NN$ 	DDMM#.	 S  r@   c                 z   d}| j                   j                  d   rt        rrt        | j                   j                  d         5 }t	        t        j                  |            }d d d        D ]#  }d|v s|d   dv s|d   j                  d      }% nt        | j                   j                  d         5 }t        j                  dt        j                        }|j                  |j                               }|r|j                  d      }d d d        |s| j                   j                  d	       d}d
D ]1  }	| j                  dddd|	|z  g}
| j!                  |
      \  }}}||z  }3 t	        t#        |j%                         D cg c]  }|s|	 c}            }|S # 1 sw Y   >xY w# 1 sw Y   xY wc c}w )N r(   metadatakind)
DeploymentPodnamez5^\s{2,4}name: ["|\']?(?P<pod_name>[\w|\-|\_]+)["|\']?   z.This Kube file doesn't have Pod or Deployment!)zname=%s$zname=%s-pod-*podpsz-qz--filter)r*   r/   HAS_YAMLopenlistyamlsafe_load_allgetrecompile	MULTILINEsearchreadgrouprP   r,   rL   setrQ   )r7   pod_namefpodsr^   textre_pod_namere_podall_podsr\   rH   rI   rJ   rK   iidss                   r>   discover_podsz"PodmanKubeManagement.discover_podsM  s   ;;k*$++,,[9: 7a 2 21 56D7 ?C!S(S[<Q-Q#&z?#6#6v#>? $++,,[9: 3d
 #%**-egigsgs"tK(//		<F#)<<?3 KK!!"RS1 	D??$j$/CC,,S1LBSOH		
 38#6#6#8>aA>?@
57 73 3& ?s%   F6AF,F8F8F),F5c                     d}d\  }}|D ]V  }| j                  | j                  ddd|g      \  }}}|dk7  r| j                  j                  d|z         Kd}||z  }||z  }X |||fS )	NF)rW   rW   r^   rmz-fr   zCan NOT delete Pod %sT)rL   r,   r*   rP   )	r7   ro   rS   out_allerr_allpod_idrI   rJ   rK   s	            r>   remove_associated_podsz+PodmanKubeManagement.remove_associated_podsm  s    ! 	F,,%tV<>LBSQw%%&=&FG33	 ((r@   c                 L   | j                   2t        | j                         t        d      k\  r| j                          n!| j                         }| j	                  |       | j                  | j                        \  }}}|dk7  r| j                  j                  d|z         ||fS )N3.4.0r   zCan NOT create Pod! Error: %s)	r.   r   rU   rv   r|   rL   r-   r*   rP   )r7   ro   rI   rJ   rK   s        r>   pod_recreatez!PodmanKubeManagement.pod_recreate|  s    <<#T\\(BlSZF[([!%%'D''- ((6C7KK!!"AC"GHCxr@   c                    | j                  | j                        \  }}}|dk7  rhd|v rd| j                  j                  d   r| j	                         \  }}d}nd}dj                  |j                         D cg c]	  }d|vs| c}      }n*|dk7  r#| j                  j                  d|d|	       nd}||fS c c}w )
Nr   zpod already existsrecreateTF
zOutput: z
Error=rN   )rL   r-   r*   r/   r   r3   rQ   rP   )r7   rI   rJ   rK   rS   rt   s         r>   r   zPodmanKubeManagement.play  s    ((6C7+s2{{!!*-,,.S))>>+N/C1/LN OC1WKK!!S&I!JGS  Ns   7	B<B<c                     ddi}t        | j                  d      }|j                  |        | j                  j                  di | y )NrS   Fr    )r	   r*   update	exit_json)r7   resultsresults_updates      r>   make_quadletz!PodmanKubeManagement.make_quadlet  s?    e$-dkk6B~&((r@   N)__name__
__module____qualname__r?   rL   rU   rv   r|   r   r   r   r   r@   r>   r   r      s,    -"^!4@)! )r@   r   c                     t        t        d>i dt        ddg      dt        dd      d	t        d
      dt        d      dt        d
      dt        d      dt        d
      dt        dd
      dt        d
      dt        d
      dt        d      dt        dd      dt        d      dt        ddgt        t        d      t        d      t        d                  dt        dd      d t        dg d!d"      d#t        d      d$t        d      d%t        d      d&t        d      d't        d      d(t        dg d)*      d+t        d
d,-      d.t        dd,-      d/t        d0d,-      d1t        ddd,2      dd d3d.gfgd4g5      } | j                  | j                  d   d6      }t	        | |      }d,}d7x}}| j                  d    d8k(  r|j
                  yt        |j
                        t        d9      kD  rX|j                  j                  d:|j
                  d;|j                  j                  d	   <       |j                         \  }}}n]|j                         }|j                  |      \  }}}n7| j                  d    d3k(  r|j                          n|j                         \  }}}||||j                  d=} | j                  d>i | y )?Nr   dictannotations)typealiasesr,   r5   podman)r   defaultr(   path)r   r)   r   r   boolr   r   rb   )r   elementsr    r"   r   r   T)r   no_logr!   r   log_options)r   max_sizetag)r   r   optionsr   r   )r   createdabsentquadlet)r   choicesrequiredr#   rD   r&   r   r%   r$   )rD   infowarnerrorfatalpanic)r   r   quadlet_dirF)r   r   quadlet_filenamequadlet_file_moderawquadlet_options)r   r   r   r   )r(   r)   )argument_specsupports_check_moderequired_ifrequired_one_of)r   rW   r   r~   z	version: z, kube file rN   )rS   stdoutstderrr+   r   )r   r   get_bin_pathr/   r   r.   r   r*   rG   rU   rv   r|   r   r   r+   r   )r*   r,   managerS   rJ   rK   ro   r   s           r>   mainr     sC    #
-A#
9#
 '#
 #.	#

 v&#
 F##
 v&#
 8#
 &)#
 "&6!2#
 u%#
 uT2#
 '#
 f}otu%5)e$H& '#
$ fu5%#
& C'#
. (/#
0 F#1#
2 F#3#
4 v&5#
6 U#7#
8 LN9#
> &59?#
@ "uu=A#
B #>C#
D !fuuME#
H !i"4!56
 /
S,F\ $$l#d % 4J!&*5FGNC#}}W)>>%,v~~*FV]I^*^MMQWQ^Q^QeQefqQr"st & 5 5 7GS#'')D & = =d CGS#	w	9	,"KKMc>>	G Fwr@   __main__)
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESrf   rc   r`   ImportErroransible.module_utils.basicr   Hansible_collections.containers.podman.plugins.module_utils.podman.commonr   r   Iansible_collections.containers.podman.plugins.module_utils.podman.quadletr	   r   r   r   r   r@   r>   <module>r      s   
 A @|| B 
H 5 u jh) h)VE P zF w  Hs   A AA