
    Vh@                        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
mZ dZ	 d dlZdZdZ	 d dlZd dlmZmZ er eej,                         ed	      k\  rdZnej,                  d	k\  rdZd d
lmZmZ  G d de      Z G d de      Z G d de      Z G d de      Zd Z d Z!e"dk(  r e!        yy# e$ r dZY w xY w# e$ r dZY w xY w# e$ r Y iw xY w)    )absolute_importdivisionprint_functiona#  
---
module: digital_ocean
short_description: Create/delete a droplet/SSH_key in DigitalOcean
deprecated:
  removed_in: 2.0.0  # was Ansible 2.12
  why: Updated module to remove external dependency with increased functionality.
  alternative: Use M(community.digitalocean.digital_ocean_droplet) instead.
description:
     - Create/delete a droplet in DigitalOcean and optionally wait for it to be 'running', or deploy an SSH key.
author: "Vincent Viallet (@zbal)"
options:
  command:
    description:
     - Which target you want to operate on.
    default: droplet
    choices: ['droplet', 'ssh']
    type: str
  state:
    description:
     - Indicate desired state of the target.
    default: present
    choices: ['present', 'active', 'absent', 'deleted']
    type: str
  api_token:
    description:
     - DigitalOcean api token.
    type: str
    aliases:
      - API_TOKEN
  id:
    description:
     - Numeric, the droplet id you want to operate on.
    aliases: ['droplet_id']
    type: int
  name:
    description:
     - String, this is the name of the droplet - must be formatted by hostname rules, or the name of a SSH key.
    type: str
  unique_name:
    description:
     - Bool, require unique hostnames.  By default, DigitalOcean allows multiple hosts with the same name.  Setting this to "yes" allows only one host
       per name.  Useful for idempotence.
    type: bool
    default: 'no'
  size_id:
    description:
     - This is the slug of the size you would like the droplet created with.
    type: str
  image_id:
    description:
     - This is the slug of the image you would like the droplet created with.
    type: str
  region_id:
    description:
     - This is the slug of the region you would like your server to be created in.
    type: str
  ssh_key_ids:
    description:
     - Optional, array of SSH key (numeric) ID that you would like to be added to the server.
    type: list
    elements: str
  virtio:
    description:
     - "Bool, turn on virtio driver in droplet for improved network and storage I/O."
    type: bool
    default: 'yes'
  private_networking:
    description:
     - "Bool, add an additional, private network interface to droplet for inter-droplet communication."
    type: bool
    default: 'no'
  backups_enabled:
    description:
     - Optional, Boolean, enables backups for your droplet.
    type: bool
    default: 'no'
  user_data:
    description:
      - opaque blob of data which is made available to the droplet
    type: str
  ipv6:
    description:
      - Optional, Boolean, enable IPv6 for your droplet.
    type: bool
    default: 'no'
  wait:
    description:
     - Wait for the droplet to be in state 'running' before returning.  If wait is "no" an ip_address may not be returned.
    type: bool
    default: 'yes'
  wait_timeout:
    description:
     - How long before wait gives up, in seconds.
    default: 300
    type: int
  ssh_pub_key:
    description:
     - The public SSH key you want to add to your account.
    type: str

notes:
  - Two environment variables can be used, DO_API_KEY and DO_API_TOKEN. They both refer to the v2 token.
  - As of Ansible 1.9.5 and 2.0, Version 2 of the DigitalOcean API is used, this removes C(client_id) and C(api_key) options in favor of C(api_token).
  - If you are running Ansible 1.9.4 or earlier you might not be able to use the included version of this module as the API version used has been retired.
    Upgrade Ansible or, if unable to, try downloading the latest version of this module from github and putting it into a 'library' directory.
requirements:
  - "python >= 2.6"
  - dopy
a  
# Ensure a SSH key is present
# If a key matches this name, will return the ssh key id and changed = False
# If no existing key matches this name, a new key is created, the ssh key id is returned and changed = False

