
    Vh,"                         d dl mZmZmZ eZdZdZd dlZd dl	m
Z
mZ d dlmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZmZmZ  G d deee      Zy)    )absolute_importdivisionprint_functionu  
name: digitalocean
author:
  - Janos Gerzson (@grzs)
  - Tadej Borovšak (@tadeboro)
  - Max Truxa (@maxtruxa)
short_description: DigitalOcean Inventory Plugin
version_added: "1.1.0"
description:
  - DigitalOcean (DO) inventory plugin.
  - Acquires droplet list from DO API.
  - Uses configuration file that ends with '(do_hosts|digitalocean|digital_ocean).(yaml|yml)'.
extends_documentation_fragment:
  - community.digitalocean.digital_ocean.documentation
  - constructed
  - inventory_cache
options:
  plugin:
    description:
      - The name of the DigitalOcean Inventory Plugin,
        this should always be C(community.digitalocean.digitalocean).
    required: true
    choices: ['community.digitalocean.digitalocean']
  attributes:
    description: >-
      Droplet attributes to add as host vars to each inventory host.
      Check out the DO API docs for full list of attributes at
      U(https://docs.digitalocean.com/reference/api/api-reference/#operation/list_all_droplets).
    type: list
    elements: str
    default:
      - id
      - name
      - networks
      - region
      - size_slug
  var_prefix:
    description:
      - Prefix of generated varible names (e.g. C(tags) -> C(do_tags))
    type: str
    default: 'do_'
  pagination:
    description:
      - Maximum droplet objects per response page.
      - If the number of droplets related to the account exceeds this value,
        the query will be broken to multiple requests (pages).
      - DigitalOcean currently allows a maximum of 200.
    type: int
    default: 200
  filters:
    description:
      - Filter hosts with Jinja templates.
      - If no filters are specified, all hosts are added to the inventory.
    type: list
    elements: str
    default: []
    version_added: '1.5.0'
a  
# Using keyed groups and compose for hostvars
plugin: community.digitalocean.digitalocean
oauth_token: '{{ lookup("pipe", "./get-do-token.sh") }}'
attributes:
  - id
  - name
  - memory
  - vcpus
  - disk
  - size
  - image
  - networks
  - volume_ids
  - tags
  - region
keyed_groups:
  - key: do_region.slug
    prefix: 'region'
    separator: '_'
  - key: do_tags | lower
    prefix: ''
    separator: ''
compose:
  ansible_host: do_networks.v4 | selectattr('type','eq','public')
    | map(attribute='ip_address') | first
  class: do_size.description | lower
  distro: do_image.distribution | lower
filters:
  - '"kubernetes" in do_tags'
  - 'do_region.slug == "fra1"'
N)AnsibleErrorAnsibleParserError)to_safe_group_name)	to_native)Request)URLError	HTTPError)BaseInventoryPluginConstructable	Cacheablec                   X     e Zd ZdZ ee      Z fdZd Zd Z	d Z
ddZd	 fd	Z xZS )
InventoryModulez#community.digitalocean.digitaloceanc                     d}t         t        |   |      r0|j                  d      rd}|S | j                  j                  d       |S )NF)zdo_hosts.yamlzdo_hosts.ymlzdigitalocean.yamlzdigitalocean.ymlzdigital_ocean.yamlzdigital_ocean.ymlTzSkipping due to inventory source file name mismatch. The file name has to end with one of the following: do_hosts.yaml, do_hosts.yml digitalocean.yaml, digitalocean.yml, digital_ocean.yaml, digital_ocean.yml.)superr   verify_fileendswithdisplayvvv)selfpathvalid	__class__s      y/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/digitalocean/plugins/inventory/digitalocean.pyr   zInventoryModule.verify_filey   sV    $3D9}}	     =     c                 |    | j                  |      }i | j                  _        | j                  j                  |      S )N)
get_optiontemplaravailable_variablestemplate)r   optionvalues      r   _template_optionz InventoryModule._template_option   s1    '+-(||$$U++r   c                    | j                  d      }ddj                  |      d}| j                  d      }d}| j                  d      r| j                  d      }|dt        |      z   z  }t	        || j                  d	      
      | _        g }	 |r| j                  j                  dj                  |             t        j                  | j
                  j                  |            }|j                  |d          |j                  di       j                  di       j                  d      }|r|S # t        $ r t        d      t        t        f$ r}t        |      d }~ww xY w)Noauth_tokenzapplication/jsonz
