From 4336763c5c055ae90b887d453e4e7edc3bbb8549 Mon Sep 17 00:00:00 2001 From: "tiago.ferreira" Date: Tue, 29 Sep 2026 14:01:45 +0000 Subject: [PATCH] Atualizar crialab.sh --- crialab.sh | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 98 insertions(+), 1 deletion(-) diff --git a/crialab.sh b/crialab.sh index 9d9cdbc..a73e3fb 100644 --- a/crialab.sh +++ b/crialab.sh @@ -1,3 +1,99 @@ +#!/usr/bin/env bash +# Infraestrutura do laboratorio. Compativel com curl -fsSL URL | bash. +# Configuracao por variaveis de ambiente; nao le perguntas de stdin. +set -Eeuo pipefail +export AWS_PAGER="" AWS_CLI_AUTO_PROMPT=off + +main() { + local mode="${1:---apply}" + case "$mode" in --plan|--apply) ;; *) echo 'Use --plan ou --apply' >&2; return 2;; esac + for tool in aws python3 curl; do + command -v "$tool" >/dev/null || { echo "Falta instalar: $tool" >&2; return 2; } + done + REGION="${REGION:-us-east-1}" + LAB_NAME="${LAB_NAME:-ssor-vpn}" + INSTANCE_TYPE="${INSTANCE_TYPE:-t3.micro}" + LOCAL_CIDR="${LOCAL_CIDR:-172.17.0.0/24}" + VPN_CIDR="${VPN_CIDR:-10.8.0.0/24}" + local create_key=false key_file='' run_id + run_id="$(date -u +%Y%m%dT%H%M%SZ)-$$" + if [[ -z "${KEY_NAME:-}" ]]; then + KEY_NAME="$LAB_NAME-$run_id" + create_key=true + fi + [[ "$LAB_NAME" =~ ^[a-zA-Z][a-zA-Z0-9-]{0,39}$ ]] || { echo 'LAB_NAME invalido' >&2; return 2; } + + # Validar as redes local e VPN. + python3 - "$LOCAL_CIDR" "$VPN_CIDR" <<'PY' +import ipaddress, sys +local, vpn = [ipaddress.IPv4Network(x, strict=True) for x in sys.argv[1:]] +vpc = ipaddress.IPv4Network('10.20.0.0/16') +private = [ipaddress.ip_network(x) for x in ['10.0.0.0/8','172.16.0.0/12','192.168.0.0/16']] +for net in [local, vpn]: + if not any(net.subnet_of(x) for x in private): + raise SystemExit('Redes local e VPN devem usar faixas privadas RFC1918.') +if local.overlaps(vpn) or local.overlaps(vpc) or vpn.overlaps(vpc): + raise SystemExit('As redes local, VPN e VPC nao podem se sobrepor.') +PY + aw() { aws --region "$REGION" "$@"; } + local account existing ami root_device az + account=$(aw sts get-caller-identity --query Account --output text) + if [[ "$create_key" == false ]]; then + aw ec2 describe-key-pairs --key-names "$KEY_NAME" >/dev/null + fi + existing=$(aw ec2 describe-vpcs --filters "Name=tag:Lab,Values=$LAB_NAME" --query 'Vpcs[].VpcId' --output text) + if [[ -n "$existing" && "$existing" != None ]]; then + echo "Ja existe uma VPC deste laboratorio: $existing. Revise-a antes de executar novamente." >&2 + return 2 + fi + # Imagem oficial Canonical Ubuntu 24.04 LTS amd64, sem Marketplace. + ami=$(aw ec2 describe-images --owners 099720109477 --filters \ + 'Name=name,Values=ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-amd64-server-*' \ + 'Name=state,Values=available' 'Name=architecture,Values=x86_64' \ + 'Name=root-device-type,Values=ebs' 'Name=virtualization-type,Values=hvm' \ + --query 'sort_by(Images,&CreationDate)[-1].ImageId' --output text) + [[ -n "$ami" && "$ami" != None ]] || { echo 'AMI Ubuntu nao encontrada.' >&2; return 2; } + root_device=$(aw ec2 describe-images --image-ids "$ami" --query 'Images[0].RootDeviceName' --output text) + az=$(aw ec2 describe-instance-type-offerings --location-type availability-zone \ + --filters "Name=instance-type,Values=$INSTANCE_TYPE" \ + --query 'sort_by(InstanceTypeOfferings,&Location)[0].Location' --output text) + [[ -n "$az" && "$az" != None ]] || { echo 'Tipo de instancia indisponivel na regiao.' >&2; return 2; } + cat < "$STATE_FILE" + trap 'echo "Falha na linha $LINENO. Recursos parciais podem existir; consulte $STATE_FILE e a tag Lab=$LAB_NAME. Nao houve rollback automatico." >&2' ERR + record() { printf '%s=%s\n' "$1" "$2" | tee -a "$STATE_FILE"; } + tags() { printf 'ResourceType=%s,Tags=[{Key=Lab,Value=%s},{Key=Name,Value=%s-%s}]' "$1" "$LAB_NAME" "$LAB_NAME" "$2"; } + record LocalCidr "$LOCAL_CIDR" + record VpnCidr "$VPN_CIDR" + record KeyName "$KEY_NAME" + record KeyCreatedByScript "$create_key" + if [[ "$create_key" == true ]]; then + key_file="$state_dir/$KEY_NAME.pem" + # noclobber impede sobrescrever uma chave preexistente; conteudo nunca vai para stdout. + # RSA/PEM sao os padroes; omitir flags novas permite usar a CLI antiga do Learner Lab. (set -o noclobber; aw ec2 create-key-pair --key-name "$KEY_NAME" \ --tag-specifications "$(tags key-pair ssh)" --query KeyMaterial --output text > "$key_file") chmod 600 "$key_file" @@ -125,4 +221,5 @@ Ao desmontar o laboratorio, desassocie e libere esse Elastic IP para encerrar su EOF } -# Executar somente depois de Bash ter lido a funcao inteira do pipe. \ No newline at end of file +# Executar somente depois de Bash ter lido a funcao inteira do pipe. +main "$@"