- name: Ensure a SSH key is present
  community.digitalocean.digital_ocean:
    state: present
    oauth_token: "{{ lookup('ansible.builtin.env', 'DO_API_TOKEN') }}"
    command: ssh
    name: my_ssh_key
    ssh_pub_key: 'ssh-rsa AAAA...'

# Will return the droplet details including the droplet id (used for idempotence)
- name: Create a new Droplet
  community.digitalocean.digital_ocean:
    state: present
    oauth_token: "{{ lookup('ansible.builtin.env', 'DO_API_TOKEN') }}"
    command: droplet
    name: mydroplet
    size_id: 2gb
    region_id: ams2
    image_id: fedora-19-x64
    wait_timeout: 500
  register: my_droplet

- debug:
    msg: "ID is {{ my_droplet.droplet.id }}"

- debug:
    msg: "IP is {{ my_droplet.droplet.ip_address }}"

# Ensure a droplet is present
# If droplet id already exist, will return the droplet details and changed = False
# If no droplet matches the id, a new droplet will be created and the droplet details (including the new id) are returned, changed = True.

- name: Ensure a droplet is present
  community.digitalocean.digital_ocean:
    state: present
    oauth_token: "{{ lookup('ansible.builtin.env', 'DO_API_TOKEN') }}"
    command: droplet
    id: 123
    name: mydroplet
    size_id: 2gb
    region_id: ams2
    image_id: fedora-19-x64
    wait_timeout: 500

# Create a droplet with ssh key
# The ssh key id can be passed as argument at the creation of a droplet (see ssh_key_ids).
# Several keys can be added to ssh_key_ids as id1,id2,id3
# The keys are used to connect as root to the droplet.

- name: Create a droplet with ssh key
  community.digitalocean.digital_ocean:
    state: present
    oauth_token: "{{ lookup('ansible.builtin.env', 'DO_API_TOKEN') }}"
    ssh_key_ids: 123,456
    name: mydroplet
    size_id: 2gb
    region_id: ams2
    image_id: fedora-19-x64
N)VersionTF)DoError	DoManagerz0.3.2)AnsibleModuleenv_fallbackc                        e Zd Z fdZ xZS )TimeoutErrorc                 :    t         t        |   |       || _        y N)superr   __init__id)selfmsgid_	__class__s      x/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/digitalocean/plugins/modules/digital_ocean.pyr   zTimeoutError.__init__   s    lD*3/    )__name__
__module____qualname__r   __classcell__)r   s   @r   r   r      s     r   r   c                       e Zd Zd Zy)JsonfyMixInc                     | j                   S r   )__dict__r   s    r   to_jsonzJsonfyMixIn.to_json   s    }}r   N)r   r   r   r!    r   r   r   r      s    r   r   c                       e Zd ZdZd Zd ZddZd ZddZd Z	e
d        Ze
	 	 	 	 	 	 dd	       Ze
dd
       Ze
d        Zy)DropletNc                 H    d| _         | j                  j                  |       y )Nnew)statusr   update)r   droplet_jsons     r   r   zDroplet.__init__   s    \*r   c                      | j                   dk(  S )Nactive)r'   r    s    r   is_powered_onzDroplet.is_powered_on   s    {{h&&r   c                 p   |rx|j                         D ]  \  }}t        | ||        |j                  di       }|j                  dg       D ]+  }|d   dk(  rt        | d|d          t        | d|d          - y | j                  j	                  | j
                        }|d   r| j                  |       y y )Nnetworksv6typepublicpublic_ipv6_address
ip_addressprivate_ipv6_address)itemssetattrgetmanagershow_dropletr   update_attr)r   attrskvr.   networkjsons          r   r:   zDroplet.update_attr   s     $1a#$yyR0H#<<b1 Q6?h.D"79NOD"8',:OP	Q <<,,TWW5DL!  & "r   c                     | j                   dk7  rt        d      | j                  j                  | j                        }| j                  |       y )NoffzCan only power on a closed one.)r'   AssertionErrorr8   power_on_dropletr   r:   )r   r?   s     r   power_onzDroplet.power_on  s@    ;;% !BCC||,,TWW5r   c                    | j                         ry | j                  dk(  r| j                          |rt        j                         |z   }t        j                         |k  rpt        j
                  d       | j                          | j                         r#| j                  st        d| j                        y t        j                         |k  rpt        d| j                        y )NrA   
   zNo ip is found.z Wait for droplet running timeout)
