
    Vh9                         d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZ d dlmZmZ d dlmZ d d	lmZ d d
lmZmZmZ d dlmZ d Zd Z G d de      Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functionu  
module: ssh_config
short_description: Manage SSH config for user
version_added: '2.0.0'
description:
  - Configures SSH hosts with special C(IdentityFile)s and hostnames.
author:
  - Björn Andersson (@gaqzi)
  - Abhijeet Kasurde (@Akasurde)
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  state:
    description:
      - Whether a host entry should exist or not.
    default: present
    choices: ['present', 'absent']
    type: str
  user:
    description:
      - Which user account this configuration file belongs to.
      - If none given and O(ssh_config_file) is not specified, C(/etc/ssh/ssh_config) is used.
      - If a user is given, C(~/.ssh/config) is used.
      - Mutually exclusive with O(ssh_config_file).
    type: str
  group:
    description:
      - Which group this configuration file belongs to.
      - If none given, O(user) is used.
    type: str
  host:
    description:
      - The endpoint this configuration is valid for.
      - Can be an actual address on the internet or an alias that will connect to the value of O(hostname).
    required: true
    type: str
  hostname:
    description:
      - The actual host to connect to when connecting to the host defined.
    type: str
  port:
    description:
      - The actual port to connect to when connecting to the host defined.
    type: str
  remote_user:
    description:
      - Specifies the user to log in as.
    type: str
  identity_file:
    description:
      - The path to an identity file (SSH private key) that will be used when connecting to this host.
      - File need to exist and have mode V(0600) to be valid.
    type: path
  identities_only:
    description:
      - Specifies that SSH should only use the configured authentication identity and certificate files (either the default
        files, or those explicitly configured in the C(ssh_config) files or passed on the ssh command-line), even if C(ssh-agent)
        or a C(PKCS11Provider) or C(SecurityKeyProvider) offers more identities.
    type: bool
    version_added: 8.2.0
  user_known_hosts_file:
    description:
      - Sets the user known hosts file option.
    type: str
  strict_host_key_checking:
    description:
      - Whether to strictly check the host key when doing connections to the remote host.
      - The value V(accept-new) is supported since community.general 8.6.0.
    choices: ['yes', 'no', 'ask', 'accept-new']
    type: str
  proxycommand:
    description:
      - Sets the C(ProxyCommand) option.
      - Mutually exclusive with O(proxyjump).
    type: str
  proxyjump:
    description:
      - Sets the C(ProxyJump) option.
      - Mutually exclusive with O(proxycommand).
    type: str
    version_added: 6.5.0
  forward_agent:
    description:
      - Sets the C(ForwardAgent) option.
    type: bool
    version_added: 4.0.0
  add_keys_to_agent:
    description:
      - Sets the C(AddKeysToAgent) option.
    type: bool
    version_added: 8.2.0
  ssh_config_file:
    description:
      - SSH config file.
      - If O(user) and this option are not specified, C(/etc/ssh/ssh_config) is used.
      - Mutually exclusive with O(user).
    type: path
  host_key_algorithms:
    description:
      - Sets the C(HostKeyAlgorithms) option.
    type: str
    version_added: 6.1.0
  controlmaster:
    description:
      - Sets the C(ControlMaster) option.
    choices: ['yes', 'no', 'ask', 'auto', 'autoask']
    type: str
    version_added: 8.1.0
  controlpath:
    description:
      - Sets the C(ControlPath) option.
    type: str
    version_added: 8.1.0
  controlpersist:
    description:
      - Sets the C(ControlPersist) option.
    type: str
    version_added: 8.1.0
  dynamicforward:
    description:
      - Sets the C(DynamicForward) option.
    type: str
    version_added: 10.1.0
  other_options:
    description:
      - Provides the option to specify arbitrary SSH config entry options via a dictionary.
      - The key names must be lower case. Keys with upper case values are rejected.
      - The values must be strings. Other values are rejected.
    type: dict
    version_added: 10.4.0
requirements:
  - paramiko
a  
- name: Add a host in the configuration
  community.general.ssh_config:
    user: akasurde
    host: "example.com"
    hostname: "github.com"
    identity_file: "/home/akasurde/.ssh/id_rsa"
    port: '2223'
    state: present
    other_options:
      serveraliveinterval: '30'

- name: Delete a host from the configuration
  community.general.ssh_config:
    ssh_config_file: "{{ ssh_config_test }}"
    host: "example.com"
    state: absent
a  
hosts_added:
  description: A list of host added.
  returned: success
  type: list
  sample: ["example.com"]
