Update app.py
Browse files
app.py
CHANGED
|
@@ -3,13 +3,13 @@ import google.generativeai as genai
|
|
| 3 |
import re
|
| 4 |
import datetime
|
| 5 |
import os
|
| 6 |
-
import
|
| 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="
|
| 13 |
|
| 14 |
# --- Helper Functions ---
|
| 15 |
def send_message_to_model(message, model_name, temperature, top_p, top_k, max_tokens):
|
|
@@ -34,214 +34,120 @@ 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
|
| 38 |
-
"""Generates
|
| 39 |
prompt = f"""
|
| 40 |
-
You are an expert
|
| 41 |
|
| 42 |
-
**Goal:** Create the most complete, detailed, efficient, and secure
|
| 43 |
|
| 44 |
-
**
|
| 45 |
|
| 46 |
**Detail Level:** {detail_level}
|
| 47 |
**Security Level:** {security_level}
|
| 48 |
**Prompt Detail Level**:{prompt_detail}
|
| 49 |
-
**
|
| 50 |
-
**
|
|
|
|
|
|
|
|
|
|
| 51 |
**Custom Requirements:** {custom_requirements if custom_requirements else "None"}
|
| 52 |
**Specific Details:** {specific_details if specific_details else "None"}
|
| 53 |
|
| 54 |
**Response Format:**
|
| 55 |
-
- Respond in Markdown format, including a
|
| 56 |
-
- The
|
| 57 |
-
- Do not include comments, explanations, or any other text outside the code block.
|
| 58 |
- The code must maintain its full vertical formatting, respecting indentation and line breaks.
|
| 59 |
- The code must be realistic, using real-world examples, data, and situations.
|
| 60 |
- Explore different approaches, techniques, and advanced practices, always prioritizing security and efficiency.
|
| 61 |
-
- Use advanced
|
| 62 |
-
- Unless the user specifies otherwise, use the most current and secure versions of the
|
| 63 |
-
- If the description asks to create a file, the
|
| 64 |
-
- If the description asks to read a file, the
|
|
|
|
| 65 |
- Use incremental reasoning to add improvements, expansions, and considerations to your code.
|
| 66 |
- Use the history of the conversations so that the response is incremental.
|
| 67 |
|
| 68 |
**Log Level**:{log_level}
|
| 69 |
|
| 70 |
**Important:**
|
| 71 |
-
- Generate only one
|
| 72 |
- Create the longest, most complete, and detailed code possible to cover a wide range of possibilities and scenarios.
|
| 73 |
- Consider all the details of the request, expanding the response and improving the configuration.
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
- If the description includes networking, create a secure and complete network infrastructure with all the necessary parameters, avoiding defaults.
|
| 79 |
-
- If the description includes storage, create secure and complete storage configurations, using all the available options from the provider.
|
| 80 |
-
- If the description includes compute resources, create the most secure and complete setup using the provider options.
|
| 81 |
-
|
| 82 |
-
Always create cloud infrastructure with the following considerations:
|
| 83 |
-
|
| 84 |
-
Security:
|
| 85 |
-
|
| 86 |
-
Implement strict security groups/firewalls allowing only necessary ports.
|
| 87 |
-
Configure IAM roles and policies with the principle of least privilege.
|
| 88 |
-
Enable logging and monitoring for all resources.
|
| 89 |
-
Networking:
|
| 90 |
-
|
| 91 |
-
Set up a Virtual Private Cloud (VPC) or equivalent, with public and private subnets.
|
| 92 |
-
Use NAT gateways for internet access in private subnets.
|
| 93 |
-
Configure proper routing tables and internet gateways.
|
| 94 |
-
Automation:
|
| 95 |
-
|
| 96 |
-
Use Infrastructure as Code (IaC) tools like Terraform, CloudFormation, or ARM templates.
|
| 97 |
-
Include automation for updates, scaling, and backups.
|
| 98 |
-
Resilience:
|
| 99 |
-
|
| 100 |
-
Ensure resources are highly available, using multiple availability zones where possible.
|
| 101 |
-
Configure automatic backups and disaster recovery plans.
|
| 102 |
-
Resource Optimization:
|
| 103 |
-
|
| 104 |
-
Choose appropriate instance types and sizes based on the workload.
|
| 105 |
-
Enable resource tagging for cost management and organization.
|
| 106 |
-
Specific Instructions for Cloud Providers:
|
| 107 |
-
|
| 108 |
-
For AWS:
|
| 109 |
-
|
| 110 |
-
Use AWS services like EC2, S3, RDS, and CloudWatch.
|
| 111 |
-
Always select the latest AMI for operating systems.
|
| 112 |
-
Configure CloudTrail for auditing.
|
| 113 |
-
Use Auto Scaling Groups for EC2 instances to ensure high availability.
|
| 114 |
-
For Google Cloud:
|
| 115 |
-
|
| 116 |
-
Use Google Compute Engine for VMs, Cloud Storage, and Cloud Monitoring.
|
| 117 |
-
Set up VPC networks with subnets in multiple regions for high availability.
|
| 118 |
-
Use Google Cloud IAM for access management.
|
| 119 |
-
For Azure:
|
| 120 |
-
|
| 121 |
-
Utilize Azure Virtual Machines, Azure Storage, and Azure Monitor.
|
| 122 |
-
Set up Azure Virtual Networks with subnets and NSGs.
|
| 123 |
-
Use Azure Role-Based Access Control (RBAC) for permissions.
|
| 124 |
-
Never forget to:
|
| 125 |
-
|
| 126 |
-
Configure proper logging and monitoring for observability.
|
| 127 |
-
Include alerts and notifications for critical resource changes.
|
| 128 |
-
Use version control for all IaC files.
|
| 129 |
-
Ensure compliance with the cloud providerβs best practices and guidelines.
|
| 130 |
-
|
| 131 |
-
When creating cloud infrastructure, always adhere to state-of-the-art practices across different cloud providers (AWS, Google Cloud, Azure). Your goal is to ensure the architecture is secure, scalable, resilient, and cost-optimized while maintaining high automation and compliance standards. Follow these detailed instructions:
|
| 132 |
-
|
| 133 |
-
General Best Practices (Applicable to All Providers):
|
| 134 |
-
Security:
|
| 135 |
-
|
| 136 |
-
Implement multi-layered security:
|
| 137 |
-
Use security groups/firewalls to restrict inbound and outbound traffic to the minimum necessary.
|
| 138 |
-
Enforce encryption for data at rest (e.g., EBS volumes, databases) and in transit (e.g., HTTPS, TLS).
|
| 139 |
-
Use secrets management services for sensitive data (e.g., AWS Secrets Manager, Google Secret Manager, Azure Key Vault).
|
| 140 |
-
IAM Policies:
|
| 141 |
-
Define and apply the principle of least privilege (PoLP) to all roles and users.
|
| 142 |
-
Use separate accounts/projects/subscriptions for different environments (e.g., development, testing, production).
|
| 143 |
-
Monitoring and Logging:
|
| 144 |
-
Enable centralized logging (e.g., CloudWatch Logs, Stackdriver Logging, Azure Monitor).
|
| 145 |
-
Set up alerts for unusual activities (e.g., unauthorized access attempts).
|
| 146 |
-
Networking:
|
| 147 |
-
|
| 148 |
-
Create VPCs or equivalent for isolated networking environments.
|
| 149 |
-
Design subnets (public/private) based on the applicationβs accessibility needs.
|
| 150 |
-
Use NAT Gateways for private subnet instances to access the internet securely.
|
| 151 |
-
Apply Network Access Control Lists (ACLs) to provide an additional layer of security.
|
| 152 |
-
Implement VPC Peering, VPN, or Direct Connect for secure on-premises connectivity.
|
| 153 |
-
Automation and IaC:
|
| 154 |
-
|
| 155 |
-
Use Terraform for declaring all cloud resources, ensuring infrastructure is version-controlled and repeatable.
|
| 156 |
-
Apply modular design in Terraform for reusability and maintainability.
|
| 157 |
-
Use remote state storage (e.g., S3 with state locking via DynamoDB, Google Cloud Storage with versioning) for state management.
|
| 158 |
-
Integrate CI/CD pipelines for automatic deployment and validation of infrastructure code.
|
| 159 |
-
Resilience and High Availability:
|
| 160 |
-
|
| 161 |
-
Design for multi-region and multi-availability zone deployments for critical applications.
|
| 162 |
-
Implement load balancers (e.g., ALB, Cloud Load Balancer, Azure Load Balancer) to distribute traffic across multiple instances.
|
| 163 |
-
Use Auto Scaling Groups or equivalent to handle variable traffic loads automatically.
|
| 164 |
-
Set up disaster recovery strategies, including backups and failover mechanisms.
|
| 165 |
-
Cost Optimization:
|
| 166 |
-
|
| 167 |
-
Tag all resources for cost tracking and management.
|
| 168 |
-
Use Reserved Instances or Savings Plans for predictable workloads.
|
| 169 |
-
Enable idle resource management (e.g., stopping unused instances, rightsizing underutilized resources).
|
| 170 |
-
Compliance and Governance:
|
| 171 |
-
|
| 172 |
-
Implement policies and guardrails using services like AWS Config, Google Organization Policies, and Azure Policy.
|
| 173 |
-
Use audit logs to ensure traceability of actions.
|
| 174 |
-
Regularly conduct compliance checks and audits.
|
| 175 |
-
AWS-Specific Best Practices:
|
| 176 |
-
Compute:
|
| 177 |
-
Use EC2 Auto Scaling Groups for dynamic scaling.
|
| 178 |
-
Leverage Lambda for serverless applications to reduce costs and increase scalability.
|
| 179 |
-
Storage:
|
| 180 |
-
Use S3 with lifecycle policies for automatic transition of data between storage classes.
|
| 181 |
-
Enable S3 Bucket Versioning and MFA Delete for data protection.
|
| 182 |
-
Database:
|
| 183 |
-
Use RDS Multi-AZ for high availability.
|
| 184 |
-
Leverage Aurora for managed relational databases with built-in replication.
|
| 185 |
-
Networking:
|
| 186 |
-
Configure VPC Flow Logs for network traffic analysis.
|
| 187 |
-
Use CloudFront for CDN and enhanced security with AWS Shield.
|
| 188 |
-
Google Cloud-Specific Best Practices:
|
| 189 |
-
Compute:
|
| 190 |
-
Use Managed Instance Groups for high availability and scaling.
|
| 191 |
-
Leverage Cloud Functions or Cloud Run for serverless deployments.
|
| 192 |
-
Storage:
|
| 193 |
-
Enable Bucket Versioning and use Nearline/Coldline storage classes for cost efficiency.
|
| 194 |
-
Set up Data Loss Prevention (DLP) to safeguard sensitive data.
|
| 195 |
-
Networking:
|
| 196 |
-
Use Cloud NAT for private instance internet access.
|
| 197 |
-
Implement VPC Service Controls for enhanced data security.
|
| 198 |
-
Monitoring:
|
| 199 |
-
Set up Stackdriver Monitoring with custom metrics and dashboards.
|
| 200 |
-
Azure-Specific Best Practices:
|
| 201 |
-
Compute:
|
| 202 |
-
Use Virtual Machine Scale Sets for scalable VMs.
|
| 203 |
-
Leverage Azure Functions for event-driven, serverless applications.
|
| 204 |
-
Storage:
|
| 205 |
-
Use Azure Blob Storage with Soft Delete enabled for accidental recovery.
|
| 206 |
-
Implement Storage Account Firewalls and VNET Service Endpoints.
|
| 207 |
-
Networking:
|
| 208 |
-
Configure NSGs (Network Security Groups) with detailed inbound/outbound rules.
|
| 209 |
-
Use Azure Bastion for secure RDP/SSH connectivity.
|
| 210 |
-
Monitoring:
|
| 211 |
-
Enable Azure Monitor with Log Analytics for resource insights.
|
| 212 |
-
Set up Application Insights for performance monitoring.
|
| 213 |
|
| 214 |
"""
|
| 215 |
response = send_message_to_model(prompt, model_name, temperature, top_p, top_k, max_tokens)
|
| 216 |
return response
|
| 217 |
|
| 218 |
-
def
|
| 219 |
-
"""Parses the markdown and saves the
|
| 220 |
-
match = re.search(r'```
|
| 221 |
if match:
|
| 222 |
-
|
| 223 |
else:
|
| 224 |
-
|
| 225 |
|
| 226 |
-
file_name = f"
|
| 227 |
|
| 228 |
if add_header:
|
| 229 |
current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 230 |
header = f"""#===============================================================================
|
| 231 |
-
#
|
| 232 |
# Date: {current_date}
|
| 233 |
# Author: Elias Andrade AKA Chaos4455
|
| 234 |
#===============================================================================\n"""
|
| 235 |
-
|
| 236 |
|
| 237 |
with open(file_name, "w", encoding=encoding) as f:
|
| 238 |
-
f.write(
|
| 239 |
|
| 240 |
-
return file_name,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
def main():
|
| 243 |
-
st.title("
|
| 244 |
-
st.markdown("Generate advanced
|
| 245 |
st.markdown("---")
|
| 246 |
|
| 247 |
# Layout in columns (sidebar and main area)
|
|
@@ -258,53 +164,57 @@ def main():
|
|
| 258 |
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.")
|
| 259 |
|
| 260 |
with st.expander("π Prompt Settings"):
|
| 261 |
-
prompt_presets = st.selectbox("π― Predefined Prompts", ["None", "
|
| 262 |
prompt_detail = st.selectbox("π§ Prompt Detail", ["More descriptive", "Default", "Concise"], index=1, help="Defines the level of detail of the prompt")
|
| 263 |
|
| 264 |
-
with st.expander("
|
| 265 |
-
|
| 266 |
-
"
|
| 267 |
-
[
|
| 268 |
-
"aws", "azurerm", "google", "kubernetes", "docker", "vmware"
|
| 269 |
-
],
|
| 270 |
-
index=0, help="Choose the target provider."
|
| 271 |
-
)
|
| 272 |
-
infrastructure_type = st.selectbox(
|
| 273 |
-
"ποΈ Infrastructure Type",
|
| 274 |
[
|
| 275 |
-
"
|
| 276 |
],
|
| 277 |
-
index=0, help="Choose the
|
| 278 |
)
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
log_level = st.selectbox("ποΈ Logging Level", ["Detailed", "Default", "Minimum"], index=1, help="Defines the detail level of logs.")
|
| 282 |
security_level = st.radio("Security Level", ["High", "Medium", "Low"], index=1)
|
| 283 |
-
custom_requirements = st.text_input("Custom Requirements", placeholder="Ex: Use specific modules, parameters", help="Add specific requirements for the generated
|
| 284 |
-
specific_details = st.text_input("Specific Details", placeholder="Ex: Specific configurations, edge cases", help="Add specific details for
|
| 285 |
|
| 286 |
detail_level = st.selectbox("Detail Level", ["More detailed", "Default", "More concise"], index=1)
|
| 287 |
|
| 288 |
|
| 289 |
with col2:
|
| 290 |
# User's base prompt
|
| 291 |
-
prompt_base = st.text_input("Describe the
|
|
|
|
| 292 |
|
| 293 |
if prompt_presets != "None":
|
| 294 |
if prompt_base:
|
| 295 |
prompt_base = f"{prompt_presets} , {prompt_base}"
|
| 296 |
else:
|
| 297 |
prompt_base = prompt_presets;
|
| 298 |
-
if st.button("β¨ Generate
|
| 299 |
if not prompt_base:
|
| 300 |
-
st.error("β οΈ Please enter a
|
| 301 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
-
with st.spinner("β³ Generating
|
| 304 |
-
ai_code =
|
| 305 |
prompt_base,
|
| 306 |
detail_level,
|
| 307 |
-
|
| 308 |
security_level,
|
| 309 |
model_name,
|
| 310 |
temperature,
|
|
@@ -315,26 +225,29 @@ def main():
|
|
| 315 |
encoding,
|
| 316 |
add_header,
|
| 317 |
log_level,
|
| 318 |
-
|
|
|
|
|
|
|
| 319 |
custom_requirements,
|
| 320 |
-
specific_details
|
|
|
|
| 321 |
)
|
| 322 |
|
| 323 |
if ai_code:
|
| 324 |
-
st.markdown("### β
Generated
|
| 325 |
-
st.code(ai_code, language="
|
| 326 |
|
| 327 |
short_title = prompt_base[:30].strip().replace(" ", "_").lower()
|
| 328 |
-
|
| 329 |
|
| 330 |
st.download_button(
|
| 331 |
-
label="β¬οΈ Download
|
| 332 |
-
data=
|
| 333 |
-
file_name=
|
| 334 |
-
mime="application/x-
|
| 335 |
)
|
| 336 |
else:
|
| 337 |
-
st.error("β Error generating the
|
| 338 |
|
| 339 |
if __name__ == "__main__":
|
| 340 |
main()
|
|
|
|
| 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 |
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):
|
| 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 if target_hosts 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.
|
| 59 |
+
- The YAML code block must be delimited by ```yaml and ```.
|
| 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 |
- Explore different approaches, techniques, and advanced practices, always prioritizing security and efficiency.
|
| 64 |
+
- Use advanced Ansible resources such as modules, roles, variables, functions, conditionals, loops, and handlers, when necessary.
|
| 65 |
+
- Unless the user specifies otherwise, use the most current and secure versions of the modules, using ansible and following best practices.
|
| 66 |
+
- 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.
|
| 67 |
+
- 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.
|
| 68 |
+
- If possible, use Jinja2 templates when required and do not create hard code in your code
|
| 69 |
- Use incremental reasoning to add improvements, expansions, and considerations to your code.
|
| 70 |
- Use the history of the conversations so that the response is incremental.
|
| 71 |
|
| 72 |
**Log Level**:{log_level}
|
| 73 |
|
| 74 |
**Important:**
|
| 75 |
+
- Generate only one playbook at a time.
|
| 76 |
- Create the longest, most complete, and detailed code possible to cover a wide range of possibilities and scenarios.
|
| 77 |
- Consider all the details of the request, expanding the response and improving the configuration.
|
| 78 |
+
- Use the `delegate_to`, `local_action` and `register` options when necessary.
|
| 79 |
+
- Use the `with_items` and `with_dict` options when necessary.
|
| 80 |
+
- Do not use `sudo` unless absolutely required, prefer `become`
|
| 81 |
+
- If possible, use `ansible.builtin` modules instead of other modules.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
"""
|
| 84 |
response = send_message_to_model(prompt, model_name, temperature, top_p, top_k, max_tokens)
|
| 85 |
return response
|
| 86 |
|
| 87 |
+
def parse_and_save_yml(ai_code, short_title, encoding, add_header):
|
| 88 |
+
"""Parses the markdown and saves the ansible playbook as .yml."""
|
| 89 |
+
match = re.search(r'```yaml\s*(.*?)\s*```', ai_code, re.DOTALL | re.IGNORECASE)
|
| 90 |
if match:
|
| 91 |
+
yml_code = match.group(1).strip()
|
| 92 |
else:
|
| 93 |
+
yml_code = ai_code.strip()
|
| 94 |
|
| 95 |
+
file_name = f"ansible_{short_title}.yml"
|
| 96 |
|
| 97 |
if add_header:
|
| 98 |
current_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 99 |
header = f"""#===============================================================================
|
| 100 |
+
# Ansible Playbook Generated by Google Gemini 2 Ansible Gen Pro
|
| 101 |
# Date: {current_date}
|
| 102 |
# Author: Elias Andrade AKA Chaos4455
|
| 103 |
#===============================================================================\n"""
|
| 104 |
+
yml_code = header + yml_code
|
| 105 |
|
| 106 |
with open(file_name, "w", encoding=encoding) as f:
|
| 107 |
+
f.write(yml_code)
|
| 108 |
|
| 109 |
+
return file_name, yml_code
|
| 110 |
+
|
| 111 |
+
def validate_ip_input(ip_input):
|
| 112 |
+
"""Validates and parses IP address input."""
|
| 113 |
+
try:
|
| 114 |
+
if "," in ip_input:
|
| 115 |
+
ips = [ip.strip() for ip in ip_input.split(",")]
|
| 116 |
+
for ip in ips:
|
| 117 |
+
if "/" in ip:
|
| 118 |
+
ipaddress.ip_network(ip, strict=False) #verify if is a network
|
| 119 |
+
elif "-" in ip:
|
| 120 |
+
parts = ip.split("-")
|
| 121 |
+
if len(parts) != 2:
|
| 122 |
+
return False, "Invalid Range Format"
|
| 123 |
+
|
| 124 |
+
ipaddress.ip_address(parts[0])
|
| 125 |
+
ipaddress.ip_address(parts[1])
|
| 126 |
+
else:
|
| 127 |
+
ipaddress.ip_address(ip) #verify if is a valid address
|
| 128 |
+
return True, ips
|
| 129 |
+
elif "/" in ip_input:
|
| 130 |
+
ipaddress.ip_network(ip_input, strict=False) #verify if is a network
|
| 131 |
+
return True, [ip_input]
|
| 132 |
+
elif "-" in ip_input:
|
| 133 |
+
parts = ip_input.split("-")
|
| 134 |
+
if len(parts) != 2:
|
| 135 |
+
return False, "Invalid Range Format"
|
| 136 |
+
|
| 137 |
+
ipaddress.ip_address(parts[0])
|
| 138 |
+
ipaddress.ip_address(parts[1])
|
| 139 |
+
return True,[ip_input]
|
| 140 |
+
else:
|
| 141 |
+
ipaddress.ip_address(ip_input)
|
| 142 |
+
return True, [ip_input]
|
| 143 |
+
except ValueError as e:
|
| 144 |
+
return False, str(e)
|
| 145 |
+
except Exception as e:
|
| 146 |
+
return False, str(e)
|
| 147 |
|
| 148 |
def main():
|
| 149 |
+
st.title("βοΈ Gemini2 Ansible Gen Pro by [Elias Andrade](https://github.com/chaos4455)")
|
| 150 |
+
st.markdown("Generate advanced Ansible playbooks with ease! π")
|
| 151 |
st.markdown("---")
|
| 152 |
|
| 153 |
# Layout in columns (sidebar and main area)
|
|
|
|
| 164 |
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.")
|
| 165 |
|
| 166 |
with st.expander("π Prompt Settings"):
|
| 167 |
+
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.")
|
| 168 |
prompt_detail = st.selectbox("π§ Prompt Detail", ["More descriptive", "Default", "Concise"], index=1, help="Defines the level of detail of the prompt")
|
| 169 |
|
| 170 |
+
with st.expander("βοΈ Ansible Settings"):
|
| 171 |
+
os_type = st.selectbox(
|
| 172 |
+
"π» Operating System",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
[
|
| 174 |
+
"Ubuntu", "CentOS", "RedHat", "Debian", "Windows", "Other"
|
| 175 |
],
|
| 176 |
+
index=0, help="Choose the target operating system."
|
| 177 |
)
|
| 178 |
+
|
| 179 |
+
ansible_user = st.text_input("π€ Ansible User", value="root", help="User for Ansible SSH connection")
|
| 180 |
+
ansible_ssh_pass = st.text_input("π Ansible SSH Password", type="password", help="Password for Ansible SSH connection (Use with caution)")
|
| 181 |
+
ansible_become = st.checkbox("π₯ Use Become", value=True, help="Enable privilege escalation")
|
| 182 |
+
|
| 183 |
+
encoding = st.selectbox("π€ Encoding", ["utf-8", "ansi"], index=0, help="Choose the encoding of the .yml file.")
|
| 184 |
+
add_header = st.checkbox("π Add Header", value=True, help="Add a header with information in the .yml file.")
|
| 185 |
log_level = st.selectbox("ποΈ Logging Level", ["Detailed", "Default", "Minimum"], index=1, help="Defines the detail level of logs.")
|
| 186 |
security_level = st.radio("Security Level", ["High", "Medium", "Low"], index=1)
|
| 187 |
+
custom_requirements = st.text_input("Custom Requirements", placeholder="Ex: Use specific modules, parameters", help="Add specific requirements for the generated playbook.")
|
| 188 |
+
specific_details = st.text_input("Specific Details", placeholder="Ex: Specific configurations, edge cases", help="Add specific details for playbook generation.")
|
| 189 |
|
| 190 |
detail_level = st.selectbox("Detail Level", ["More detailed", "Default", "More concise"], index=1)
|
| 191 |
|
| 192 |
|
| 193 |
with col2:
|
| 194 |
# User's base prompt
|
| 195 |
+
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")
|
| 196 |
+
target_hosts = st.text_input("Target Hosts (IP(s), Range or CIDR, separated by comma):", placeholder="192.168.0.1,192.168.0.2,192.168.0.1/24 or 192.168.0.1-255",key="target_hosts")
|
| 197 |
|
| 198 |
if prompt_presets != "None":
|
| 199 |
if prompt_base:
|
| 200 |
prompt_base = f"{prompt_presets} , {prompt_base}"
|
| 201 |
else:
|
| 202 |
prompt_base = prompt_presets;
|
| 203 |
+
if st.button("β¨ Generate Ansible Playbook"):
|
| 204 |
if not prompt_base:
|
| 205 |
+
st.error("β οΈ Please enter a playbook description.")
|
| 206 |
return
|
| 207 |
+
|
| 208 |
+
valid_ip, parsed_ips = validate_ip_input(target_hosts)
|
| 209 |
+
if not valid_ip:
|
| 210 |
+
st.error(f"β οΈ Invalid IP Address or Range: {parsed_ips}")
|
| 211 |
+
return
|
| 212 |
|
| 213 |
+
with st.spinner("β³ Generating playbook..."):
|
| 214 |
+
ai_code = generate_ansible_playbook(
|
| 215 |
prompt_base,
|
| 216 |
detail_level,
|
| 217 |
+
os_type,
|
| 218 |
security_level,
|
| 219 |
model_name,
|
| 220 |
temperature,
|
|
|
|
| 225 |
encoding,
|
| 226 |
add_header,
|
| 227 |
log_level,
|
| 228 |
+
ansible_user,
|
| 229 |
+
ansible_ssh_pass,
|
| 230 |
+
ansible_become,
|
| 231 |
custom_requirements,
|
| 232 |
+
specific_details,
|
| 233 |
+
parsed_ips if parsed_ips else None
|
| 234 |
)
|
| 235 |
|
| 236 |
if ai_code:
|
| 237 |
+
st.markdown("### β
Generated Playbook:")
|
| 238 |
+
st.code(ai_code, language="yaml")
|
| 239 |
|
| 240 |
short_title = prompt_base[:30].strip().replace(" ", "_").lower()
|
| 241 |
+
file_name_yml, yml_code = parse_and_save_yml(ai_code, short_title, encoding, add_header)
|
| 242 |
|
| 243 |
st.download_button(
|
| 244 |
+
label="β¬οΈ Download Playbook (.yml)",
|
| 245 |
+
data=yml_code,
|
| 246 |
+
file_name=file_name_yml,
|
| 247 |
+
mime="application/x-yaml",
|
| 248 |
)
|
| 249 |
else:
|
| 250 |
+
st.error("β Error generating the playbook. Check the connection with the AI and try again.")
|
| 251 |
|
| 252 |
if __name__ == "__main__":
|
| 253 |
main()
|