r,   r'   rD   time	monotonicsleepr:   r3   r   r   )r   waitwait_timeoutend_times       r   ensure_powered_onzDroplet.ensure_powered_on  s    ;;%MMO~~',6H.."X-

2  "%%'??*+<dggFF .."X- A477KK r   c                 P    | j                   j                  | j                  d      S )NT)
scrub_data)r8   destroy_dropletr   r    s    r   destroyzDroplet.destroy  s     ||++DGG+EEr   c                 *    t        d |d      | _        y N   )api_versionr   r8   cls	api_tokens     r   setupzDroplet.setup      iQ?r   c                     t        |      j                         }t        |      j                         }t        |
      j                         }| j                  j                  |||||||||	|
      } | |      }|S )N)ssh_key_idsvirtioprivate_networkingbackups_enabled	user_dataipv6)strlowerr8   new_droplet)rX   namesize_idimage_id	region_idr]   r^   r_   r`   ra   rb   private_networking_lowerbackups_enabled_lower
ipv6_lowerr?   droplets                   r   addzDroplet.add#  s     $''9#:#@#@#B  #O 4 : : <Y__&
{{&&#71 ' 
 d)r   c                     |s|sy| j                         }|D ]  }|j                  |k(  s|c S  |D ]  }|j                  |k(  s|c S  yNF)list_allr   rf   )rX   r   rf   dropletsrm   s        r   findzDroplet.findC  s^    $<<>   	GzzR	
   	G||t#	 r   c                 `    | j                   j                         }t        t        | |            S r   )r8   all_active_dropletslistmaprX   r?   s     r   rq   zDroplet.list_allV  s%    {{..0CTN##r   r   )T,  )NTFFNF)NN)r   r   r   r8   r   r,   r:   rD   rM   rQ   classmethodrZ   rn   rs   rq   r"   r   r   r$   r$      s    G+''L"F @ @    >  $ $ $r   r$   c                   `    e Zd ZdZd ZeZd Zed        Zed        Z	ed        Z
ed        Zy)SSHNc                 :    | j                   j                  |       y r   )r   r(   )r   ssh_key_jsons     r   r   zSSH.__init___  s    \*r   c                 N    | j                   j                  | j                         y)NT)r8   destroy_ssh_keyr   r    s    r   rQ   zSSH.destroyd  s    $$TWW-r   c                 *    t        d |d      | _        y rS   rV   rW   s     r   rZ   z	SSH.setuph  r[   r   c                 ^    |sy| j                         }|D ]  }|j                  |k(  s|c S  yrp   )rq   rf   )rX   rf   keyskeys       r   rs   zSSH.findl  s8    ||~ 	Cxx4
	 r   c                 `    | j                   j                         }t        t        | |            S r   )r8   all_ssh_keysrv   rw   rx   s     r   rq   zSSH.list_allv  s%    {{'')CTN##r   c                 J    | j                   j                  ||      } | |      S r   )r8   new_ssh_key)rX   rf   key_pubr?   s       r   rn   zSSH.add{  s"    {{&&tW54yr   )r   r   r   r8   r   r:   rQ   rz   rZ   rs   rq   rn   r"   r   r   r|   r|   \  sj    G+ K @ @   $ $  r   r|   c                      fd} j                   d   }d} j                   d   } j                   d   }|dk(  rt        j                  |       |dv r6t        j                   j                   d   	      }|s+ j                   d
   rt        j                   |d            }|st        j	                   |d       |d       |d       |d       j                   d    j                   d    j                   d    j                   d    j                   j                  d       j                   d   
      }|j                         rd}|j                   |d       |d              j                  ||j                                y |dv rt        j                   j                   d         }|s+ j                   d
   rt        j                   |d            }|s j                  dd       |j                           j                  d       y y |d k(  rt        j                  |        |d      }|dv rvt        j                  |      }|r! j                  d|j                         !       t        j	                  | |d"            } j                  d|j                         !       y |dv rPt        j                  |      }|s j                  dd#|z         |j                           j                  d       y y y )$Nc                 T    j                   |    }|j                  d| z         |S )NzUnable to load %sr   )params	fail_json)r<   r=   modules     r   getkeyordiezcore.<locals>.getkeyordie  s2    MM!9!4q!89r   rY   Tcommandstaterm   )r+   presentr   )r   unique_namerf   )rf   rg   rh   ri   r]   r^   r_   r`   ra   rb   )