hosts_removed:
  description: A list of host removed.
  returned: success
  type: list
  sample: ["example.com"]
hosts_changed:
  description: A list of host changed.
  returned: success
  type: list
  sample: ["example.com"]
hosts_change_diff:
  description: A list of host diff changes.
  returned: on change
  type: list
  sample: [
    {
      "example.com": {
        "new": {
          "hostname": "github.com",
          "identityfile": ["/tmp/test_ssh_config/fake_id_rsa"],
          "port": "2224"
        },
        "old": {
          "hostname": "github.com",
          "identityfile": ["/tmp/test_ssh_config/fake_id_rsa"],
          "port": "2224"
        }
      }
    }
  ]
N)deepcopy)AnsibleModulemissing_required_lib)	to_native)string_types)ConfigParserHAS_PARAMIKOPARAMIKO_IMPORT_ERROR)determine_config_filec                     | du ry| du ryy )NTyesFno values    p/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/ssh_config.pyconvert_boolr      s    }~    c                     | dk(  ry| dk(  ry| S )NTruer   Falser   r   r   s    r   fix_bool_strr      s    Lr   c                   .    e Zd Zd Zd Zd Zed        Zy)	SSHConfigc                    || _         t        s |j                  t        d      t               |j
                  | _        | j
                  j                  d      | _        | j
                  j                  d      xs | j                  | _        | j
                  j                  d      | _	        | j
                  j                  d      | _
        | j
                  d   | _        | j                          	 t        | j                        | _        | j                  j!                          y # t        $ r, | j                   j                  d| j                  z  	       Y Ow xY w)
NPARAMIKO)msg	exceptionusergrouphostssh_config_fileidentity_filezFailed to find %sr    )moduler   	fail_jsonr   r   paramsgetr"   r#   r$   config_filer&   check_ssh_config_pathr   configFileNotFoundErrorload)selfr(   s     r   __init__zSSHConfig.__init__   s   !5j!AMbcmmKKOOF+	[[__W-:
KKOOF+	;;??+<=![[9""$	N&t'7'78DK 	 ! 	NKK!!&9D<L<L&L!M	Ns   2D' '2EEc                    t        | j                  | j                        | _        t        j                  j                  | j                        r| j                  t        j                  j                  | j                        }t        j                  j                  || j                        | _        t        j                  j                  | j                        s-| j                  j                  d| j                  d   z         y y y y )NzIdentityFile %s does not existr&   r'   )r   r"   r,   ospathexistsr&   dirnamejoinr(   r)   r*   )r1   r7   s     r   r-   zSSHConfig.check_ssh_config_path   s    0D<L<LM 77>>$**+0B0B0Nggood&6&67G!#gt7I7I!JD77>>$"4"45%%*JT[[YhMi*i%j 6	 1O+r   c           
      ^   | j                   j                  | j                        }| j                  d   }t	        d'i d| j                  j                  d      d| j                  j                  d      d| j                  j                  d      dt        | j                  j                  d            d| j                  j                  d      d| j                  j                  d      d	| j                  j                  d	      d
| j                  j                  d
      d| j                  j                  d      d| j                  j                  d      dt        | j                  j                  d            dt        | j                  j                  d            d| j                  j                  d      d| j                  j                  d      dt        | j                  j                  d            d| j                  j                  d      }| j                  j                  d      r| j                  j                  d      j                         D ]  \  }}|j                         |k7  r,| j                  j                  dj                  |             ||vrLt        |t              s6| j                  j                  dj                  |t        |                   |||<   | j                  j                  dj                  |              d}g }g }g }	g }
|D cg c]  }|d   | j                  k(  s| }}|r|D ]  }|dk(  r5d}|	j!                  |d          | j                   j#                  |d          = | j$                  |d   fi |\  }}|sYd}| j                   j'                  |d   |       |j!                  |d          |j!                  |d   |d   |di        nh|d k(  rc | j$                  t	               fi |\  }}|rCd}|
j!                  | j                         | j                   j)                  | j                  |       |r| j                  j*                  s	 | j                   j-                          d#}| j0                  d$k(  rd%}| j                  j5                  | j0                  |d       | j                  j7                  | j0                  | j8                  d       | j                  j;                  | j0                  | j<                  d       | j                  j?                  |||	||
&       y c c}w # t.        $ r@}| j                  j                  d!| j0                  d"t3        |             Y d }~d }~ww xY w)(Nstatehostnameportr&   identities_onlyr"   remote_userstrict_host_key_checkinguser_known_hosts_fileproxycommand	proxyjumphost_key_algorithmsforward_agentadd_keys_to_agentcontrolmastercontrolpathcontrolpersistdynamicforwardother_optionsz0The other_options key {key!r} must be lower case)keyr'   zMThe other_options value provided for key {key!r} must be a string, got {type})rK   typez(Multiple values provided for key {key!r}Fr$   absentToptions)oldnewpresentzFailed to write to z due to permission issue: 0600z/etc/ssh/ssh_config0644)changedhosts_changedhosts_removedhosts_change_diffhosts_addedr   ) r.   search_hostr$   r*   dictr+   r   r   itemslowerr(   r)   format
isinstancer
   rL   appenddelete_hostchange_hostupdate_hostadd_host