Bearer {0})zContent-TypeAuthorization
paginationzhttps://api.digitalocean.com/v2baseurlz/droplets?per_page=timeout)headersr+   zSending request to {0}dropletslinkspagesnextz&something went wrong with JSON loading)r%   formatr   strr
   reqr   r   jsonloadgetextend
ValueErrorr   r   r   )r   	api_tokenr,   r)   urlpayloadresponseerrors           r   _get_payloadzInventoryModule._get_payload   sH   ))-8	.)00;
 __\2
/??9%//),C$s:66 7DOOI4NO		,  !9!@!@!EF99TXX\\#%67x
34ll7B/33GR@DDVL	    	O$%MNN)$ 	,$U++	,s   B!D4 4"E&E!!E&c                 r   | j                  d      }| j                  d      }| j                  d      }| j                  d      }|D ]m  }|j                  d      }|si }|j                         D ]  \  }	}
|	|v s|
|||	z   <    | j                  ||||      s+| j                  j                  dj                  |             ~| j                  j                  |       |j                         D ]"  \  }	}
| j                  j                  ||	|
       $ | j                  | j                  d      | j                  j                  |      j                         ||       | j                  | j                  d      t               ||       | j                  | j                  d	      t               ||       p y )
N
attributes
var_prefixstrictfiltersnamez!Host {0} did not pass all filterscomposegroupskeyed_groups)r   r6   items_passes_filtersr   r   r1   	inventoryadd_hostset_variable_set_composite_varsget_hostget_vars_add_host_to_composed_groupsdict_add_host_to_keyed_groups)r   recordsr@   rA   rB   host_filtersrecord	host_name	host_varskvs              r   	_populatezInventoryModule._populate   s   __\2
__\2
*y1 "	F

6*II 21
?01Ij1n-2 ''iFS  !D!K!KI!VW NN##I. ") =1++Iq!<= $$	*''	2;;=	 --)469f **/FA"	r   c                     |r,t        |t              r|D ]  }	 | j                  ||      s y y# t        $ r2}|r%t	        dj                  ||t        |                  Y d }~ yd }~ww xY w)NFz4Could not evaluate host filter {0} for host {1}: {2}T)
isinstancelist_compose	Exceptionr   r1   r	   )r   rC   	variableshostrB   r"   es          r   rI   zInventoryModule._passes_filters   s}    z'40# !!==9=$ >!  ! !*RYY ($	!  !!s   0	A+'A&&A+c                 |   t         t        |   |||       | j                  |       | j	                  |      }| j                  d      xr |}| j                  d      xr | }d }|r	 | j                  |   }|| j                         }|r|| j                  |<   | j                  |       y # t        $ r d}Y Bw xY w)NcacheT)
r   r   parse_read_config_dataget_cache_keyr   _cacheKeyErrorr>   rZ   )
r   rJ   loaderr   rd   	cache_key	use_cacheupdate_cacherS   r   s
            r   re   zInventoryModule.parse   s    ot*9fdCt$ &&t,	OOG,6	w/=I$++i0 ?'')G%,DKK	"w  $#$s   )B- -B;:B;)F)T)__name__
__module____qualname__NAMEstaticmethodr   _sanitize_group_namer   r%   r>   rZ   rI   re   __classcell__)r   s   @r   r   r   o   s:    0D ((:;0,
>'R"   r   r   )
__future__r   r   r   type__metaclass__DOCUMENTATIONEXAMPLESr4   ansible.errorsr   r   ansible.inventory.groupr   ansible.module_utils._textr	   ansible.module_utils.urlsr
   +ansible.module_utils.six.moves.urllib.errorr   r   ansible.plugins.inventoryr   r   r   r    r   r   <module>r      sP    A @9vB  ; 6 0 - K S SW )=) W r   