chaos4455 commited on
Commit
a84ea15
Β·
verified Β·
1 Parent(s): af518dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -60
app.py CHANGED
@@ -3,13 +3,13 @@ import google.generativeai as genai
3
  import re
4
  import datetime
5
  import os
6
- import ipaddress
7
 
8
  # Secret key and Google Gemini API configuration
9
  API_KEY = st.secrets["GOOGLE_API_KEY"]
10
 
11
  # Page configuration
12
- st.set_page_config(page_title="βš™οΈ Gemini2 Ansible Gen Pro", page_icon="βš™οΈ", layout="wide")
13
 
14
  # --- Helper Functions ---
15
  def send_message_to_model(message, model_name, temperature, top_p, top_k, max_tokens):
@@ -34,25 +34,27 @@ def send_message_to_model(message, model_name, temperature, top_p, top_k, max_to
34
  st.error(f"❌ Error communicating with the AI: {e}")
35
  return None
36
 
37
- def generate_ansible_playbook(prompt_base, detail_level, os_type, security_level, model_name, temperature, top_p, top_k, max_tokens, prompt_detail, encoding, add_header, log_level, ansible_user, ansible_ssh_pass, ansible_become, custom_requirements, specific_details, target_hosts_description):
38
- """Generates an Ansible playbook based on user settings."""
39
  prompt = f"""
40
- You are an expert Ansible automation engineer. Your task is to generate a complete, secure, and efficient Ansible playbook based on the following description:
41
 
42
- **Goal:** Create the most complete, detailed, efficient, and secure Ansible playbook possible, considering all variables, edge cases, and potential scenarios.
43
 
44
- **Playbook Description:** {prompt_base}
45
 
46
  **Detail Level:** {detail_level}
47
  **Security Level:** {security_level}
48
  **Prompt Detail Level**:{prompt_detail}
49
  **Operating System:** {os_type}
50
- **Target Hosts:** {target_hosts_description if target_hosts_description else "None"}
51
- **Ansible User:** {ansible_user if ansible_user else "root"}
52
- **Ansible SSH Password:** {ansible_ssh_pass if ansible_ssh_pass else "None"}
53
- **Ansible Become:** {ansible_become}
54
  **Custom Requirements:** {custom_requirements if custom_requirements else "None"}
55
  **Specific Details:** {specific_details if specific_details else "None"}
 
 
56
 
57
  **Response Format:**
58
  - Respond in Markdown format, including a YAML code block with its original formatting, without line breaks.
@@ -60,45 +62,50 @@ def generate_ansible_playbook(prompt_base, detail_level, os_type, security_level
60
  - Do not include comments, explanations, or any other text outside the code block, unless the prompt requires.
61
  - The code must maintain its full vertical formatting, respecting indentation and line breaks.
62
  - The code must be realistic, using real-world examples, data, and situations.
63
- - The `hosts` section of the playbook, must include the list of the target hosts in the description, if the target hosts are not specified you must create your own hosts list, please avoid using "all" if the target hosts are specified.
 
 
64
  - Explore different approaches, techniques, and advanced practices, always prioritizing security and efficiency.
65
- - Use advanced Ansible resources such as modules, roles, variables, functions, conditionals, loops, and handlers, when necessary.
66
- - Unless the user specifies otherwise, use the most current and secure versions of the modules, using ansible and following best practices.
67
- - If the description asks to create a file, the ansible playbook should create the file directly in the file system and not use a screen output for this.
68
- - If the description asks to read a file, the ansible playbook should read the file directly from the file system and not use a screen input for this.
69
- - If possible, use Jinja2 templates when required and do not create hard code in your code
70
  - Use incremental reasoning to add improvements, expansions, and considerations to your code.
71
  - Use the history of the conversations so that the response is incremental.
72
 
73
  **Log Level**:{log_level}
74
 
75
  **Important:**
76
- - Generate only one playbook at a time.
77
  - Create the longest, most complete, and detailed code possible to cover a wide range of possibilities and scenarios.
78
  - Consider all the details of the request, expanding the response and improving the configuration.
79
- - Use the `delegate_to`, `local_action` and `register` options when necessary.
80
- - Use the `with_items` and `with_dict` options when necessary.
81
- - Do not use `sudo` unless absolutely required, prefer `become`
82
- - If possible, use `ansible.builtin` modules instead of other modules.
83
-
84
  """
85
- response = send_message_to_model(prompt, model_name, temperature, top_p, top_k, max_tokens)
86
  return response
87
 
88
  def parse_and_save_yml(ai_code, short_title, encoding, add_header):
89
- """Parses the markdown and saves the ansible playbook as .yml."""
90
  match = re.search(r'```yaml\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
91
  if match:
92
  yml_code = match.group(1).strip()
93
  else:
94
  yml_code = ai_code.strip()
95
-
96
- file_name = f"ansible_{short_title}.yml"
 
 
 
 
 
 
 
97
 
98
  if add_header:
99
  current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
100
  header = f"""#===============================================================================
101
- # Ansible Playbook Generated by Google Gemini 2 Ansible Gen Pro
102
  # Date: {current_date}
103
  # Author: Elias Andrade AKA Chaos4455
104
  #===============================================================================\n"""
@@ -111,8 +118,8 @@ def parse_and_save_yml(ai_code, short_title, encoding, add_header):
111
 
112
 
113
  def main():
114
- st.title("βš™οΈ Gemini2 Ansible Gen Pro by [Elias Andrade](https://github.com/chaos4455)")
115
- st.markdown("Generate advanced Ansible playbooks with ease! πŸš€")
116
  st.markdown("---")
117
 
118
  # Layout in columns (sidebar and main area)
@@ -129,49 +136,56 @@ def main():
129
  max_tokens = st.number_input("πŸ“ Max Tokens", min_value=128, max_value=8192, value=8192, step=128, help="Adjust the maximum size of the response.")
130
 
131
  with st.expander("πŸ“ Prompt Settings"):
132
- prompt_presets = st.selectbox("🎯 Predefined Prompts", ["None", "Install packages", "Configure services", "Manage users", "File management", "System updates", "Deploy applications"], index=0, help="Choose a predefined prompt.")
133
- prompt_detail = st.selectbox("🧐 Prompt Detail", ["More descriptive", "Default", "Concise"], index=1, help="Defines the level of detail of the prompt")
134
 
135
- with st.expander("βš™οΈ Ansible Settings"):
136
  os_type = st.selectbox(
137
  "πŸ’» Operating System",
138
  [
139
- "Ubuntu", "CentOS", "RedHat", "Debian", "Windows", "Other"
140
  ],
141
  index=0, help="Choose the target operating system."
142
  )
143
 
144
- ansible_user = st.text_input("πŸ‘€ Ansible User", value="root", help="User for Ansible SSH connection")
145
- ansible_ssh_pass = st.text_input("πŸ”‘ Ansible SSH Password", type="password", help="Password for Ansible SSH connection (Use with caution)")
146
- ansible_become = st.checkbox("πŸ”₯ Use Become", value=True, help="Enable privilege escalation")
147
 
148
  encoding = st.selectbox("πŸ”€ Encoding", ["utf-8", "ansi"], index=0, help="Choose the encoding of the .yml file.")
149
  add_header = st.checkbox("πŸ“œ Add Header", value=True, help="Add a header with information in the .yml file.")
150
  log_level = st.selectbox("πŸ—‚οΈ Logging Level", ["Detailed", "Default", "Minimum"], index=1, help="Defines the detail level of logs.")
151
  security_level = st.radio("Security Level", ["High", "Medium", "Low"], index=1)
152
- custom_requirements = st.text_input("Custom Requirements", placeholder="Ex: Use specific modules, parameters", help="Add specific requirements for the generated playbook.")
153
- specific_details = st.text_input("Specific Details", placeholder="Ex: Specific configurations, edge cases", help="Add specific details for playbook generation.")
154
 
155
  detail_level = st.selectbox("Detail Level", ["More detailed", "Default", "More concise"], index=1)
156
-
 
 
 
 
157
 
158
  with col2:
159
  # User's base prompt
160
- prompt_base = st.text_input("Describe the Ansible Playbook:", placeholder="Ex: Install apache2 and configure a default page for all the servers", key="prompt_base")
161
- target_hosts_description = st.text_input("Target Hosts Description (text format, IP(s), Range or CIDR):", placeholder="Ex: all the servers in 192.168.0.0/24 network",key="target_hosts")
162
 
163
  if prompt_presets != "None":
164
  if prompt_base:
165
  prompt_base = f"{prompt_presets} , {prompt_base}"
166
  else:
167
  prompt_base = prompt_presets;
168
- if st.button("✨ Generate Ansible Playbook"):
169
  if not prompt_base:
170
- st.error("⚠️ Please enter a playbook description.")
171
  return
172
-
173
- with st.spinner("⏳ Generating playbook..."):
174
- ai_code = generate_ansible_playbook(
 
 
 
 
175
  prompt_base,
176
  detail_level,
177
  os_type,
@@ -185,29 +199,32 @@ def main():
185
  encoding,
186
  add_header,
187
  log_level,
188
- ansible_user,
189
- ansible_ssh_pass,
190
- ansible_become,
191
  custom_requirements,
192
  specific_details,
193
- target_hosts_description # Pass only the description
 
 
 
194
  )
195
 
196
  if ai_code:
197
- st.markdown("### βœ… Generated Playbook:")
198
  st.code(ai_code, language="yaml")
199
 
200
  short_title = prompt_base[:30].strip().replace(" ", "_").lower()
201
  file_name_yml, yml_code = parse_and_save_yml(ai_code, short_title, encoding, add_header)
202
-
203
- st.download_button(
204
- label="⬇️ Download Playbook (.yml)",
205
- data=yml_code,
206
- file_name=file_name_yml,
207
- mime="application/x-yaml",
208
- )
 
209
  else:
210
- st.error("❌ Error generating the playbook. Check the connection with the AI and try again.")
211
 
212
  if __name__ == "__main__":
213
  main()
 
3
  import re
4
  import datetime
5
  import os
6
+ import yaml
7
 
8
  # Secret key and Google Gemini API configuration
9
  API_KEY = st.secrets["GOOGLE_API_KEY"]
10
 
11
  # Page configuration
12
+ st.set_page_config(page_title="βš™οΈ Gemini2 Puppet Bolt Gen Pro", page_icon="βš™οΈ", layout="wide")
13
 
14
  # --- Helper Functions ---
15
  def send_message_to_model(message, model_name, temperature, top_p, top_k, max_tokens):
 
34
  st.error(f"❌ Error communicating with the AI: {e}")
35
  return None
36
 
37
+ def generate_puppet_bolt_plan(prompt_base, detail_level, os_type, security_level, model_name, temperature, top_p, top_k, max_tokens, prompt_detail, encoding, add_header, log_level, bolt_user, bolt_ssh_pass, custom_requirements, specific_details, target_nodes_description, task_type, task_code, parameters_description):
38
+ """Generates a Puppet Bolt plan based on user settings."""
39
  prompt = f"""
40
+ You are an expert automation engineer specializing in Puppet Bolt. Your task is to generate a complete, secure, and efficient Puppet Bolt plan based on the following description:
41
 
42
+ **Goal:** Create the most complete, detailed, efficient, and secure Puppet Bolt plan possible, considering all variables, edge cases, and potential scenarios.
43
 
44
+ **Plan Description:** {prompt_base}
45
 
46
  **Detail Level:** {detail_level}
47
  **Security Level:** {security_level}
48
  **Prompt Detail Level**:{prompt_detail}
49
  **Operating System:** {os_type}
50
+ **Target Nodes:** {target_nodes_description if target_nodes_description else "None"}
51
+ **Bolt User:** {bolt_user if bolt_user else "root"}
52
+ **Bolt SSH Password:** {bolt_ssh_pass if bolt_ssh_pass else "None"}
53
+ **Parameters:** {parameters_description if parameters_description else "None"}
54
  **Custom Requirements:** {custom_requirements if custom_requirements else "None"}
55
  **Specific Details:** {specific_details if specific_details else "None"}
56
+ **Task Type:** {task_type}
57
+ **Task Code:** {task_code if task_code else "None"}
58
 
59
  **Response Format:**
60
  - Respond in Markdown format, including a YAML code block with its original formatting, without line breaks.
 
62
  - Do not include comments, explanations, or any other text outside the code block, unless the prompt requires.
63
  - The code must maintain its full vertical formatting, respecting indentation and line breaks.
64
  - The code must be realistic, using real-world examples, data, and situations.
65
+ - The plan must use advanced Bolt resources, such as tasks, parameters, variables, functions, conditionals, loops and targets when necessary.
66
+ -The plan must use the `run_task` function to execute the tasks.
67
+ -The plan must use a valid node target.
68
  - Explore different approaches, techniques, and advanced practices, always prioritizing security and efficiency.
69
+ - The plan must use native Bolt functions and modules instead of others.
70
+ - Unless the user specifies otherwise, use the most current and secure versions of the modules, using bolt and following best practices.
71
+ - If the description asks to create a file, the plan should create the file directly in the file system and not use a screen output for this.
72
+ - If the description asks to read a file, the plan should read the file directly from the file system and not use a screen input for this.
 
73
  - Use incremental reasoning to add improvements, expansions, and considerations to your code.
74
  - Use the history of the conversations so that the response is incremental.
75
 
76
  **Log Level**:{log_level}
77
 
78
  **Important:**
79
+ - Generate only one plan at a time.
80
  - Create the longest, most complete, and detailed code possible to cover a wide range of possibilities and scenarios.
81
  - Consider all the details of the request, expanding the response and improving the configuration.
82
+ - If the prompt does not include parameters, but if the user add a variable in a code block, create a task parameter to use that variable.
83
+ - If the prompt includes parameters, create a task parameter to use that parameters.
 
 
 
84
  """
85
+ response = send_message_to_model(message, model_name, temperature, top_p, top_k, max_tokens)
86
  return response
87
 
88
  def parse_and_save_yml(ai_code, short_title, encoding, add_header):
89
+ """Parses the markdown and saves the Puppet Bolt plan as .yml."""
90
  match = re.search(r'```yaml\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
91
  if match:
92
  yml_code = match.group(1).strip()
93
  else:
94
  yml_code = ai_code.strip()
95
+
96
+ try:
97
+ yaml.safe_load(yml_code)
98
+ except yaml.YAMLError as e:
99
+ st.error(f"❌ Generated YAML is invalid: {e}")
100
+ return None, None
101
+
102
+
103
+ file_name = f"bolt_{short_title}.yml"
104
 
105
  if add_header:
106
  current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
107
  header = f"""#===============================================================================
108
+ # Puppet Bolt Plan Generated by Google Gemini 2 Bolt Gen Pro
109
  # Date: {current_date}
110
  # Author: Elias Andrade AKA Chaos4455
111
  #===============================================================================\n"""
 
118
 
119
 
120
  def main():
121
+ st.title("βš™οΈ Gemini2 Puppet Bolt Gen Pro by [Elias Andrade](https://github.com/chaos4455)")
122
+ st.markdown("Generate advanced Puppet Bolt plans with ease! πŸš€")
123
  st.markdown("---")
124
 
125
  # Layout in columns (sidebar and main area)
 
136
  max_tokens = st.number_input("πŸ“ Max Tokens", min_value=128, max_value=8192, value=8192, step=128, help="Adjust the maximum size of the response.")
137
 
138
  with st.expander("πŸ“ Prompt Settings"):
139
+ prompt_presets = st.selectbox("🎯 Predefined Prompts", ["None", "Install packages", "Run commands", "Manage services", "Manage files", "System Updates", "Copy Files"], index=0, help="Choose a predefined prompt.")
140
+ prompt_detail = st.selectbox("🧐 Prompt Detail", ["More descriptive", "Default", "Concise"], index=1, help="Defines the level of detail of the prompt")
141
 
142
+ with st.expander("βš™οΈ Puppet Bolt Settings"):
143
  os_type = st.selectbox(
144
  "πŸ’» Operating System",
145
  [
146
+ "Linux", "Windows", "Other"
147
  ],
148
  index=0, help="Choose the target operating system."
149
  )
150
 
151
+ bolt_user = st.text_input("πŸ‘€ Bolt User", value="root", help="User for Bolt SSH connection")
152
+ bolt_ssh_pass = st.text_input("πŸ”‘ Bolt SSH Password", type="password", help="Password for Bolt SSH connection (Use with caution)")
 
153
 
154
  encoding = st.selectbox("πŸ”€ Encoding", ["utf-8", "ansi"], index=0, help="Choose the encoding of the .yml file.")
155
  add_header = st.checkbox("πŸ“œ Add Header", value=True, help="Add a header with information in the .yml file.")
156
  log_level = st.selectbox("πŸ—‚οΈ Logging Level", ["Detailed", "Default", "Minimum"], index=1, help="Defines the detail level of logs.")
157
  security_level = st.radio("Security Level", ["High", "Medium", "Low"], index=1)
158
+ custom_requirements = st.text_input("Custom Requirements", placeholder="Ex: Use specific modules, parameters", help="Add specific requirements for the generated plan.")
159
+ specific_details = st.text_input("Specific Details", placeholder="Ex: Specific configurations, edge cases", help="Add specific details for plan generation.")
160
 
161
  detail_level = st.selectbox("Detail Level", ["More detailed", "Default", "More concise"], index=1)
162
+
163
+ with st.expander("πŸ”¨ Task Settings"):
164
+ task_type = st.selectbox("🎯 Task Type", ["command", "script", "puppet"], index = 0, help="Type of task")
165
+ task_code = st.text_area("πŸ“‹ Task Code", placeholder="Command or Code for the task", help="Enter your command, script or Puppet code")
166
+ parameters_description = st.text_input("🧰 Parameters Description", placeholder="List of parameters for the task", help="Enter the parameters needed for this task")
167
 
168
  with col2:
169
  # User's base prompt
170
+ prompt_base = st.text_input("Describe the Puppet Bolt Plan:", placeholder="Ex: Execute a command to check disk space on all Linux servers, and save the output on /tmp/output.txt", key="prompt_base")
171
+ target_nodes_description = st.text_input("Target Nodes Description (text format, IP(s), Range or CIDR):", placeholder="Ex: all servers in the 192.168.0.0/24 network",key="target_nodes")
172
 
173
  if prompt_presets != "None":
174
  if prompt_base:
175
  prompt_base = f"{prompt_presets} , {prompt_base}"
176
  else:
177
  prompt_base = prompt_presets;
178
+ if st.button("✨ Generate Puppet Bolt Plan"):
179
  if not prompt_base:
180
+ st.error("⚠️ Please enter a plan description.")
181
  return
182
+
183
+ if task_type != "command" and not task_code:
184
+ st.error("⚠️ Please enter the code for the task.")
185
+ return
186
+
187
+ with st.spinner("⏳ Generating plan..."):
188
+ ai_code = generate_puppet_bolt_plan(
189
  prompt_base,
190
  detail_level,
191
  os_type,
 
199
  encoding,
200
  add_header,
201
  log_level,
202
+ bolt_user,
203
+ bolt_ssh_pass,
 
204
  custom_requirements,
205
  specific_details,
206
+ target_nodes_description,
207
+ task_type,
208
+ task_code,
209
+ parameters_description
210
  )
211
 
212
  if ai_code:
213
+ st.markdown("### βœ… Generated Plan:")
214
  st.code(ai_code, language="yaml")
215
 
216
  short_title = prompt_base[:30].strip().replace(" ", "_").lower()
217
  file_name_yml, yml_code = parse_and_save_yml(ai_code, short_title, encoding, add_header)
218
+
219
+ if file_name_yml and yml_code: #check if the file was generated
220
+ st.download_button(
221
+ label="⬇️ Download Plan (.yml)",
222
+ data=yml_code,
223
+ file_name=file_name_yml,
224
+ mime="application/x-yaml",
225
+ )
226
  else:
227
+ st.error("❌ Error generating the plan. Check the connection with the AI and try again.")
228
 
229
  if __name__ == "__main__":
230
  main()