
    Vh)                        d dl mZ dZdZd dlmZ d dlmZmZm	Z	 d dl
mZ 	 d dlmZ d dlmZ d d	lmZ d
Z G d deee	      Zy# e$ r dZY w xY w)    )annotationsa(  
name: linode
author:
  - Luke Murphy (@decentral1se)
short_description: Ansible dynamic inventory plugin for Linode.
requirements:
  - linode_api4 >= 2.0.0
description:
  - Reads inventories from the Linode API v4.
  - Uses a YAML configuration file that ends with linode.(yml|yaml).
  - Linode labels are used by default as the hostnames.
  - The default inventory groups are built from groups (deprecated by
    Linode) and not tags.
extends_documentation_fragment:
  - constructed
  - inventory_cache
options:
  cache:
    version_added: 4.5.0
  cache_plugin:
    version_added: 4.5.0
  cache_timeout:
    version_added: 4.5.0
  cache_connection:
    version_added: 4.5.0
  cache_prefix:
    version_added: 4.5.0
  plugin:
    description: Marks this as an instance of the 'linode' plugin.
    type: string
    required: true
    choices: ['linode', 'community.general.linode']
  ip_style:
    description: Populate hostvars with all information available from the Linode APIv4.
    type: string
    default: plain
    choices:
      - plain
      - api
    version_added: 3.6.0
  access_token:
    description: The Linode account personal access token.
    type: string
    required: true
    env:
      - name: LINODE_ACCESS_TOKEN
  regions:
    description: Populate inventory with instances in this region.
    default: []
    type: list
    elements: string
  tags:
    description: Populate inventory only with instances which have at least one of the tags listed here.
    default: []
    type: list
    elements: string
    version_added: 2.0.0
  types:
    description: Populate inventory with instances with this type.
    default: []
    type: list
    elements: string
  strict:
    version_added: 2.0.0
  compose:
    version_added: 2.0.0
  groups:
    version_added: 2.0.0
  keyed_groups:
    version_added: 2.0.0
a^  
---
# Minimal example. `LINODE_ACCESS_TOKEN` is exposed in environment.
plugin: community.general.linode

---
# You can use Jinja to template the access token.
plugin: community.general.linode
access_token: "{{ lookup('ini', 'token', section='your_username', file='~/.config/linode-cli') }}"
# For older Ansible versions, you need to write this as:
# access_token: "{{ lookup('ini', 'token section=your_username file=~/.config/linode-cli') }}"

---
# Example with regions, types, groups and access token
plugin: community.general.linode
access_token: foobar
regions:
  - eu-west
types:
  - g5-standard-2

---
# Example with keyed_groups, groups, and compose
plugin: community.general.linode
access_token: foobar
keyed_groups:
  - key: tags
    separator: ''
  - key: region
    prefix: region
groups:
  webservers: "'web' in (tags|list)"
  mailservers: "'mail' in (tags|list)"
compose:
  # By default, Ansible tries to connect to the label of the instance.
  # Since that might not be a valid name to connect to, you can
  # replace it with the first IPv4 address of the linode as follows:
  ansible_ssh_host: ipv4[0]
  ansible_port: 2222

