Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_sshpublickey.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2023 xuzhang3 (@xuzhang3), Fred-sun (@Fred-sun)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 DOCUMENTATION = '''
12 ---
13 module: azure_rm_sshpublickey
14 version_added: "2.0.0"
15 short_description: Manage ssh public key with vm
16 description:
17 - Create, update or delete the vm public key.
18 options:
19 resource_group:
20 description:
21 - Name of resource group.
22 required: true
23 type: str
24 location:
25 description:
26 - Valid Azure location. Defaults to location of the resource group.
27 type: str
28 name:
29 description:
30 - The name of the SSH public key.
31 required: true
32 type: str
33 public_key:
34 description:
35 - SSH public key used to authenticate to a virtual machine through ssh.
36 - If this property is not initially provided when the resource is created, the publicKey property will be populated when generateKeyPair is called.
37 - If the public key is provided upon resource creation, the provided public key needs to be at least 2048-bit and in ssh-rsa format.
38 type: str
39 state:
40 description:
41 - State of the SSH Public Key. Use C(present) to create or update and C(absent) to delete.
42 default: present
43 type: str
44 choices:
45 - absent
46 - present
47
48 extends_documentation_fragment:
49 - azure.azcollection.azure
50 - azure.azcollection.azure_tags
51
52 author:
53 - xuzhang3 (@xuzhang3)
54 - Fred-sun (@Fred-sun)
55
56 '''
57
58 EXAMPLES = '''
59 - name: Create a SSH Public Key
60 azure_rm_sshpublickey:
61 resource_group: myResourceGroup
62 name: mySshPublicKey
63 public_key: "ssh-rsa ****************************@test.com"
64 tags:
65 testing: testing
66 delete: on-exit
67
68 - name: Generate a pair SSH Public Key
69 azure_rm_sshpublickey:
70 resource_group: myResourceGroup
71 name: mySshPublicKey
72 tags:
73 testing: testing
74 delete: on-exit
75
76 - name: Delete a SSH Public Key
77 azure_rm_sshpublickey:
78 resource_group: myResourceGroup
79 name: mySshPublicKey
80 state: absent
81 '''
82 RETURN = '''
83 state:
84 description:
85 - Current state of the SSH Public Key.
86 returned: always
87 type: complex
88 contains:
89 id:
90 description:
91 - Resource ID.
92 returned: always
93 type: str
94 sample: /subscriptions/xxxx/resourceGroups/xxx/providers/Microsoft.Compute/sshPublicKeys/mySshPublicKeyName
95 location:
96 description:
97 - The Geo-location where the resource lives.
98 returned: always
99 type: str
100 sample: eastus
101 name:
102 description:
103 - Resource name.
104 returned: always
105 type: str
106 sample: mySshPublicKey
107 tags:
108 description:
109 - Resource tags, such as { 'tags1':'value1' }.
110 returned: always
111 type: dict
112 sample: { 'key1':'value1' }
113 public_key:
114 description:
115 - SSH public key used to authenticate to a virtual machine through ssh.
116 returned: always
117 type: str
118 sample: "ssh-rsa **************@test.com"
119 '''
120
121 try:
122 from azure.core.exceptions import ResourceNotFoundError
123 except ImportError:
124 # This is handled in azure_rm_common
125 pass
126
127 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
128
129
130 class AzureRMSshPublicKey(AzureRMModuleBase):
131
132 def __init__(self):
133
134 self.module_arg_spec = dict(
135 resource_group=dict(type='str', required=True),
136 name=dict(type='str', required=True),
137 state=dict(type='str', default='present', choices=['present', 'absent']),
138 location=dict(type='str'),
139 public_key=dict(type='str'),
140 )
141
142 self.resource_group = None
143 self.name = None
144 self.state = None
145 self.location = None
146 self.public_key = None
147
148 self.body = dict()
149
150 self.results = dict(
151 changed=False,
152 state=dict()
153 )
154
155 super(AzureRMSshPublicKey, self).__init__(self.module_arg_spec,
156 supports_tags=True,
157 supports_check_mode=True)
158
159 def exec_module(self, **kwargs):
160
161 for key in list(self.module_arg_spec.keys()) + ['tags']:
162 setattr(self, key, kwargs[key])
163 for key in ['tags', 'public_key']:
164 self.body[key] = kwargs[key]
165
166 resource_group = self.get_resource_group(self.resource_group)
167 if not self.location:
168 # Set default location
169 self.location = resource_group.location
170
171 changed = False
172 results = dict()
173
174 old_response = self.get_by_name()
175
176 if old_response is not None:
177 if self.state == 'present':
178 update_tags, self.body['tags'] = self.update_tags(old_response['tags'])
179 if update_tags or self.body['public_key'] is not None and self.body['public_key'] != old_response['public_key']:
180 changed = True
181 if not self.check_mode:
182 results = self.update_ssh_public_key(self.body)
183 else:
184 results = old_response
185 else:
186 changed = True
187 if not self.check_mode:
188 results = self.delete_ssh_public_key()
189 else:
190 if self.state == 'present':
191 changed = True
192 if not self.check_mode:
193 self.body['location'] = self.location
194 results = self.create_ssh_public_key(self.body)
195 else:
196 changed = False
197 self.log("The SSH Public Key is not exists")
198
199 self.results['changed'] = changed
200 self.results['state'] = results
201
202 return self.results
203
204 def get_by_name(self):
205 response = None
206 try:
207 response = self.compute_client.ssh_public_keys.get(self.resource_group, self.name)
208
209 except ResourceNotFoundError as exec:
210 self.log("Failed to get ssh public keys, Exception as {0}".format(exec))
211
212 return self.to_dict(response)
213
214 def create_ssh_public_key(self, body):
215 response = None
216 try:
217 if body.get('public_key') is None:
218 response = self.to_dict(self.compute_client.ssh_public_keys.create(self.resource_group, self.name, body))
219 response.update(self.to_dict(self.compute_client.ssh_public_keys.generate_key_pair(self.resource_group, self.name)))
220 else:
221 response = self.to_dict(self.compute_client.ssh_public_keys.create(self.resource_group, self.name, body))
222 except Exception as exc:
223 self.fail("Error creating SSH Public Key {0} - {1}".format(self.name, str(exc)))
224
225 return response
226
227 def update_ssh_public_key(self, body):
228 response = None
229 try:
230 response = self.compute_client.ssh_public_keys.update(self.resource_group, self.name, body)
231 except Exception as exc:
232 self.fail("Error updating SSH Public Key {0} - {1}".format(self.name, str(exc)))
233 return self.to_dict(response)
234
235 def delete_ssh_public_key(self):
236 try:
237 self.compute_client.ssh_public_keys.delete(self.resource_group, self.name)
238 except Exception as exc:
239 self.fail("Error deleting SSH Public Key {0} - {1}".format(self.name, str(exc)))
240
241 def to_dict(self, body):
242 results = None
243 if body is not None:
244 if hasattr(body, 'private_key'):
245 results = dict(
246 private_key=body.private_key,
247 id=body.id,
248 public_key=body.public_key
249 )
250 else:
251 results = dict(
252 id=body.id,
253 name=body.name,
254 location=body.location,
255 tags=body.tags,
256 public_key=body.public_key
257 )
258 return results
259
260
261 def main():
262 AzureRMSshPublicKey()
263
264
265 if __name__ == '__main__':
266 main()