-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathansible_docker.py
More file actions
executable file
·194 lines (169 loc) · 6.45 KB
/
ansible_docker.py
File metadata and controls
executable file
·194 lines (169 loc) · 6.45 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Action to upload ansible roles to galaxy.ansible.com (galaxy-ng)
"""
import subprocess
import os
import sys
import requests
from urllib.parse import urlparse
class EnvironmentManager:
"""
Parsing Enviroment Variables
"""
def __init__(self, env_var_name):
self.env_var_name = env_var_name
self.env_var_value = os.getenv(env_var_name)
def check_optional_environment_variable_with_default(self):
"""
Check if optional variable with defaukt value is defined.
"""
if self.env_var_value is not None:
print(f"The value of {self.env_var_name} is: {self.env_var_value}")
return f"{self.env_var_value}"
print(f"The variable {self.env_var_name} is not set.")
print("But a default value should have be defined.\nSomething is wrong. CANCEL")
sys.exit(1)
def check_optional_environment_variable_without_default(self):
"""
Check if optional Variable is defined.
"""
if self.env_var_value is not None:
print(f"The value of {self.env_var_name} is: {self.env_var_value}")
return f"{self.env_var_value}"
print(f"The variable {self.env_var_name} is not set.")
return ""
def check_secret_environment_variable(self):
"""
Check if required Variable is defined.
exit if undefined
"""
if self.env_var_value is not None:
print(f"The value of {self.env_var_name} is defined")
return f"{self.env_var_value}"
print(f"The variable {self.env_var_name} is not set but needs to be defined.\nFAILED")
sys.exit(1)
# pylint: disable=R0903
class AnsibleCommandExecution:
"""
running ansible galaxy command
"""
def run_command(self, command):
"""
Running command as subprocess.
Printing error on fail and exit
"""
try:
result = subprocess.run(command, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, check=True)
return result.stdout
except subprocess.CalledProcessError as error:
print(f"Error running Ansible command: {error}\n\n{error.stdout}\n{error.stderr}")
sys.exit(1)
def is_url(string):
"""
Check if a string is a valid url, using urlparse
"""
try:
result = urlparse(string)
print(result)
return str(string)
except ValueError:
print(f"{string} is not a valid URL.\nCANCEL")
sys.exit(1)
def validate_subscription():
API_URL = f"https://agent.api.stepsecurity.io/v1/github/{os.environ['GITHUB_REPOSITORY']}/actions/subscription"
try:
response = requests.get(API_URL, timeout=3)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 403:
print("Subscription is not valid. Reach out to support@stepsecurity.io")
exit(1)
else:
print("Timeout or API not reachable. Continuing to next step.")
except requests.exceptions.RequestException:
print("Timeout or API not reachable. Continuing to next step.")
def write_ansible_galaxy_config(galaxy_api_key_value, galaxy_api_value):
"""
writing ansible galaxy config to file
"""
content = f"""
[galaxy]
server_list = galaxy
[galaxy_server.galaxy]
url = {galaxy_api_value}
token = {galaxy_api_key_value}
"""
file_path = "/etc/ansible/galaxy.cfg"
directory_path = '/etc/ansible/'
# Check if the directory exists, and if not, create it
if not os.path.exists(directory_path):
os.makedirs(directory_path)
# Inhalt in die Datei schreiben
with open(file_path, "w", encoding="utf-8") as file:
file.write(content)
print(f'Die Config wurde erfolgreich als Datei "{file_path}" geschrieben.')
if __name__ == "__main__":
# Validate subscription at the start
validate_subscription()
# define known enviroment vars
ENV_GALAXY_API_KEY_NAME = "GALAXY_API_KEY"
ENV_GIT_BRANCH_NAME = "GIT_BRANCH"
ENV_PATH_NAME = "PATH"
ENV_GALAXY_API_NAME = "GALAXY_API"
# check for galaxy_api_key variable
env_galaxy_api_key = EnvironmentManager(ENV_GALAXY_API_KEY_NAME)
galaxy_api_key = env_galaxy_api_key.check_secret_environment_variable()
if galaxy_api_key == "":
print("galaxy_api_key needs to be defined")
sys.exit(1)
# check for git_branch variable
env_git_branch = EnvironmentManager(ENV_GIT_BRANCH_NAME)
git_branch_check = env_git_branch.check_optional_environment_variable_without_default()
if git_branch_check == "":
print("Using main as git_branch")
git_branch = 'main'
else:
git_branch = git_branch_check
# check for path variable
env_path = EnvironmentManager(ENV_PATH_NAME)
path = env_path.check_optional_environment_variable_with_default()
if path == "":
print("path needs to be defined")
sys.exit(1)
# check for galaxy_api variable
env_galaxy_api = EnvironmentManager(ENV_GALAXY_API_NAME)
galaxy_api_url = env_galaxy_api.check_optional_environment_variable_with_default()
# pylint: disable=C0103
galaxy_api = str(is_url(galaxy_api_url))
if galaxy_api == "":
print("galaxy_api needs to be defined")
print(f"galaxy api is {galaxy_api}, default is 'https://galaxy.ansible.com/api/'.")
sys.exit(1)
# define git repo ans user/organisation
github_repository_env = EnvironmentManager('GITHUB_REPOSITORY')
github_repository = github_repository_env.check_optional_environment_variable_with_default()
gh_parts = github_repository.split('/')
github_organisation = gh_parts[0]
github_repo = gh_parts[1]
# config for galaxy
write_ansible_galaxy_config(f"{galaxy_api_key}", f"{galaxy_api}")
# execute linting commands
execute = AnsibleCommandExecution()
# run ansible galaxy
import_command = ["/usr/local/bin/ansible-galaxy", "role", "import", "-vvv", "--api-key",
f"{galaxy_api_key}", "--branch", f"{git_branch}", f"{github_organisation}", f"{github_repo}"]
upload_run = execute.run_command(import_command)
upload_result = f"""
---start+galaxy-ng+role+upload---
/usr/local/bin/ansible-galaxyrole import -vvv \\
--api-key *********** \\
--branch {git_branch} \\
{github_organisation} {github_repo}
{upload_run}
Galaxy upload run executed
---end+galaxy-ng+role+upload---
"""
print(upload_result)