-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive_mycli.txt
199 lines (162 loc) · 8.66 KB
/
archive_mycli.txt
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
#!/usr/bin/env python3
import click
import logging
import json
import os
import re
import subprocess
# Setup basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("fast-deploy.log"),
logging.StreamHandler()
])
# def check_aws_status():
def check_aws_configuration():
"""Check for AWS CLI configuration and prompt the user to configure if not found."""
aws_config_file = os.path.expanduser('~/.aws/config')
aws_credentials_file = os.path.expanduser('~/.aws/credentials')
if not os.path.exists(aws_config_file) or not os.path.exists(aws_credentials_file):
click.echo("AWS CLI is not configured on this system.")
if click.confirm("Do you want to configure AWS CLI now?"):
try:
subprocess.run(["aws", "configure"], check=True)
except subprocess.CalledProcessError as e:
click.echo(
"Failed to run 'aws configure'. Please ensure AWS CLI is installed.")
except FileNotFoundError:
click.echo(
"AWS CLI not found. Please install AWS CLI and run 'aws configure'.")
else:
click.echo("AWS CLI configuration is required to deploy. Exiting.")
exit(1)
else:
click.echo("AWS CLI is already configured.")
@click.group()
def cli():
"""Demo CLI for webapp deployment"""
pass
@click.command()
def init():
"""Initialize a new project configuration"""
check_aws_configuration()
project_name = click.prompt("Please enter your project name", type=str)
# Sanitize project name by replacing spaces, slashes, and backslashes
sanitized_project_name = re.sub(r'[ /\\]', '_', project_name)
config_filename = f"{sanitized_project_name}_fd_config.json"
# Scan the directory for any existing _config.json files
existing_configs = [f for f in os.listdir(
'.') if f.endswith('_fd_config.json')]
# If any existing configuration file is found, prompt for overwrite
if existing_configs:
click.echo(
f"Found existing project configuration(s): {', '.join(existing_configs)}")
confirm = click.confirm(
"Do you want to overwrite the existing project configuration(s)?", default=False)
if not confirm:
click.echo("Initialization cancelled. No changes made.")
return
else:
# If user confirms, delete all existing configuration files
for config_file in existing_configs:
os.remove(config_file)
config = {
"project_name": sanitized_project_name,
"instance_type": "t2.micro", # Default value, can be changed by user later
}
# Save the new configuration to a file
with open(config_filename, 'w') as config_file:
json.dump(config, config_file, indent=4)
logging.info(
f"Project '{sanitized_project_name}' initialized with new configuration, previous configurations were overwritten.")
click.echo(
f"Project '{sanitized_project_name}' initialized and existing configuration(s) overwritten.")
@click.command()
def build():
"""Build a Docker image using Nixpacks"""
project_path = os.getcwd() # Assuming we are building in the current directory
image_name = click.prompt("Please enter your image name", type=str)
logging.info("Building Docker image with Nixpacks...")
click.echo("Building Docker image with Nixpacks...")
# try:
# # Build with Dockerfile
# build_result = subprocess.run(["nixpacks", "build", "--dockerfile",
# "--no-cache", project_path], capture_output=True, text=True, check=True)
# # Assuming the output from the build command is the Dockerfile content
# dockerfile_content = build_result.stdout
# # Optional: Modify the Dockerfile content here if necessary
# dockerfile_content = dockerfile_content.replace(
# """
# ╔══════════════════════════════ Nixpacks v1.21.0 ══════════════════════════════╗
# ║ setup │ python38, gcc ║
# ║──────────────────────────────────────────────────────────────────────────────║
# ║ install │ python -m venv --copies /opt/venv && . /opt/venv/bin/activate ║
# ║ │ && pip install -r requirements.txt ║
# ║──────────────────────────────────────────────────────────────────────────────║
# ║ start │ python main.py ║
# ╚══════════════════════════════════════════════════════════════════════════════╝
# """, "")
# # Write the Dockerfile content to a Dockerfile in the project directory
# dockerfile_path = os.path.join(project_path, "Dockerfile")
# with open(dockerfile_path, 'w') as dockerfile:
# dockerfile.write(dockerfile_content)
# click.echo(f"Dockerfile created at {dockerfile_path}")
# except subprocess.CalledProcessError as e:
# error_message = e.stderr # Capture the standard error output for the error message
# logging.error(
# f"Error during the Dockerfile creation process: {error_message}")
# click.echo(
# f"Error during the Dockerfile creation process: {error_message}")
# return
try:
# Build with Dockerfile
# build_result = subprocess.run(["nixpacks", "build", "--dockerfile", project_path], capture_output=True, text=True, check=True)
# modified_build_output = build_result.stdout.replace("some text to find", "new text")
# click.echo(modified_build_output)
# Build with image name
build_with_name_result = subprocess.run(
["nixpacks", "build", f"--name={image_name}", project_path], capture_output=True, text=True, check=True)
modified_build_with_name_output = build_with_name_result.stdout.replace(
"docker run -it", "docker run -p PORT:PORT -it")
click.echo(modified_build_with_name_output)
except subprocess.CalledProcessError as e:
error_message = e.stderr # Capture the standard error output for the error message
logging.error(f"Error during the build process: {error_message}")
click.echo(f"Error during the build process: {error_message}")
return
@click.command()
def deploy():
"""Deploy to AWS EC2 instance (simulation)"""
# Attempt to find any configuration files in the current directory
config_files = [f for f in os.listdir(
'.') if f.endswith('_fd_config.json')]
if not config_files:
click.echo("No project configuration found. Please run 'init' first.")
return
# If there's exactly one config file, use it; otherwise, prompt the user to specify the project name
if len(config_files) == 1:
config_filename = config_files[0]
else:
project_name = click.prompt(
"Multiple projects detected. Please enter the project name", type=str)
sanitized_project_name = re.sub(r'[ /\\]', '_', project_name)
config_filename = f"{sanitized_project_name}_config.json"
if not os.path.exists(config_filename):
click.echo(
f"No configuration found for project '{sanitized_project_name}'. Please check the project name and try again.")
return
with open(config_filename, 'r') as config_file:
config = json.load(config_file)
# Prompt for EC2 instance type with the default from config or t2.micro if not specified
instance_type = click.prompt("Please enter the EC2 instance type",
type=str, default=config.get("instance_type", "t2.micro"))
logging.info(
f"Deploying to AWS EC2 instance of type {instance_type}... (simulated)")
click.echo(
f"Deploying to AWS EC2 instance of type {instance_type}... (simulated)")
# Add commands to the CLI group
cli.add_command(init)
cli.add_command(build)
cli.add_command(deploy)
if __name__ == '__main__':
cli()