Skip to main content

3 posts tagged with "AWS Lambda"

View All Tags

How to Export AWS CloudWatch Logs to OpenSearch (Elasticsearch): Step-by-Step Tutorial

· 6 min read

When managing large volumes of AWS CloudWatch logs, the built-in tools may fall short in terms of searchability and cost-effectiveness. A more efficient approach is to export these logs to OpenSearch (formerly Elasticsearch), which offers better performance for log management and analysis. This blog will walk you through the entire process.

Step 1: Create an OpenSearch Cluster

Navigate to AWS Console: Navigate to the OpenSearch Service. Create a Domain:

Domain

  1. Click on “Create Domain.”
    1. Choose “Standard Create” instead of “Easy Create” to avoid unnecessary nodes.

Select Domain Configuration:

  1. For a demo, select “Dev/Test.”
    Dev or Test

  2. Choose a general-purpose instance type like the M5 family for performance.

    1. Choose the storage settings: gp3 and size (e.g., 10 GB).
    2. Select “Public Access” temporarily for easier setup (but always use VPC access in production).

Set Security Settings:

  1. Set up an IAM master user for OpenSearch.
  2. Assign a tag to the domain to make it easier to track.

Create the Domain: Wait for the domain to become active (this can take up to 30 minutes).

Step 2: Configure CloudWatch Log Group

Navigate to CloudWatch Logs:
CloudWatch Logs

  1. Select the log group you want to export. Create a Subscription Filter:

subscription filter

  1. Choose “OpenSearch” as the destination.
    1. Link the subscription filter to your OpenSearch domain created earlier.

Step 3: Create a Lambda Role

IAM Console

Navigate to IAM Console:

Role for Lambda

  1. Create a role for Lambda.
    AWS Lambda service

  2. Choose the AWS Lambda service. Attach VPC and OpenSearch Permissions:

    1. Add AWSLambdaVPCAccessExecutionRole policy . Add Inline Policy:

Inline Policy

  1. Create an inline policy allowing OpenSearch access (index permissions, bulk data access, etc.).

Following policy shows example, where it is recommended to narrow the policy from es:* only to required permission.

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "OpensearchAccess",
"Effect": "Allow",
"Action": "es:*",
"Resource": "arn:aws:es:us-east-1:<account-id>:domain/<cluster-name>"
}
]
}

Save the Role: Ensure the role is configured properly with access to both OpenSearch and CloudWatch logs.

Step 4: Edit the Lambda Function

Edit the Lambda Code:

  1. Update the code to handle exporting CloudWatch logs to specific OpenSearch indices. Modify the default index name and ensure it handles the log data properly.

Managing Users and Permissions

Modify Lambda for Multiple Log Groups:

  1. If you have multiple log groups, modify the Lambda function code to create separate indices for each log group.
  2. Update the code to check the log group name and route it to a specific index in OpenSearch. Deploy the Updates: Ensure the Lambda function properly handles log exports from multiple log groups.

In function transform (payload) around line 52, update to add additional log groups or change the index name, as shown:

function transform(payload) {
if (payload.messageType === 'CONTROL_MESSAGE') {
return null;
}

var bulkRequestBody = '';

payload.logEvents.forEach(function(logEvent) {
var timestamp = new Date(1 * logEvent.timestamp);

// Initialize indexName variable
var indexName;

// index name format: cwl-YYYY.MM.DD
if (payload.logGroup === '<log-group-1>') {
indexName = [
'cw-log-group-1-' + timestamp.getUTCFullYear(), // year
('0' + (timestamp.getUTCMonth() + 1)).slice(-2), // month
('0' + timestamp.getUTCDate()).slice(-2) // day
].join('.');

}

else {
// index name format: cw-trig-YYYY.MM.DD
indexName = [
'cw-all-other-logs-' + timestamp.getUTCFullYear(), // year
('0' + (timestamp.getUTCMonth() + 1)).slice(-2), // month
('0' + timestamp.getUTCDate()).slice(-2) // day
].join('.');
}

// var source = buildSource(logEvent.message, logEvent.extractedFields);
var source = {};
source['@id'] = logEvent.id;
source['@timestamp'] = new Date(1 * logEvent.timestamp).toISOString();
source['@message'] = logEvent.message;
source['@owner'] = payload.owner;
source['@log_group'] = payload.logGroup;
source['@log_stream'] = payload.logStream;

var action = { "index": {} };
action.index._index = indexName;
action.index._id = logEvent.id;

bulkRequestBody += [
JSON.stringify(action),
JSON.stringify(source),
].join('\n') + '\n';
});
return bulkRequestBody;
}