---
# Example where control traffic limited to internal network
plugin: community.general.linode
access_token: foobar
ip_style: api
compose:
  ansible_host: "ipv4 | community.general.json_query('[?public==`false`].address') | first"
)AnsibleError)BaseInventoryPluginConstructable	Cacheable)make_unsafe)LinodeClient)Instance)ApiErrorTFc                  d     e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Z fdZd fd	Z xZS )InventoryModulezcommunity.general.linodec                    | j                  d      }| j                  j                  |      r| j                  j                  |d      }|t	        d      t        |      | _        y)zBuild the Linode client.access_tokenF)variabledisable_lookupsNzHCould not retrieve Linode access token from plugin configuration sources)
get_optiontemplaris_templatetemplater   r	   client)selfloaderr   s      n/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/inventory/linode.py_build_clientzInventoryModule._build_client   sd     ~6<<##L1<<00,X]0^L4 
 #<0    c                    	 | j                   j                  j                         | _        y# t        $ r}t	        d|       d}~ww xY w)z:Retrieve Linode instance information from cloud inventory.zLinode client raised: N)r   linode	instancesLinodeApiErrorr   )r   	exceptions     r   _get_instances_inventoryz(InventoryModule._get_instances_inventory   sG    	E![[//99;DN 	E!7	{CDD	Es   ), 	AAAc           	         t        t        d| j                  D cg c]  }|j                   c}            | _        | j                  D ]  }| j
                  j                  |        yc c}w )z4Add Linode instance groups to the dynamic inventory.N)setfilterr   grouplinode_groups	inventory	add_group)r   instancelinode_groups      r   _add_groupszInventoryModule._add_groups   sg     4 >>  
 !.. 	3LNN$$\2	3s   A*c                   | j                  d      }|r7| j                  D cg c]  }|j                  j                  |v r| c}| _        | j                  d      }|r7| j                  D cg c]  }|j                  j                  |v r| c}| _        | j                  d      }|r5| j                  D cg c]  t        fd|D              r c}| _        yyc c}w c c}w c c}w )z1Filter instances by user specified configuration.regionstypestagsc              3  :   K   | ]  }|j                   v   y wN)r/   ).0tagr)   s     r   	<genexpr>z4InventoryModule._filter_by_config.<locals>.<genexpr>   s     <shmm+<s   N)r   r   regionidtypeany)r   r-   r)   r.   r/   s     `  r   _filter_by_configz!InventoryModule._filter_by_config   s    //),)-%??%%0 DN
 ()-%==##u, DN
 v&)-%<t<< DN s   !C-!C$8C)c                    | j                   D ]<  }| j                  j                  t        |j                        |j
                         > y)z5Add instance names to their dynamic inventory groups.)r%   N)r   r'   add_hostr   labelr%   )r   r)   s     r   _add_instances_to_groupsz(InventoryModule._add_instances_to_groups   s;     	WHNN##K$?x~~#V	Wr   c                :   | j                  d      }| j                  D ]u  }|j                  }t        |j                        }|D ]5  }|dk(  r|dv r| j
                  j                  ||t        ||                7 |dk(  se|j                  j                  j                  |j                  j                  j                  z   }||j                  j                  j                  |j                  j                  j                  gz  }||j                  j                  j                  z  }t        d |D              D ]U  }| j
                  j                  ||t        | j!                  |D cg c]  }|j"                  |k(  s| c}                   W x yc c}w )z4Add hostvars for instances in the dynamic inventory.ip_styleapi)ipv4ipv6c              3  4   K   | ]  }|j                     y wr1   )r7   )r2   ips     r   r4   z>InventoryModule._add_hostvars_for_instances.<locals>.<genexpr>   s     "9r277"9s   N)r   r   	_raw_jsonr   r<   r'   set_variableipsrA   publicprivaterB   slaac
link_localpoolsr#   _ip_datar7   )	r   r?   r)   hostvarshostnamehostvar_keyrG   ip_typerD   s	            r   _add_hostvars_for_instancesz+InventoryModule._add_hostvars_for_instances   s`   ??:. 	H))H"8>>2H' u$8H)H++ 56 5 ll''..1B1B1J1JJ))//1B1B1M1MNNx||((...""9S"99 GNN// #DMM2Z"rwwRYGY22Z$[\!	( 3[s   *F?Fc                    g }t        |      D ]a  }|j                  |j                  |j                  |j                  |j
                  |j                  |j                  |j                  d       c |S )N)addresssubnet_maskgatewayrH   prefixrdnsr7   )	listappendrT   rU   rV   rH   rW   rX   r7   )r   ip_listdatarD   s       r   rM   zInventoryModule._ip_data   sc    w- 	BKK!zz#%>>!zz ii iiGGGG
	 r   c                T    | j                   D cg c]  }|j                   c}S c c}w r1   )r   rE   )r   is     r   _cacheable_inventoryz$InventoryModule._cacheable_inventory   s    %)^^4444s   %c                   | j                  d      }| j                          | j                          | j                          | j	                          | j
                  D ]  }t        |j                        }| j                  j                  |      j                         }| j                  | j                  d      |||       | j                  | j                  d      |||       | j                  | j                  d      |||        y )Nstrictgroups)ra   keyed_groupscompose)r   r9   r+   r=   rR   r   r   r<   r'   get_hostget_vars_add_host_to_composed_groups_add_host_to_keyed_groups_set_composite_vars)r   ra   r)   rO   	variabless        r   populatezInventoryModule.populate   s    * %%'((* 	H"8>>2H//9BBDI--)	 . 
 **/	 + 
 $$	*	 % 	r   c                    d}t         t        |   |      r0|j                  d      rd}|S | j                  j                  d       |S )a&  Verify the Linode configuration file.

        Return true/false if the config-file is valid for this plugin

        Args:
            str(path): path to the config
        Kwargs:
            None
        Raises:
            None
        Returns:
            bool(valid): is valid config fileF)zlinode.yamlz
linode.ymlTz<Inventory source not ending in "linode.yaml" or "linode.yml")superr   verify_fileendswithdisplayvvv)r   pathvalid	__class__s      r   rn   zInventoryModule.verify_file  sL     $3D9}}:;    !_`r   c                   t         t        |   |||       d| _        t        st        d      | j                  |       | j                  |      }|r| j                  d      }d}|r1	 | j                  |   D cg c]  }t        d|d   |       c}| _        | j                  !| j                  |       | j                          |r| j                         | j                  |<   | j                          yc c}w # t        $ r d}Y ow xY w)z-Dynamically parse Linode the cloud inventory.Nz9the Linode dynamic inventory plugin requires linode_api4.cacheFr6   T)rm   r   parser   
HAS_LINODEr   _read_config_dataget_cache_keyr   _cacher
   KeyErrorr   r!   r_   rk   )	r   r'   r   rr   rv   	cache_keyupdate_cacher^   rt   s	           r   rw   zInventoryModule.parse0  s    ot*9fdCZ[[t$&&t,	OOG,E$FJkkR[F\!](44!"<!] >>!v&))+%)%>%>%@DKK	" "^ $#$s$   )C; :C6C; 6C; ;D	D	)T)__name__
__module____qualname__NAMEr   r!   r+   r9   r=   rR   rM   r_   rk   rn   rw   __classcell__)rt   s   @r   r   r      sF    %D1E3.W
4 56* r   r   N)
__future__r   DOCUMENTATIONEXAMPLESansible.errorsr   ansible.plugins.inventoryr   r   r   Aansible_collections.community.general.plugins.plugin_utils.unsafer   linode_api4r	   linode_api4.objects.linoder
   linode_api4.errorsr   r   rx   ImportErrorr    r   r   <module>r      se    #FP/b ( S S Y(3=J
)=) 	  Js   A AA