check_modewrite_to_ssh_configPermissionErrorr,   r	   set_mode_if_differentset_owner_if_differentr"   set_group_if_differentr#   	exit_json)r1   hosts_resultr:   argsrK   r   config_changedrU   rW   rV   rX   r$   rT   rN   	perm_exec	perm_modes                   r   ensure_statezSSHConfig.ensure_state
  s$   {{..tyy9G$ 
[[__Z0
(
 ++///:
 )9J)KL	

 /
 &*[[__5O%P
 #'++//2I"J
 8
 kkook2
 !%0E F
 't{{'GH
 +4;;??;N+OP
 ++///:
 6
 (8H(IJ
   ;;??+;<!
$ ;;???+"kkooo>DDF 	j
U99;#%KK)).`.g.glo.g.p)qd?%e\:--  3B  3I  3I  NQ OS  TY  OZ 3I 3[- \ %DIKK)).X._._dg._.h)i	j )5Sf9RSS$ H$%)N!((f6KK++DL9 (8t'7'7Y'P4'P$GW)-//VgF%,,T&\:)00 L'+I'.+2 ( i/t//?$?GW!%""499-$$TYY8$++"8"8x//1
 I#88"	KK--d.>.>	5QKK..t/?/?ERKK..t/?/?USn,9,90A*5	 	 	7] TD # x%%OSO_O_ajktauv & x xxs$   7UUU# #	V,,5V''V,c                 R   t        |       } d}|j                         D ]  \  }}d|v r|j                  dd      }|s| j                  |      s0| |= d}6| j                  |      |k7  sKt	        | j                  |      t
              r|| j                  |      v r~|| |<   d} || fS )NF_ T)r   r[   replacer+   r^   list)rN   kwargsrT   kvs        r   ra   zSSHConfig.change_hoste  s    7#LLN 
	DAqaxIIc2&;;q>
"GQ1$jQ.NSTX_XcXcdeXfSf

	 r   N)__name__
__module____qualname__r2   r-   rp   staticmethodra   r   r   r   r   r      s(    "	kY7v    r   r   c                     t        t        d(i dt        d d      dt        dd      dt        d      d	t        dd
      dt        d      dt        d      dt        d      dt        d      dt        dd       dt        dd       dt        d      dt        d      dt        d      dt        d d      dt        ddddg      dt        dd g d      d t        dd g d!      d"t        dd       d#t        dd       d$t        d      d%t        d d      d&t        dd       dd%dgddgg'      } t        |       }|j                          y ))Nr#   str)defaultrL   r$   T)rL   requiredr;   )rL   rC   F)rL   no_logr&   r5   r=   boolrJ   rZ   r<   rA   )rL   r   rB   rD   rE   r>   r%   r:   rQ   rM   )rL   r   choicesr?   )r   r   askz
accept-newrF   )r   r   r   autoautoaskrG   rH   rI   r"   r@   )argument_specsupports_check_modemutually_exclusiver   )r   rZ   r   rp   )r(   ssh_config_objs     r   mainr   x  s    
t%0
540
 u%
 !%% >	

 F+
 !f-
 F+
 5!
 5$7
 t4
 F+
 #/
 %(
 !F;
 E9y(>ST
  &*:&!
* E4Ahi+
, %6-
.  UD9/
0  U+1
2 d/3
4 #'E4"@5
8 !&'[)
="FH v&N!r   __main__)
__future__r   r   r   rL   __metaclass__DOCUMENTATIONEXAMPLESRETURNr4   copyr   ansible.module_utils.basicr   r   +ansible.module_utils.common.text.convertersr	   ansible.module_utils.sixr
   Dansible_collections.community.general.plugins.module_utils._stormsshr   r   r   >ansible_collections.community.general.plugins.module_utils.sshr   r   r   objectr   r   ry   r   r   r   <module>r      s~    A @IV&$
L 
  J A 1 C  C `H  H V&"R zF r   