Deploy the Function: Once the code is set up, deploy it and link it to your log group subscription.

Step 5: Debugging and Monitoring

Monitor Logs:

  1. In the CloudWatch Logs section, monitor the log groups for any issues.
  2. Open the OpenSearch dashboard and check if the logs are properly flowing into the indices.

Handle Common Errors:

  1. If no logs appear, check the Lambda function for errors. Where in line 12, you can update following line:
var logFailedResponses = false;

to

var logFailedResponses = true;
  1. Ensure that the Lambda role has the correct permissions and that the OpenSearch cluster is properly configured.

Steps for Dashboard

Step 1: Set Up OpenSearch Users and Roles

Create OpenSearch Users:

security section

  1. In the OpenSearch dashboard, navigate to the security section.
    1. Create a user for accessing logs.

Assign Roles:

Assign Roles

  1. Create roles with index-level permissions (e.g., read-only, bulk, and monitoring).

Map

  1. Map the roles to the created users.

Test User Access:

  1. Log in as the user and ensure they can only access their assigned indices.

Step 2: Test and Monitor

Run Test Queries:

Dev Tools

  1. Use OpenSearch Dev Tools to run queries against the imported log data.
    1. Verify that the logs are properly indexed and searchable.

Monitor Cluster Health:

CloudWatch Logs

Check the OpenSearch cluster status and ensure it remains healthy. -1. Add more nodes if necessary, especially in production environments, to ensure high availability and better performance.

Conclusion

Exporting CloudWatch logs to OpenSearch offers improved search capabilities and better scalability. By following these steps, you can set up an efficient logging infrastructure that allows you to analyze large volumes of log data with ease.

Please reach out to us for any of your cloud requirements

Ready to take your cloud infrastructure to the next level? Please Contact Us

AWS services that support Containers: Containers!=Kubernetes.

· 4 min read

When it comes to choosing the right container service for your application, AWS offers a myriad of options, each tailored to specific needs and use cases. This guide aims to provide a comprehensive overview of when and how to use various AWS container services, based on our extensive research and industry experience.

Please refer The Ultimate AWS ECS and EKS Tutorial


Understanding Containers and Their Use Cases

Containers have revolutionized the way applications are developed and deployed. They offer portability, consistency, and efficiency, making them ideal for various scenarios, from microservices architectures to machine learning orchestration. Alt text


Service Orchestration

Service orchestration involves managing and coordinating multiple services or microservices to work together seamlessly. Containers play a crucial role in this by ensuring that each service runs in its isolated environment, thereby reducing conflicts and improving scalability.

  1. Kubernetes Service

    • Pros: Fully managed, scalable, extensive community support.
    • Cons: Complex setup, significant operational overhead.
  2. Red Hat OpenShift on AWS (ROSA)

    • Overview: A third-party service similar to Kubernetes, managed by OpenShift.
    • Pros: Robust management platform, popular among enterprise clients.
    • Cons: Similar complexity to Kubernetes.
  3. AWS Elastic Container Service (ECS)

    • Overview: AWS's native container orchestration service.
    • Pros: Seamless integration with AWS services, flexible deployment options (EC2, Fargate).
    • Cons: Limited to AWS ecosystem.

Machine Learning Orchestration

Deploying machine learning models in containers allows for a consistent and portable environment across different stages of the ML pipeline, from training to inference.

  1. AWS Batch
    • Overview: A native service designed for batch computing jobs, including ML training and inference.
    • Pros: Simplifies job scheduling and execution, integrates well with other AWS ML services.
    • Cons: Best suited for batch jobs, may not be ideal for real-time inference.

Web Applications.Please check out our web services Refer website solutions

