1+ # ============================================================
2+ # Script: Cleanup NASA Gallery Infrastructure
3+ # Versão: 4.0 (LinkedIn/Demo Ready - Privacy Mode)
4+ # ============================================================
5+
6+ $ErrorActionPreference = " Stop"
7+ Clear-Host
8+
9+ Write-Host @"
10+ ╔══════════════════════════════════════════════════════════╗
11+ ║ 🧹 LIMPEZA COMPLETA - NASA Gallery AWS ║
12+ ║ Remoção Segura de Recursos e Redução de Custos ║
13+ ║ Status: Production-Ready ║
14+ ╚══════════════════════════════════════════════════════════╝
15+ "@ - ForegroundColor Cyan
16+
17+ # ============================================================
18+ # PARTE 1: VALIDAÇÃO E SEGURANÇA
19+ # ============================================================
20+
21+ Write-Host " `n [CHECK 1/3] Validando credenciais..." - ForegroundColor Yellow
22+ try {
23+ aws sts get-caller - identity -- output json | Out-Null
24+ Write-Host " ✅ AWS CLI Autenticado" - ForegroundColor Green
25+ Write-Host " 🔒 Conta: ************ (Oculto)" - ForegroundColor Gray
26+ } catch {
27+ Write-Host " ❌ Falha na autenticação AWS CLI" - ForegroundColor Red
28+ exit 1
29+ }
30+
31+ Write-Host " `n [CHECK 2/3] Identificando recursos..." - ForegroundColor Yellow
32+ $resourcesFile = " aws-resources.txt"
33+ $VPC_ID = $null
34+
35+ # Tenta carregar do arquivo
36+ if (Test-Path $resourcesFile ) {
37+ Get-Content $resourcesFile | ForEach-Object {
38+ if ($_ -match ' (.+)=(.+)' ) { Set-Variable - Name $matches [1 ].Trim() - Value $matches [2 ].Trim() - Scope Script }
39+ }
40+ Write-Host " ✅ Mapeamento carregado via arquivo local" - ForegroundColor Green
41+ }
42+
43+ # Fallback: Se não achar no arquivo, busca na AWS por TAG
44+ if (-not $VPC_ID ) {
45+ Write-Host " ⚠️ Arquivo não encontrado. Buscando por Tags..." - ForegroundColor Yellow
46+ $VPC_ID = aws ec2 describe- vpcs -- filters " Name=tag:Name,Values=NASA-Gallery-VPC" -- query ' Vpcs[0].VpcId' -- output text 2> $null
47+ if ($VPC_ID -and $VPC_ID -ne " None" ) {
48+ Write-Host " ✅ Infraestrutura localizada: $VPC_ID " - ForegroundColor Green
49+ } else {
50+ Write-Host " ❌ Nenhuma infraestrutura encontrada para limpar." - ForegroundColor Red
51+ exit 0
52+ }
53+ }
54+
55+ Write-Host " `n [CHECK 3/3] Confirmação de Exclusão" - ForegroundColor Yellow
56+ Write-Host " ⚠️ ATENÇÃO: Esta ação é irreversível e deletará:" - ForegroundColor Red
57+ Write-Host " • EC2, NAT Gateway, VPC, Subnets, Security Groups" - ForegroundColor Gray
58+ Write-Host " • Economia estimada: ~`$ 40/mês" - ForegroundColor Green
59+
60+ Write-Host " `n " - NoNewline
61+ $confirmation = Read-Host " Digite 'CONFIRMAR' para destruir a infraestrutura"
62+
63+ if ($confirmation -ne " CONFIRMAR" ) {
64+ Write-Host " `n ❌ Operação cancelada." - ForegroundColor Yellow
65+ exit 0
66+ }
67+
68+ Write-Host " `n 🚀 Iniciando processo de limpeza..." - ForegroundColor Cyan
69+ Start-Sleep - Seconds 2
70+
71+ # ============================================================
72+ # PARTE 2: DELEÇÃO DE COMPUTAÇÃO E NAT (Lento)
73+ # ============================================================
74+
75+ Write-Host " `n [1/6] Terminando Instância EC2..." - ForegroundColor Yellow
76+ # Busca ID atualizado caso não tenha vindo do arquivo
77+ $INST_ID = aws ec2 describe- instances -- filters " Name=tag:Name,Values=NASA-Gallery-Web" " Name=instance-state-name,Values=running,pending,stopped" -- query ' Reservations[0].Instances[0].InstanceId' -- output text 2> $null
78+
79+ if ($INST_ID -and $INST_ID -ne " None" ) {
80+ aws ec2 terminate- instances -- instance- ids $INST_ID | Out-Null
81+ Write-Host " ⏳ Aguardando terminação da instância..." - ForegroundColor Cyan
82+ aws ec2 wait instance- terminated -- instance- ids $INST_ID
83+ Write-Host " ✅ Instância EC2 terminada" - ForegroundColor Green
84+ } else {
85+ Write-Host " ℹ️ Nenhuma instância ativa encontrada" - ForegroundColor Gray
86+ }
87+
88+ Write-Host " `n [2/6] Removendo NAT Gateway (Isso leva tempo)..." - ForegroundColor Yellow
89+ $NAT_ID = aws ec2 describe- nat- gateways -- filter " Name=tag:Name,Values=NASA-Gallery-NAT" " Name=state,Values=available,pending" -- query ' NatGateways[0].NatGatewayId' -- output text 2> $null
90+
91+ if ($NAT_ID -and $NAT_ID -ne " None" ) {
92+ aws ec2 delete- nat- gateway -- nat- gateway- id $NAT_ID | Out-Null
93+ Write-Host " ⏳ Aguardando AWS liberar o NAT Gateway..." - ForegroundColor Cyan
94+
95+ # Loop visual para o vídeo não ficar estático
96+ $countdown = 0
97+ while ($true ) {
98+ $state = aws ec2 describe- nat- gateways -- nat- gateway- ids $NAT_ID -- query ' NatGateways[0].State' -- output text 2> $null
99+ if ($state -eq " deleted" -or -not $state ) { break }
100+ Start-Sleep - Seconds 10
101+ Write-Host - NoNewline " ·"
102+ $countdown ++
103+ if ($countdown -gt 60 ) { break } # Safety break
104+ }
105+ Write-Host " `n ✅ NAT Gateway removido" - ForegroundColor Green
106+ } else {
107+ Write-Host " ℹ️ NAT Gateway já removido ou inexistente" - ForegroundColor Gray
108+ }
109+
110+ # ============================================================
111+ # PARTE 3: LIMPEZA DE REDE
112+ # ============================================================
113+
114+ Write-Host " `n [3/6] Liberando Elastic IP..." - ForegroundColor Yellow
115+ $EIP_ID = aws ec2 describe- addresses -- filters " Name=tag:Name,Values=NAT-Gateway-EIP" -- query ' Addresses[0].AllocationId' -- output text 2> $null
116+ if ($EIP_ID -and $EIP_ID -ne " None" ) {
117+ aws ec2 release- address -- allocation- id $EIP_ID 2> $null
118+ Write-Host " ✅ Elastic IP liberado" - ForegroundColor Green
119+ }
120+
121+ Write-Host " `n [4/6] Removendo Gateway de Internet..." - ForegroundColor Yellow
122+ $IGW_ID = aws ec2 describe- internet- gateways -- filters " Name=tag:Name,Values=NASA-Gallery-IGW" -- query ' InternetGateways[0].InternetGatewayId' -- output text 2> $null
123+ if ($IGW_ID -and $IGW_ID -ne " None" ) {
124+ aws ec2 detach- internet- gateway -- internet- gateway- id $IGW_ID -- vpc- id $VPC_ID 2> $null
125+ aws ec2 delete- internet- gateway -- internet- gateway- id $IGW_ID 2> $null
126+ Write-Host " ✅ Internet Gateway removido" - ForegroundColor Green
127+ }
128+
129+ Write-Host " `n [5/6] Limpando Subnets, Rotas e Security Groups..." - ForegroundColor Yellow
130+
131+ # Ordem correta de dependência
132+ # 1. Subnets
133+ $subnets = aws ec2 describe- subnets -- filters " Name=vpc-id,Values=$VPC_ID " -- query ' Subnets[*].SubnetId' -- output text 2> $null
134+ if ($subnets ) {
135+ foreach ($sub in $subnets.Split (" `t " )) {
136+ if ($sub ) { aws ec2 delete- subnet -- subnet- id $sub 2> $null }
137+ }
138+ Write-Host " ✅ Subnets removidas" - ForegroundColor Green
139+ }
140+
141+ # 2. Route Tables (exceto a Main)
142+ $rts = aws ec2 describe- route- tables -- filters " Name=vpc-id,Values=$VPC_ID " -- query ' RouteTables[?Associations==`[]`].RouteTableId' -- output text 2> $null
143+ if ($rts ) {
144+ foreach ($rt in $rts.Split (" `t " )) {
145+ if ($rt ) { aws ec2 delete- route- table -- route- table- id $rt 2> $null }
146+ }
147+ Write-Host " ✅ Route Tables removidas" - ForegroundColor Green
148+ }
149+
150+ # 3. Security Groups (exceto default)
151+ $sgs = aws ec2 describe- security- groups -- filters " Name=vpc-id,Values=$VPC_ID " " Name=group-name,Values=nasa-gallery-sg" -- query ' SecurityGroups[*].GroupId' -- output text 2> $null
152+ if ($sgs ) {
153+ aws ec2 delete- security- group -- group-id $sgs 2> $null
154+ Write-Host " ✅ Security Group removido" - ForegroundColor Green
155+ }
156+
157+ # 4. VPC
158+ if ($VPC_ID ) {
159+ aws ec2 delete- vpc -- vpc- id $VPC_ID 2> $null
160+ Write-Host " ✅ VPC deletada com sucesso" - ForegroundColor Green
161+ }
162+
163+ # ============================================================
164+ # PARTE 4: ARQUIVOS LOCAIS
165+ # ============================================================
166+
167+ Write-Host " `n [6/6] Limpando arquivos locais..." - ForegroundColor Yellow
168+ aws ec2 delete- key- pair -- key- name nasa- gallery- key 2> $null
169+
170+ $files = @ (" nasa-gallery-key.pem" , " aws-resources.txt" )
171+ foreach ($file in $files ) {
172+ if (Test-Path $file ) {
173+ Remove-Item $file - Force
174+ Write-Host " ✅ Arquivo removido: $file " - ForegroundColor Green
175+ }
176+ }
177+
178+ Write-Host @"
179+
180+ ╔══════════════════════════════════════════════════════════╗
181+ ║ ✅ LIMPEZA CONCLUÍDA ║
182+ ╚══════════════════════════════════════════════════════════╝
183+
184+ 📊 Status Final:
185+ • Recursos AWS: Totalmente removidos
186+ • Custos Futuros: `$`0 .00
187+ • Arquivos Locais: Limpos
188+
189+ 👋 Pronto para o próximo laboratório!
190+
191+ "@ - ForegroundColor Cyan
0 commit comments