rf   rg   rh   ri   r]   r^   r_   r`   ra   rb   FrJ   rK   )rJ   rK   )changedrm   )absentdeletedzThe droplet is not found.)r   r   )r   ssh)r   ssh_keyssh_pub_keyz)SSH key with the name of %s is not found.)r   r$   rZ   rs   rn   r7   r,   rM   	exit_jsonr!   rQ   r|   )	r   r   rY   r   r   r   rm   rf   r   s	   `        r   corer     s    k*IGmmI&GMM'"E)i ))llfmmD&9l:G
 v}}];!,,K,?,@ !++$V,'	2(4)+6 &m <!==2'-}}5I'J$*MM2C$D$mm//<v. &  $$&%% ({>7R &  Wgoo6GH++ll6==#67G
 v}}];!,,K,?,@  4O POOT* ,  
E			)6"))((4.C   F''$M :;CT3;;=A++((4.C  !CdJ !  KKMT* , 
r   c                     t        t        d1i dt        ddgd      dt        g dd      dt        d	gd
t        ddgf      dt        d      dt               dt               dt               dt        ddd      dt        dd
      dt        dd      dt        dd      dt        dgd       d!t        dd      d"t        d #      d$t        dd      d%t        dd
      d&t        d'd(      d)t        d      g d*fdd)gdd)gdd)gfddgf+      } t        st        s| j                  d,-       t        s| j                  d.-       	 t        |        y # t        $ r0}| j                  t        |      |j                  /       Y d }~y d }~wt        t        f$ r8}| j                  t        |      t        j                         0       Y d }~y d }~ww xY w)2Nr   rm   r   )choicesdefaultr   )r+   r   r   r   r   rY   	API_TOKENTDO_API_TOKEN
DO_API_KEY)aliasesno_logfallbackrf   rc   )r0   rg   rh   ri   r]   rv   F)r0   elementsr   r^   bool)r0   r   r_   r`   r   
droplet_idint)r   r0   r   ra   )r   rb   rJ   rK   ry   )r   r0   r   )rg   rh   ri   )argument_specrequired_togethermutually_exclusiverequired_one_ofzdopy >= 0.3.2 is required for this module. dopy requires six but six is not installed. Make sure both dopy and six are installed.r   z&dopy >= 0.3.2 required for this module)r   r   )r   	exceptionr"   )r	   dictr
   HAS_DOPYHAS_SIXr   r   r   rc   r   r   	Exception	traceback
format_exc)r   es     r   mainr     s$    
)U!3YG
BI

 $&(FG
 5!
 F
 V
 f
 &5G
 VT2
   $?!
" !fe<#
$ \N7%
& &%8'
( 4()
* 651+
, 640-
. c6/
0 %(1
4 @A&'-(

 )C"FF G9 	 	
 EFGV .SV--Y GSVy/C/C/EFFGs$   E) )	G'2&FG'/.G""G'__main__)#
__future__r   r   r   r0   __metaclass__DOCUMENTATIONEXAMPLESrG   r   packaging.versionr   HAS_PACKAGINGImportErroransible.module_utils.sixansibler   r   dopydopy.managerr   r   __version__ansible.module_utils.basicr	   r
   r   r   objectr   r$   r|   r   r   r   r"   r   r   <module>r      s(   A @m`>@  )M#G 	/ 4##$(88Hw&H C9 & 
m$k m$`"+ "JR+j1Gh zF O
  M  G   		s3   B1 B> =C 1B;:B;>CCCC