AWS (Amazon Web Services) para .NET Senior
📋 Visão Geral
AWS é a plataforma de cloud computing mais popular do mundo, oferecendo mais de 200 serviços para infraestrutura, desenvolvimento, segurança e análise. Permite construir aplicações escaláveis, seguras e de alta disponibilidade.
☁️ Serviços de Computação
EC2 (Elastic Compute Cloud)
O que é: Serviço de computação em nuvem que fornece capacidade computacional redimensionável.
Características:
- Instâncias virtuais configuráveis
- Múltiplos tipos de instância (t2, t3, m5, c5, r5, etc.)
- Auto Scaling Groups
- Load Balancing
- Elastic IPs
Casos de Uso:
- Aplicações web tradicionais
- Servidores de banco de dados
- Processamento de dados
- Desenvolvimento e teste
// Exemplo: Deploy de aplicação .NET no EC2
public class EC2Deployment
{
private readonly IAmazonEC2 _ec2Client;
public async Task<string> DeployApplicationAsync()
{
var request = new RunInstancesRequest
{
ImageId = "ami-12345678",
InstanceType = InstanceType.T2Micro,
MinCount = 1,
MaxCount = 1,
SecurityGroupIds = new List<string> { "sg-12345678" },
SubnetId = "subnet-12345678",
UserData = Convert.ToBase64String(Encoding.UTF8.GetBytes(@"
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
"))
};
var response = await _ec2Client.RunInstancesAsync(request);
return response.Reservation.Instances[0].InstanceId;
}
}Lambda (Serverless Computing)
O que é: Serviço de computação serverless que executa código em resposta a eventos.
Características:
- Execução sob demanda
- Escalabilidade automática
- Pay-per-use
- Integração com outros serviços AWS
- Suporte a múltiplas linguagens
Casos de Uso:
- Processamento de eventos
- APIs serverless
- Automação de tarefas
- Processamento de dados
// Exemplo: Lambda Function em C#
public class OrderProcessor
{
public async Task<APIGatewayProxyResponse> ProcessOrderAsync(APIGatewayProxyRequest request)
{
var order = JsonSerializer.Deserialize<Order>(request.Body);
using var dynamoDb = new AmazonDynamoDBClient();
var tableName = Environment.GetEnvironmentVariable("ORDERS_TABLE");
var item = new Dictionary<string, AttributeValue>
{
["OrderId"] = new AttributeValue { S = order.Id.ToString() },
["CustomerId"] = new AttributeValue { S = order.CustomerId.ToString() },
["Total"] = new AttributeValue { N = order.Total.ToString() },
["Status"] = new AttributeValue { S = "Created" },
["CreatedAt"] = new AttributeValue { S = DateTime.UtcNow.ToString("O") }
};
await dynamoDb.PutItemAsync(tableName, item);
// Enviar notificação via SNS
using var snsClient = new AmazonSimpleNotificationServiceClient();
var message = JsonSerializer.Serialize(new { orderId = order.Id, status = "Created" });
await snsClient.PublishAsync("arn:aws:sns:region:account:order-notifications", message);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Body = JsonSerializer.Serialize(new { success = true, orderId = order.Id })
};
}
}ECS (Elastic Container Service)
O que é: Serviço de orquestração de containers totalmente gerenciado.
Características:
- Suporte a Docker containers
- Auto scaling
- Load balancing integrado
- Task definitions
- Service discovery
// Exemplo: Deploy de container .NET no ECS
public class ECSDeployment
{
private readonly IAmazonECS _ecsClient;
public async Task<string> DeployContainerAsync()
{
var taskDefinition = new RegisterTaskDefinitionRequest
{
Family = "my-app",
NetworkMode = NetworkMode.Awsvpc,
RequiresCompatibilities = new List<string> { "FARGATE" },
Cpu = "256",
Memory = "512",
ExecutionRoleArn = "arn:aws:iam::account:role/ecsTaskExecutionRole",
ContainerDefinitions = new List<ContainerDefinition>
{
new ContainerDefinition
{
Name = "my-app",
Image = "123456789012.dkr.ecr.region.amazonaws.com/my-app:latest",
PortMappings = new List<PortMapping>
{
new PortMapping { ContainerPort = 80, Protocol = TransportProtocol.Tcp }
},
Environment = new List<KeyValuePair>
{
new KeyValuePair { Name = "ASPNETCORE_ENVIRONMENT", Value = "Production" }
}
}
}
};
var response = await _ecsClient.RegisterTaskDefinitionAsync(taskDefinition);
return response.TaskDefinition.TaskDefinitionArn;
}
}🗄️ Serviços de Banco de Dados
RDS (Relational Database Service)
O que é: Serviço de banco de dados relacional gerenciado.
Características:
- Suporte a múltiplos engines (MySQL, PostgreSQL, SQL Server, Oracle)
- Backup automático
- Multi-AZ deployment
- Read replicas
- Encryption at rest
// Exemplo: Conexão com RDS SQL Server
public class RDSConnection
{
private readonly string _connectionString;
public RDSConnection()
{
_connectionString = "Server=my-rds-instance.region.rds.amazonaws.com;" +
"Database=MyDatabase;" +
"User Id=admin;" +
"Password=password;" +
"TrustServerCertificate=true;";
}
public async Task<List<Order>> GetOrdersAsync()
{
using var connection = new SqlConnection(_connectionString);
await connection.OpenAsync();
var orders = await connection.QueryAsync<Order>(
"SELECT * FROM Orders WHERE Status = @Status",
new { Status = "Active" });
return orders.ToList();
}
}DynamoDB (NoSQL Database)
O que é: Banco de dados NoSQL totalmente gerenciado.
Características:
- Performance consistente
- Escalabilidade automática
- Backup point-in-time
- Global tables
- Streams para eventos
// Exemplo: Operações com DynamoDB
public class DynamoDBService
{
private readonly IAmazonDynamoDB _dynamoDbClient;
private readonly string _tableName;
public DynamoDBService(IAmazonDynamoDB dynamoDbClient, string tableName)
{
_dynamoDbClient = dynamoDbClient;
_tableName = tableName;
}
public async Task<Order> GetOrderAsync(string orderId)
{
var request = new GetItemRequest
{
TableName = _tableName,
Key = new Dictionary<string, AttributeValue>
{
["OrderId"] = new AttributeValue { S = orderId }
}
};
var response = await _dynamoDbClient.GetItemAsync(request);
if (response.Item == null)
return null;
return new Order
{
Id = response.Item["OrderId"].S,
CustomerId = response.Item["CustomerId"].S,
Total = decimal.Parse(response.Item["Total"].N),
Status = response.Item["Status"].S
};
}
public async Task SaveOrderAsync(Order order)
{
var request = new PutItemRequest
{
TableName = _tableName,
Item = new Dictionary<string, AttributeValue>
{
["OrderId"] = new AttributeValue { S = order.Id },
["CustomerId"] = new AttributeValue { S = order.CustomerId },
["Total"] = new AttributeValue { N = order.Total.ToString() },
["Status"] = new AttributeValue { S = order.Status },
["CreatedAt"] = new AttributeValue { S = DateTime.UtcNow.ToString("O") }
}
};
await _dynamoDbClient.PutItemAsync(request);
}
}ElastiCache (Caching)
O que é: Serviço de cache em memória gerenciado.
Características:
- Suporte a Redis e Memcached
- Multi-AZ deployment
- Encryption in transit
- Backup e restore
// Exemplo: Cache com Redis via ElastiCache
public class RedisCacheService
{
private readonly ConnectionMultiplexer _redis;
public RedisCacheService(string connectionString)
{
_redis = ConnectionMultiplexer.Connect(connectionString);
}
public async Task<T> GetAsync<T>(string key)
{
var database = _redis.GetDatabase();
var value = await database.StringGetAsync(key);
if (value.IsNull)
return default(T);
return JsonSerializer.Deserialize<T>(value);
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
var database = _redis.GetDatabase();
var serializedValue = JsonSerializer.Serialize(value);
await database.StringSetAsync(key, serializedValue, expiry);
}
}📡 Serviços de Mensageria
SQS (Simple Queue Service)
O que é: Serviço de filas de mensagens totalmente gerenciado.
Características:
- Filas padrão e FIFO
- Dead letter queues
- Visibility timeout
- Long polling
- Encryption
// Exemplo: Producer e Consumer com SQS
public class SQSProducer
{
private readonly IAmazonSQS _sqsClient;
private readonly string _queueUrl;
public SQSProducer(IAmazonSQS sqsClient, string queueUrl)
{
_sqsClient = sqsClient;
_queueUrl = queueUrl;
}
public async Task SendMessageAsync(Order order)
{
var message = JsonSerializer.Serialize(order);
var request = new SendMessageRequest
{
QueueUrl = _queueUrl,
MessageBody = message,
MessageAttributes = new Dictionary<string, MessageAttributeValue>
{
["OrderType"] = new MessageAttributeValue
{
DataType = "String",
StringValue = order.Type
}
}
};
await _sqsClient.SendMessageAsync(request);
}
}
public class SQSConsumer
{
private readonly IAmazonSQS _sqsClient;
private readonly string _queueUrl;
public SQSConsumer(IAmazonSQS sqsClient, string queueUrl)
{
_sqsClient = sqsClient;
_queueUrl = queueUrl;
}
public async Task ProcessMessagesAsync()
{
var request = new ReceiveMessageRequest
{
QueueUrl = _queueUrl,
MaxNumberOfMessages = 10,
WaitTimeSeconds = 20
};
var response = await _sqsClient.ReceiveMessageAsync(request);
foreach (var message in response.Messages)
{
try
{
var order = JsonSerializer.Deserialize<Order>(message.Body);
await ProcessOrderAsync(order);
await _sqsClient.DeleteMessageAsync(_queueUrl, message.ReceiptHandle);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing message: {ex.Message}");
}
}
}
}SNS (Simple Notification Service)
O que é: Serviço de publicação/assinatura de mensagens.
Características:
- Topics e subscriptions
- Múltiplos protocolos (HTTP, HTTPS, Email, SMS)
- Message filtering
- Dead letter queues
// Exemplo: Publicação e assinatura com SNS
public class SNSPublisher
{
private readonly IAmazonSimpleNotificationService _snsClient;
private readonly string _topicArn;
public SNSPublisher(IAmazonSimpleNotificationService snsClient, string topicArn)
{
_snsClient = snsClient;
_topicArn = topicArn;
}
public async Task PublishOrderEventAsync(Order order)
{
var message = JsonSerializer.Serialize(new
{
orderId = order.Id,
customerId = order.CustomerId,
status = order.Status,
timestamp = DateTime.UtcNow
});
var request = new PublishRequest
{
TopicArn = _topicArn,
Message = message,
MessageAttributes = new Dictionary<string, MessageAttributeValue>
{
["EventType"] = new MessageAttributeValue
{
DataType = "String",
StringValue = "OrderCreated"
}
}
};
await _snsClient.PublishAsync(request);
}
}📧 Serviços de Email
SES (Simple Email Service)
O que é: Serviço de email transacional escalável.
Características:
- Envio de emails transacionais
- Templates de email
- Configuração de domínios
- Reputation management
- Bounce e complaint handling
// Exemplo: Envio de email com SES
public class SESEmailService
{
private readonly IAmazonSimpleEmailService _sesClient;
private readonly string _fromEmail;
public SESEmailService(IAmazonSimpleEmailService sesClient, string fromEmail)
{
_sesClient = sesClient;
_fromEmail = fromEmail;
}
public async Task SendOrderConfirmationAsync(Order order, string customerEmail)
{
var request = new SendEmailRequest
{
Source = _fromEmail,
Destination = new Destination
{
ToAddresses = new List<string> { customerEmail }
},
Message = new Message
{
Subject = new Content
{
Charset = "UTF-8",
Data = $"Confirmação do Pedido #{order.Id}"
},
Body = new Body
{
Html = new Content
{
Charset = "UTF-8",
Data = $@"
<h1>Pedido Confirmado</h1>
<p>Olá! Seu pedido #{order.Id} foi confirmado.</p>
<p>Total: R$ {order.Total:F2}</p>
<p>Status: {order.Status}</p>
"
}
}
}
};
await _sesClient.SendEmailAsync(request);
}
public async Task SendTemplatedEmailAsync(string templateName, string customerEmail, Dictionary<string, string> templateData)
{
var request = new SendTemplatedEmailRequest
{
Source = _fromEmail,
Destination = new Destination
{
ToAddresses = new List<string> { customerEmail }
},
Template = templateName,
TemplateData = JsonSerializer.Serialize(templateData)
};
await _sesClient.SendTemplatedEmailAsync(request);
}
}🔒 Serviços de Segurança
IAM (Identity and Access Management)
O que é: Serviço de controle de acesso e identidade.
Características:
- Users, groups e roles
- Policies e permissions
- Multi-factor authentication
- Access keys
- Cross-account access
// Exemplo: Verificação de permissões IAM
public class IAMService
{
private readonly IAmazonIdentityManagementService _iamClient;
public IAMService(IAmazonIdentityManagementService iamClient)
{
_iamClient = iamClient;
}
public async Task<bool> UserHasPermissionAsync(string userName, string permission)
{
var request = new SimulatePrincipalPolicyRequest
{
PolicySourceArn = $"arn:aws:iam::{Environment.GetEnvironmentVariable("AWS_ACCOUNT_ID")}:user/{userName}",
ActionNames = new List<string> { permission },
ResourceArns = new List<string> { "*" }
};
var response = await _iamClient.SimulatePrincipalPolicyAsync(request);
return response.EvaluationResults.Any(r => r.EvalDecision == "allowed");
}
}Cognito (Authentication)
O que é: Serviço de autenticação e autorização.
Características:
- User pools e identity pools
- Social identity providers
- Multi-factor authentication
- JWT tokens
- App client integration
// Exemplo: Autenticação com Cognito
public class CognitoAuthenticationService
{
private readonly IAmazonCognitoIdentityProvider _cognitoClient;
private readonly string _clientId;
private readonly string _userPoolId;
public CognitoAuthenticationService(IAmazonCognitoIdentityProvider cognitoClient, string clientId, string userPoolId)
{
_cognitoClient = cognitoClient;
_clientId = clientId;
_userPoolId = userPoolId;
}
public async Task<AuthenticationResult> SignInAsync(string username, string password)
{
var request = new InitiateAuthRequest
{
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
ClientId = _clientId,
AuthParameters = new Dictionary<string, string>
{
["USERNAME"] = username,
["PASSWORD"] = password
}
};
var response = await _cognitoClient.InitiateAuthAsync(request);
return new AuthenticationResult
{
IsSuccess = response.AuthenticationResult != null,
IdToken = response.AuthenticationResult?.IdToken,
AccessToken = response.AuthenticationResult?.AccessToken,
RefreshToken = response.AuthenticationResult?.RefreshToken
};
}
public async Task<bool> SignUpAsync(string username, string email, string password)
{
var request = new SignUpRequest
{
ClientId = _clientId,
Username = username,
Password = password,
UserAttributes = new List<AttributeType>
{
new AttributeType
{
Name = "email",
Value = email
}
}
};
try
{
await _cognitoClient.SignUpAsync(request);
return true;
}
catch
{
return false;
}
}
}📊 Serviços de Monitoramento
CloudWatch
O que é: Serviço de monitoramento e observabilidade.
Características:
- Métricas customizadas
- Logs centralizados
- Dashboards
- Alarmes
- Insights
// Exemplo: Métricas customizadas com CloudWatch
public class CloudWatchMetrics
{
private readonly IAmazonCloudWatch _cloudWatchClient;
public CloudWatchMetrics(IAmazonCloudWatch cloudWatchClient)
{
_cloudWatchClient = cloudWatchClient;
}
public async Task PutMetricAsync(string metricName, double value, Dictionary<string, string> dimensions = null)
{
var request = new PutMetricDataRequest
{
Namespace = "MyApplication",
MetricData = new List<MetricDatum>
{
new MetricDatum
{
MetricName = metricName,
Value = value,
Unit = StandardUnit.Count,
Dimensions = dimensions?.Select(d => new Dimension
{
Name = d.Key,
Value = d.Value
}).ToList()
}
}
};
await _cloudWatchClient.PutMetricDataAsync(request);
}
public async Task LogOrderCreatedAsync(Order order)
{
await PutMetricAsync("OrdersCreated", 1, new Dictionary<string, string>
{
["OrderType"] = order.Type,
["CustomerSegment"] = order.CustomerSegment
});
}
}X-Ray
O que é: Serviço de distributed tracing.
Características:
- Traçamento distribuído
- Análise de performance
- Debugging de problemas
- Service map
// Exemplo: Tracing com X-Ray
public class XRayTracing
{
public async Task<Order> ProcessOrderWithTracingAsync(Order order)
{
using var segment = AWSXRayRecorder.Instance.BeginSubsegment("ProcessOrder");
try
{
segment.AddAnnotation("OrderId", order.Id.ToString());
segment.AddAnnotation("CustomerId", order.CustomerId.ToString());
// Processar pedido
await ProcessOrderAsync(order);
segment.AddMetadata("OrderTotal", order.Total);
return order;
}
catch (Exception ex)
{
segment.AddException(ex);
throw;
}
}
}🗄️ Serviços de Storage
S3 (Simple Storage Service)
O que é: Serviço de armazenamento de objetos.
Características:
- Armazenamento escalável
- Múltiplas classes de storage
- Versionamento
- Lifecycle policies
- Encryption
// Exemplo: Operações com S3
public class S3Service
{
private readonly IAmazonS3 _s3Client;
private readonly string _bucketName;
public S3Service(IAmazonS3 s3Client, string bucketName)
{
_s3Client = s3Client;
_bucketName = bucketName;
}
public async Task<string> UploadFileAsync(Stream fileStream, string key, string contentType)
{
var request = new PutObjectRequest
{
BucketName = _bucketName,
Key = key,
InputStream = fileStream,
ContentType = contentType
};
await _s3Client.PutObjectAsync(request);
return $"https://{_bucketName}.s3.amazonaws.com/{key}";
}
public async Task<Stream> DownloadFileAsync(string key)
{
var request = new GetObjectRequest
{
BucketName = _bucketName,
Key = key
};
var response = await _s3Client.GetObjectAsync(request);
return response.ResponseStream;
}
public async Task DeleteFileAsync(string key)
{
var request = new DeleteObjectRequest
{
BucketName = _bucketName,
Key = key
};
await _s3Client.DeleteObjectAsync(request);
}
}🔧 Configuração e Deploy
CloudFormation
O que é: Serviço de Infrastructure as Code.
Características:
- Templates JSON/YAML
- Stack management
- Rollback automático
- Nested stacks
# Exemplo: Template CloudFormation para aplicação .NET
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Aplicação .NET com Lambda, DynamoDB e S3'
Resources:
OrdersTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: Orders
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: OrderId
AttributeType: S
KeySchema:
- AttributeName: OrderId
KeyType: HASH
OrderProcessorFunction:
Type: AWS::Lambda::Function
Properties:
FunctionName: OrderProcessor
Runtime: dotnet6
Handler: OrderProcessor::OrderProcessor.Function::FunctionHandler
Code:
ZipFile: |
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;
public class Function
{
public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
{
return new APIGatewayProxyResponse
{
StatusCode = 200,
Body = "Hello from Lambda!"
};
}
}
Role: !GetAtt LambdaExecutionRole.Arn
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: DynamoDBAccess
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: !GetAtt OrdersTable.ArnCodeDeploy
O que é: Serviço de deploy automatizado.
Características:
- Deploy automático
- Rollback automático
- Blue/green deployments
- In-place deployments
// Exemplo: Deploy com CodeDeploy
public class CodeDeployService
{
private readonly IAmazonCodeDeploy _codeDeployClient;
public CodeDeployService(IAmazonCodeDeploy codeDeployClient)
{
_codeDeployClient = codeDeployClient;
}
public async Task<string> CreateDeploymentAsync(string applicationName, string deploymentGroupName, string revisionLocation)
{
var request = new CreateDeploymentRequest
{
ApplicationName = applicationName,
DeploymentGroupName = deploymentGroupName,
Revision = new RevisionLocation
{
RevisionType = RevisionLocationType.S3,
S3Location = new S3Location
{
Bucket = "my-deployment-bucket",
Key = revisionLocation,
BundleType = BundleType.Zip
}
},
DeploymentConfigName = "CodeDeployDefault.OneAtATime"
};
var response = await _codeDeployClient.CreateDeploymentAsync(request);
return response.DeploymentId;
}
}📈 Serviços de Analytics
Kinesis
O que é: Serviço de streaming de dados em tempo real.
Características:
- Data streams
- Real-time processing
- Auto scaling
- Multiple consumers
// Exemplo: Producer e Consumer com Kinesis
public class KinesisProducer
{
private readonly IAmazonKinesis _kinesisClient;
private readonly string _streamName;
public KinesisProducer(IAmazonKinesis kinesisClient, string streamName)
{
_kinesisClient = kinesisClient;
_streamName = streamName;
}
public async Task PutRecordAsync(Order order)
{
var data = JsonSerializer.Serialize(order);
var dataBytes = Encoding.UTF8.GetBytes(data);
var request = new PutRecordRequest
{
StreamName = _streamName,
Data = new MemoryStream(dataBytes),
PartitionKey = order.CustomerId.ToString()
};
await _kinesisClient.PutRecordAsync(request);
}
}⚠️ Considerações Importantes
Segurança
- IAM Roles: Use roles em vez de access keys
- Encryption: Habilite encryption em trânsito e em repouso
- VPC: Use VPC para isolamento de rede
- Security Groups: Configure security groups adequadamente
Custos
- Monitoramento: Use CloudWatch para monitorar custos
- Reserved Instances: Para cargas de trabalho previsíveis
- Spot Instances: Para workloads flexíveis
- S3 Lifecycle: Configure políticas de lifecycle
Performance
- CDN: Use CloudFront para conteúdo estático
- Caching: Implemente caching adequado
- Auto Scaling: Configure auto scaling groups
- Load Balancing: Use ALB/NLB para distribuição de carga
Monitoramento
- CloudWatch: Configure métricas e alarmes
- X-Ray: Use para distributed tracing
- Logs: Centralize logs com CloudWatch Logs
- Dashboards: Crie dashboards para visualização
📚 Recursos Adicionais
SDKs .NET
- AWS SDK for .NET: SDK oficial para .NET
- AWSSDK.Core: Core functionality
- AWSSDK.Lambda: Lambda operations
- AWSSDK.DynamoDBv2: DynamoDB operations
- AWSSDK.S3: S3 operations
Ferramentas
- AWS CLI: Command line interface
- AWS CloudFormation: Infrastructure as Code
- AWS SAM: Serverless Application Model
- AWS CDK: Infrastructure as Code com TypeScript
Documentação
- AWS Documentation: Documentação oficial
- AWS Architecture Center: Arquiteturas de referência
- AWS Well-Architected Framework: Melhores práticas
Livros Recomendados
- "AWS Lambda in Action"
- "Amazon Web Services in Action"
- "Serverless Architectures on AWS"