Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/tower.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import string
7 import textwrap
8
9 from ansible.module_utils.common.text.converters import to_native
10 from ansible.module_utils.six.moves.urllib import parse as urlparse
11
12
13 def _windows_callback_script(passwd=None):
14 script_url = (
15 "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
16 )
17 if passwd is not None:
18 passwd = passwd.replace("'", "''")
19 script_tpl = """\
20 <powershell>
21 $admin = [adsi]('WinNT://./administrator, user')
22 $admin.PSBase.Invoke('SetPassword', '${PASS}')
23 Invoke-Expression ((New-Object System.Net.Webclient).DownloadString('${SCRIPT}'))
24 </powershell>
25 """
26 else:
27 script_tpl = """\
28 <powershell>
29 $admin = [adsi]('WinNT://./administrator, user')
30 Invoke-Expression ((New-Object System.Net.Webclient).DownloadString('${SCRIPT}'))
31 </powershell>
32 """
33
34 tpl = string.Template(textwrap.dedent(script_tpl))
35 return tpl.safe_substitute(PASS=passwd, SCRIPT=script_url)
36
37
38 def _linux_callback_script(tower_address, template_id, host_config_key):
39 template_id = urlparse.quote(template_id)
40 tower_address = urlparse.quote(tower_address)
41 host_config_key = host_config_key.replace("'", "'\"'\"'")
42
43 script_tpl = """\
44 #!/bin/bash
45 set -x
46
47 retry_attempts=10
48 attempt=0
49 while [[ $attempt -lt $retry_attempts ]]
50 do
51 status_code=$(curl --max-time 10 -v -k -s -i \
52 --data 'host_config_key=${host_config_key}' \
53 'https://${tower_address}/api/v2/job_templates/${template_id}/callback/' \
54 | head -n 1 \
55 | awk '{print $2}')
56 if [[ $status_code == 404 ]]
57 then
58 status_code=$(curl --max-time 10 -v -k -s -i \
59 --data 'host_config_key=${host_config_key}' \
60 'https://${tower_address}/api/v1/job_templates/${template_id}/callback/' \
61 | head -n 1 \
62 | awk '{print $2}')
63 # fall back to using V1 API for Tower 3.1 and below, since v2 API will always 404
64 fi
65 if [[ $status_code == 201 ]]
66 then
67 exit 0
68 fi
69 attempt=$(( attempt + 1 ))
70 echo "$${status_code} received... retrying in 1 minute. (Attempt $${attempt})"
71 sleep 60
72 done
73 exit 1
74 """
75 tpl = string.Template(textwrap.dedent(script_tpl))
76 return tpl.safe_substitute(tower_address=tower_address, template_id=template_id, host_config_key=host_config_key)
77
78
79 def tower_callback_script(tower_address, job_template_id, host_config_key, windows, passwd):
80 if windows:
81 return to_native(_windows_callback_script(passwd=passwd))
82 return _linux_callback_script(tower_address, job_template_id, host_config_key)