Containers can also streamline the deployment and management of web applications, providing a consistent environment across development, testing, and production.

  1. AWS Elastic Beanstalk

    • Overview: A legacy service that simplifies application deployment and management.
    • Pros: Easy to use, good for traditional web applications.
    • Cons: Considered outdated, fewer modern features compared to newer services.
  2. AWS App Runner

    • Overview: A newer service that simplifies running containerized web applications and APIs.
    • Pros: Supports container deployments, integrates with AWS ECR.
    • Cons: Limited to ECR for container images, still relatively new.

Serverless Options

For applications that don't require a full-fledged orchestration setup, serverless options like AWS Lambda can be a good fit.

  1. AWS Lambda

    • Pros: Scalable, supports multiple languages, cost-effective for short-running functions.
    • Cons: Limited to 15-minute execution time, may require step functions for longer processes.
  2. Amazon EC2 vs. Amazon LightSail

    • Amazon EC2: Provides full control over virtual machines, suitable for custom setups.
    • Amazon LightSail: Simplifies VM deployment with pre-packaged software, ideal for quick deployments like WordPress.

Decision Tree for Choosing AWS Container Services

To help you choose the right service, consider the following decision tree based on your specific needs:

  1. Service Orchestration Needed?

    • Yes: Consider Kubernetes, ROSA, or ECS.
    • No: Move to the next question.
  2. Serverless Invocation?

    • Yes: If processing time < 15 minutes, use AWS Lambda. If > 15 minutes, consider App Runner.
    • No: Proceed to provisioned infrastructure options.
  3. Provisioned Infrastructure?

    • Yes: Choose between Amazon EC2 for full control or Amazon LightSail for simplified setup.
  4. Machine Learning Orchestration?

    • Yes: Use AWS Batch for batch jobs.
    • No: Skip to web application options.
  5. Web Application Deployment?

    • Yes: Use Elastic Beanstalk for legacy applications or App Runner for modern containerized applications.

Conclusion

AWS offers a robust set of services for container orchestration, machine learning, web applications, and serverless computing. Understanding the strengths and limitations of each service can help you make informed decisions and optimize your application architecture. Ready to take your cloud infrastructure to the next level? Please reach out to us Contact Us

How to Capture AWS Identity Center Events

· 3 min read

In today's fast-paced IT environments, maintaining control over user permissions and group memberships is crucial for security and compliance. AWS Identity Center (formerly known as AWS SSO) simplifies identity management across AWS, but monitoring changes in real-time can be challenging. This blog explores a serverless solution using AWS EventBridge and Lambda to notify you whenever key changes occur within your Identity Center.


Organizations often struggle with visibility into real-time changes within their identity management systems. Whether it's a new user being added, a permission change, or a group deletion, staying informed about these changes can help mitigate security risks and ensure compliance.


Setting Up the AWS Architecture




Step 1: Overview of AWS EventBridge and Lambda


AWS EventBridge is an event bus service that enables you to build event-driven applications using events generated from your AWS services, applications, or SaaS applications that you use. AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers.


Step 2: Creating EventBridge Rules


1.Navigate to the AWS Management Console and open the Amazon EventBridge service. 2.Create a Rule: Set up an event pattern to detect specific activities such as user additions, permission changes, or group deletions within AWS Identity Center. 3.Configure the Event Pattern: You may not find pre-configured templates for Identity Center, so you'll need to create a custom pattern. Here's an example of what your event pattern might look like:


{

"source": ["aws.identitycenter"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventName": ["CreateGroup", "UpdateGroup", "DeleteGroup"]
}
}

Step 3: Configuring AWS Lambda


1.Create a Lambda Function: Navigate to AWS Lambda and create a new function to process the events. 2.Set Up Permissions: Ensure your Lambda function has the necessary permissions to access EventBridge and perform actions based on the event data. 3.Implement Logic: Write the code to handle different types of events. For example, send notification emails or log entries to an S3 bucket for further analysis.


Step 4: Integrating EventBridge with Lambda


After creating the Lambda function, link it to the EventBridge rule as a target. This integration ensures that your Lambda function is triggered whenever the specified changes occur in AWS Identity Center.


Testing and Validation


Before going live, thoroughly test the setup by simulating the defined events and verifying that the Lambda function triggers appropriately and performs the intended actions.


Conclusion


Setting up real-time notifications for changes in AWS Identity Center using EventBridge and Lambda provides greater visibility and enhances security across your AWS environment. With this serverless approach, you can automate responses to critical events and maintain robust governance over your cloud resources.