This repository has been archived by the owner on Sep 16, 2019. It is now read-only.
forked from mohclips/k5-ansible-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k5_server_console_output.py
230 lines (172 loc) · 7.98 KB
/
k5_server_console_output.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/python
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: k5_server_console_output
short_description: Display the URL to the NoVNC Console
version_added: "1.0"
description:
- returns the openstack console output.
options:
server_name:
description:
- Name of the server.
required: true
default: None
console_length:
description:
- Number of lines to tail from the console output
required: true
default: None
requirements:
- "python >= 2.6"
'''
EXAMPLES = '''
# Get server console output
- k5_server_console_output:
server_name: test01
length: 50
k5_auth: "{{ k5_auth_facts }}"
'''
RETURN = '''
k5_server_console_output
description: List of the output details.
returned: On success when the server is found
type: list
sample:
"Generation complete.",
"",
"Ubuntu 14.04.3 LTS nx-demo01-1a-jumpserver ttyS0",
"",
"nx-demo01-1a-jumpserver login: Cloud-init v. 0.7.5 running 'modules:final' at Fri, 06 Jan 2017 23:08:22 +0000. Up 31.10 seconds.",
"ci-info: ++++++++++Authorized keys from /home/ubuntu/.ssh/authorized_keys for user ubuntu+++++++++++",
"ci-info: +---------+-------------------------------------------------+---------+-------------------+",
"ci-info: | Keytype | Fingerprint (md5) | Options | Comment |",
"ci-info: +---------+-------------------------------------------------+---------+-------------------+",
"ci-info: | ssh-rsa | ce:b7:7c:b9:48:98:d5:9a:1c:5e:8e:4e:56:81:ee:02 | - | Generated by Nova |",
"ci-info: +---------+-------------------------------------------------+---------+-------------------+",
"ec2: ",
"ec2: #############################################################",
"ec2: -----BEGIN SSH HOST KEY FINGERPRINTS-----",
"ec2: 1024 39:46:9c:ef:af:91:bf:be:a4:a4:3e:a2:0c:16:34:ed root@nx-demo01-1a-jumpserver (DSA)",
"ec2: 256 43:b4:59:1b:e8:ff:94:46:64:f8:76:15:37:ed:45:2c root@nx-demo01-1a-jumpserver (ECDSA)",
"ec2: 2048 6f:2a:0e:bb:ab:fe:78:a7:01:bc:b6:4c:5c:ca:90:1a root@nx-demo01-1a-jumpserver (RSA)",
"ec2: -----END SSH HOST KEY FINGERPRINTS-----",
"ec2: #############################################################",
"-----BEGIN SSH HOST KEY KEYS-----",
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBPshjqQvI/QzWzuMBvg5H6lRQljJaBiOnsdrISbz8W/poNWKjloRbp6MT9XF7xU1GCJoJsp3KM/NjWI85tUa4Yc= root@nx-demo01-1a-jumpserver",
"ssh-rsa AAAAB3NzaC1yc2EAAAA5AQABAAABAQDHA7Th3EZSOr6Kji2gaFDcgsO+jBETHGbJiPKPanvlYOrmsyKney0ugGcpt1cOC+OsthS968eLJQWjIKjyQHSW8/5NjissrNX6fNyE8UAKyfgcvR9jYa/nrNld7Y5cucZI6tkBRl4Z2wB5hLfEQQdCCt7uGv9s6gAMGOk5hSiXtcbLmGs/jH9KCYnNsVc6IehQ/Svf+7wJj7o721KAvlWLrP8DDJyfa6Oic481z2nMsCRxJf2MupAHzee1v9MrHdJPh191eV6d9Bsruit+64YK6KslsNSVlBb7zadDIYMme8L2YWKf0Y1VX5wRNbPyoVQzaMQCoIwxI9bsbJ7sn9h/ root@nx-demo01-1a-jumpserver",
"-----END SSH HOST KEY KEYS-----",
"Cloud-init v. 0.7.5 finished at Fri, 06 Jan 2017 23:08:22 +0000. Datasource DataSourceOpenStack [net,ver=2]. Up 31.28 seconds",
""
],
"msg": "Get Output Successful"
'''
import requests
import os
import json
from ansible.module_utils.basic import *
############## Common debug ###############
k5_debug = False
k5_debug_out = []
def k5_debug_get():
"""Return our debug list"""
return k5_debug_out
def k5_debug_clear():
"""Clear our debug list"""
k5_debug_out = []
def k5_debug_add(s):
"""Add string to debug list if env K5_DEBUG is defined"""
if k5_debug:
k5_debug_out.append(s)
############## router functions #############
def k5_get_endpoint(e,name):
"""Pull particular endpoint name from dict"""
return e['endpoints'][name]
def k5_get_server_facts(module, k5_facts):
"""Get server facts"""
endpoint = k5_facts['endpoints']['compute']
auth_token = k5_facts['auth_token']
session = requests.Session()
headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': auth_token }
url = endpoint + '/servers/detail'
k5_debug_add('endpoint: {0}'.format(endpoint))
k5_debug_add('REQ: {0}'.format(url))
k5_debug_add('headers: {0}'.format(headers))
try:
response = session.request('GET', url, headers=headers)
except requests.exceptions.RequestException as e:
module.fail_json(msg=e)
# we failed to get data
if response.status_code not in (200,):
module.fail_json(msg="RESP: HTTP Code:" + str(response.status_code) + " " + str(response.content), debug=k5_debug_out)
if 'servers' in response.json():
return response.json()
else:
module.fail_json(msg="Missing servers in response to server details request")
def k5_get_server_console_output(module):
"""Get console output"""
global k5_debug
k5_debug_clear()
if 'K5_DEBUG' in os.environ:
k5_debug = True
if 'auth_spec' in module.params['k5_auth']:
k5_facts = module.params['k5_auth']
else:
module.fail_json(msg="k5_auth_facts not found, have you run k5_auth?")
endpoint = k5_facts['endpoints']['compute']
auth_token = k5_facts['auth_token']
tenant_id = k5_facts['auth_spec']['os_project_id']
server_name = module.params['server_name']
console_length = module.params['console_length']
# we need the server_id not server_name, so grab it
server_facts = k5_get_server_facts(module, k5_facts)
server_id = ''
for s in server_facts['servers']:
if s['name'] == server_name:
server_id = s['id']
break
if server_id == '':
if k5_debug:
module.exit_json(changed=False, msg="Server " + server_name + " not found", debug=k5_debug_out)
else:
module.exit_json(changed=False, msg="Server " + server_name + " not found")
k5_debug_add('auth_token: {0}'.format(auth_token))
k5_debug_add('server_name: {0}'.format(server_name))
k5_debug_add('server_id: {0}'.format(server_id))
session = requests.Session()
headers = {'Content-Type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': auth_token }
url = endpoint + '/servers/' + server_id + '/action'
query_json = {
"os-getConsoleOutput": {
"length": console_length
}
}
k5_debug_add('endpoint: {0}'.format(endpoint))
k5_debug_add('REQ: {0}'.format(url))
k5_debug_add('headers: {0}'.format(headers))
k5_debug_add('json: {0}'.format(query_json))
try:
response = session.request('POST', url, headers=headers, json=query_json)
except requests.exceptions.RequestException as e:
module.fail_json(msg=e)
# we failed to make a change
if response.status_code not in (200,):
module.fail_json(msg="RESP: HTTP Code:" + str(response.status_code) + " " + str(response.content), debug=k5_debug_out)
output = response.json()['output'].split('\n') # because ansible cannot diplay multiline strings
if k5_debug:
module.exit_json(changed=True, msg="Get Output Successful", k5_server_console_output=output, debug=k5_debug_out )
module.exit_json(changed=True, msg="Get Output Successful", k5_server_console_output=output )
######################################################################################
def main():
module = AnsibleModule( argument_spec=dict(
server_name = dict(required=True, default=None, type='str'),
console_length = dict(required=True, default=None, type='int'),
k5_auth = dict(required=True, default=None, type='dict')
) )
k5_get_server_console_output(module)
######################################################################################
if __name__ == '__main__':
main()