<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wojciech (Dogan) Doganowski on Medium]]></title>
        <description><![CDATA[Stories by Wojciech (Dogan) Doganowski on Medium]]></description>
        <link>https://medium.com/@dogan1971?source=rss-7fc0c9d83b9f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gVHrhCaxFC_BpNJtKTuC7g.png</url>
            <title>Stories by Wojciech (Dogan) Doganowski on Medium</title>
            <link>https://medium.com/@dogan1971?source=rss-7fc0c9d83b9f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:58:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dogan1971/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Running Claude Code Locally: AWS Bedrock Setup for VS Code]]></title>
            <link>https://awstip.com/running-claude-code-locally-aws-bedrock-setup-for-vs-code-77a2afb33c33?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a2afb33c33</guid>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 19:56:01 GMT</pubDate>
            <atom:updated>2026-07-18T19:56:01.522Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p><a href="https://wdoganowski.github.io/cloud-chronicles/">← All articles</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*yGBGmHHU0ocAEm1l.png" /><figcaption>Generated with DaVinci.ai</figcaption></figure><p>In previous articles in this series, we’ve covered setting up <a href="https://medium.com/aws-tip/easier-access-to-multiple-accounts-with-iam-identity-center-35bc25fdb0c8?sharedUserId=dogan1971">IAM Identity Center for multi-account access</a> and <a href="https://medium.com/aws-tip/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a?sharedUserId=dogan1971">configuring VS Code for AWS CLI and Python tasks</a>. Now, we’ll take it a step further by integrating <strong>Claude</strong>, Anthropic’s powerful AI assistant, directly into VS Code using AWS Bedrock as a backend.</p><p>Claude Code is Anthropic’s official IDE integration that brings Claude’s capabilities directly into your development environment. Unlike traditional chatbots, Claude Code can read your codebase, make edits, run commands, and help you build software more efficiently. By connecting it to AWS Bedrock instead of using direct API keys, you get the benefits of enterprise-grade security, centralized billing, and seamless integration with your existing AWS infrastructure.</p><h3>What is AWS Bedrock?</h3><p>AWS Bedrock is Amazon’s fully managed service for accessing foundation models from leading AI companies, including Anthropic’s Claude models. It provides a unified API to work with multiple AI models while maintaining your data within your AWS environment.</p><p>Benefits of using Bedrock for Claude Code:</p><p><strong>Security</strong>: All authentication flows through your existing AWS SSO and IAM policies — no API keys stored in VS Code or on your machine.</p><p><strong>Cost Management</strong>: Usage appears in your AWS billing dashboard alongside other services, making it easier to track and allocate costs.</p><p><strong>Compliance</strong>: Data stays within your AWS environment and region, helping meet regulatory requirements.</p><p><strong>Enterprise Integration</strong>: Leverage existing AWS infrastructure, policies, and access controls your organization already has in place.</p><h3>Architecture Overview</h3><p>Here’s how Claude Code integrates with AWS Bedrock:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*kCLUirpI6z68vMOa.png" /></figure><p>The authentication and request flow works as follows:</p><ol><li>You authenticate to AWS SSO using your organization’s identity provider (e.g., Entra ID, Okta)</li><li>AWS CLI stores temporary credentials in ~/.aws/sso/cache/</li><li>VS Code reads these credentials via environment variables (AWS_PROFILE, AWS_REGION)</li><li>Claude Code extension uses the AWS SDK to call Bedrock APIs</li><li>Bedrock routes your requests to the appropriate Claude model</li><li>Responses flow back through the same chain</li></ol><p><strong>No API keys required</strong> — everything authenticates through your existing AWS SSO session.</p><h3>Prerequisites</h3><p>Before starting this guide, you should have already completed:</p><p>✅ <strong>AWS CLI installed</strong> — Covered in <a href="https://medium.com/aws-tip/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a?sharedUserId=dogan1971">Using VS Code for CLI tasks — Part 2</a></p><p>✅ <strong>IAM Identity Center configured</strong> — Covered in <a href="https://medium.com/aws-tip/easier-access-to-multiple-accounts-with-iam-identity-center-35bc25fdb0c8?sharedUserId=dogan1971">Easier access to multiple accounts with IAM Identity Center</a></p><p>✅ <strong>VS Code installed</strong> — Covered in <a href="https://medium.com/aws-tip/using-vscode-for-cli-and-python-tasks-on-aws-part-1-8cbcd907eb2?sharedUserId=dogan1971">Using VS Code for CLI tasks — Part 1</a></p><p>Additionally, you’ll need:</p><p>✅ <strong>Claude Code extension</strong> — Install from VS Code marketplace: anthropic.claude-code</p><p>✅ <strong>Bedrock access</strong> — Access to AWS Bedrock in your AWS account (we’ll cover this next)</p><h3>Step 1: Enable AWS Bedrock Access</h3><h4>1.1 Verify Bedrock Availability</h4><p>Bedrock is available in specific AWS regions. For this guide, we’ll use eu-north-1 (Stockholm), but you can check availability in other regions:</p><pre># List available regions for Bedrock<br>aws ec2 describe-regions --query &quot;Regions[].RegionName&quot; --output tables</pre><p>Common Bedrock regions include:</p><ul><li>us-east-1 (N. Virginia)</li><li>us-west-2 (Oregon)</li><li>eu-west-1 (Ireland)</li><li>eu-north-1 (Stockholm)</li><li>ap-southeast-1 (Singapore)</li></ul><h4>1.2 Verify Model Access</h4><p>Claude models in Bedrock are <strong>available by default</strong> — you don’t need to request access. However, it’s good practice to verify that the models are accessible in your account:</p><ol><li>Sign in to AWS Management Console</li><li>Navigate to <strong>Bedrock</strong> service</li><li>In the left menu, click <strong>Model access</strong></li><li>Verify that Claude models show “Available” status:</li></ol><ul><li>Claude Opus 4.8 (most capable)</li><li>Claude Sonnet 4.6 (balanced, recommended)</li><li>Claude Haiku 4.5 (fast, economical)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hLnTwKUhYfyPMnln.png" /></figure><p><strong>Note</strong>: While Claude models are available by default, some other foundation models in Bedrock may require you to request access. If you plan to use models from other providers, you may need to click <strong>Modify model access</strong> and request access to those specific models.</p><p>At the moment of writing this article, the highly anticipated <strong>Claude Fable 5</strong> model is already available, however it requires data to be shared directly with Anthropic (see below). The highest usable model through Bedrock is currently <strong>Claude Opus 4.8</strong>, which provides excellent performance for most tasks while keeping data within your AWS environment.</p><p><strong>UPDATE</strong>: As of 12 June 2026, Anthropic <strong>Claude Fable 5</strong>* has been suspended by US regulators due to concerns about data privacy and compliance, see <a href="https://www.anthropic.com/news/fable-mythos-access">Statement on the US government directive to suspend access to Fable 5 and Mythos 5</a> for up to date information. The suspension was lifted by the end of June, however, usage is being monitored to comply with export standards.</p><h4>1.3 Configure IAM Permissions</h4><p>Your IAM user or role needs permissions to invoke Bedrock models. If you’re using IAM Identity Center (as covered in our <a href="https://wdoganowski.github.io/cloud-chronicles/02.%20Easier%20access%20to%20your%20accounts%20with%20IAM%20Identity%20Center/">previous article</a>), you’ll need to update your permission set.</p><p><strong>Option A: Create a Custom Permission Set (Recommended)</strong></p><ol><li>Open <strong>IAM Identity Center</strong> in AWS Management Console</li><li>Click <strong>Permission sets</strong> in the left menu</li><li>Click <strong>Create permission set</strong></li><li>Select <strong>Custom permission set</strong></li><li>Click <strong>Create a custom permissions policy</strong></li><li>Add the following policy</li><li>Name the permission set: BedrockUserAccess</li><li>Set session duration (e.g., 12 hours)</li><li>Click <strong>Create</strong></li></ol><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;bedrock:InvokeModel&quot;,<br>        &quot;bedrock:InvokeModelWithResponseStream&quot;,<br>        &quot;bedrock:ListFoundationModels&quot;,<br>        &quot;bedrock:GetFoundationModel&quot;,<br>        &quot;bedrock:ListInferenceProfiles&quot;,<br>        &quot;bedrock:GetInferenceProfile&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;*&quot;<br>    }<br>  ]<br>}</pre><p><strong>Option B: Add Inline Policy to Existing Permission Set</strong></p><p>If you already have a PowerUserAccess or custom permission set:</p><ol><li>Go to <strong>IAM Identity Center</strong> → <strong>Permission sets</strong></li><li>Select your existing permission set</li><li>Click <strong>Edit</strong> → <strong>Inline policy</strong></li><li>Add the Bedrock permissions shown above</li><li>Save the changes</li></ol><h4>1.4 Assign Permission Set to User</h4><p>Once the permission set is created:</p><ol><li>In IAM Identity Center, click <strong>AWS accounts</strong></li><li>Select the account(s) you want to grant access to</li><li>Click <strong>Assign users or groups</strong></li><li>Select your user</li><li>Click <strong>Next</strong></li><li>Select the BedrockUserAccess permission set</li><li>Click <strong>Next</strong> → <strong>Submit</strong></li></ol><p><strong>Important</strong>: If you added permissions to an existing permission set, users will automatically get access. If you created a new permission set, you need to assign it as shown above.</p><h3>Step 2: Configure AWS CLI Profile</h3><p>If you followed our <a href="https://medium.com/aws-tip/easier-access-to-multiple-accounts-with-iam-identity-center-35bc25fdb0c8?sharedUserId=dogan1971">IAM Identity Center article</a>, you should already have AWS CLI configured with SSO. Let’s create or verify a profile with Bedrock access.</p><h4>2.1 Configure SSO Profile</h4><p>Run the AWS SSO configuration wizard:</p><pre>aws configure sso</pre><p>You’ll be prompted for:</p><pre>SSO session name (Recommended): my-sso<br>SSO start URL [None]: https://your-company.awsapps.com/start<br>SSO region [None]: eu-central-1<br>SSO registration scopes [None]: sso:account:access</pre><p>Your browser will open for authentication. Log in with your organizational credentials (e.g., Entra ID).</p><p>After authentication, select:</p><pre>Account: Your Account Name (123456789012)<br>Role: BedrockUserAccess<br>CLI default client Region [None]: eu-north-1<br>CLI default output format [None]: json<br>CLI profile name [BedrockUserAccess-123456789012]: bedrock-access-profile</pre><p>This creates a profile named bedrock-access-profile in ~/.aws/config:</p><pre>[profile bedrock-access-profile]<br>sso_session = my-sso<br>sso_account_id = 123456789012<br>sso_role_name = BedrockUserAccess<br>region = eu-north-1<br>output = json<br><br>[sso-session my-sso]<br>sso_start_url = https://your-company.awsapps.com/start<br>sso_region = eu-central-1<br>sso_registration_scopes = sso:account:access</pre><h4>2.2 Test Bedrock Access</h4><p>Login to AWS SSO:</p><pre>aws sso login --profile bedrock-access-profile</pre><p>Your browser will open again for authentication. After successful login, test Bedrock access:</p><pre># List available Claude models<br>aws bedrock list-foundation-models \<br>  --profile bedrock-access-profile \<br>  --region eu-north-1 \<br>  --query &#39;modelSummaries[?contains(modelId, `anthropic.claude`)].[modelId,modelName]&#39; \<br>  --output table</pre><p>Expected output:</p><pre>--------------------------------------------------------------------<br>|                       ListFoundationModels                       |<br>+--------------------------------------------+---------------------+<br>|  anthropic.claude-sonnet-4-20250514-v1:0   |  Claude Sonnet 4    |<br>|  anthropic.claude-opus-4-8                 |  Claude Opus 4.8    |<br>|  anthropic.claude-opus-4-7                 |  Claude Opus 4.7    |<br>|  anthropic.claude-haiku-4-5-20251001-v1:0  |  Claude Haiku 4.5   |<br>|  anthropic.claude-sonnet-4-5-20250929-v1:0 |  Claude Sonnet 4.5  |<br>|  anthropic.claude-fable-5                  |  Claude Fable 5     |<br>|  anthropic.claude-sonnet-4-6               |  Claude Sonnet 4.6  |<br>|  anthropic.claude-opus-4-5-20251101-v1:0   |  Claude Opus 4.5    |<br>|  anthropic.claude-opus-4-6-v1              |  Claude Opus 4.6    |<br>+--------------------------------------------+---------------------+</pre><h3>Step 3: Understanding Inference Profiles</h3><p>AWS Bedrock uses <strong>inference profiles</strong> to route requests to models. This is important because the model IDs you see in the list above are not what you’ll use in VS Code.</p><h4>What are Inference Profiles?</h4><p>Inference profiles are region-specific endpoints that provide:</p><ul><li><strong>Lower latency</strong>: Requests route to the nearest available model endpoint</li><li><strong>Higher availability</strong>: Automatic failover between availability zones</li><li><strong>Simplified configuration</strong>: Single ID works across model versions</li></ul><h4>Inference Profile IDs vs Model IDs</h4><p>For eu-north-1 (Stockholm), you must use inference profile IDs with the eu. prefix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*oH46GkcT3Dpq3BCMeTi4Cg.png" /></figure><p>You can list available inference profiles:</p><pre>aws bedrock list-inference-profiles \<br>  --profile bedrock-access-profile \<br>  --region eu-north-1 \<br>  --query &#39;inferenceProfileSummaries[?contains(inferenceProfileId, `anthropic`)].[inferenceProfileId,inferenceProfileName]&#39; \<br>  --output table</pre><p><strong>Key point</strong>: Always use the inference profile ID (with region prefix) in your VS Code configuration.</p><h3>Step 4: Configure VS Code for Claude Code</h3><p>Now that Bedrock access is working, let’s configure VS Code to use it.</p><h4>4.1 Install Claude Code Extension</h4><p>If not already installed:</p><ol><li>Open VS Code</li><li>Press ⌘+Shift+X (Mac) or Ctrl+Shift+X (Windows/Linux)</li><li>Search for “Claude Code”</li><li>Look for publisher: Anthropic</li><li>Click <strong>Install</strong></li></ol><h4>4.2 Configure User Settings</h4><p>Open VS Code settings:</p><ol><li>Press ⌘+, (Mac) or Ctrl+, (Windows/Linux)</li><li>Click the {} icon in the top-right to open settings.json</li><li>Add the following configuration:</li></ol><pre>{<br>  &quot;claude.apiProvider&quot;: &quot;bedrock&quot;,<br>  &quot;claude.awsRegion&quot;: &quot;eu-north-1&quot;,<br>  &quot;claude.model&quot;: &quot;eu.anthropic.claude-sonnet-4-6&quot;,<br>  &quot;terminal.integrated.env.osx&quot;: {<br>    &quot;AWS_PROFILE&quot;: &quot;bedrock-access-profile&quot;,<br>    &quot;AWS_REGION&quot;: &quot;eu-north-1&quot;<br>  },<br>  &quot;terminal.integrated.inheritEnv&quot;: true<br>}</pre><p><strong>For Windows users</strong>, replace terminal.integrated.env.osx with:</p><pre>&quot;terminal.integrated.env.windows&quot;: {<br>  &quot;AWS_PROFILE&quot;: &quot;bedrock-access-profile&quot;,<br>  &quot;AWS_REGION&quot;: &quot;eu-north-1&quot;<br>}</pre><p><strong>For Linux users</strong>, use:</p><pre>&quot;terminal.integrated.env.linux&quot;: {<br>  &quot;AWS_PROFILE&quot;: &quot;bedrock-access-profile&quot;,<br>  &quot;AWS_REGION&quot;: &quot;eu-north-1&quot;<br>}</pre><p>Save the file ( ⌘+S or Ctrl+S).</p><h4>4.3 Project-Specific Configuration (Optional)</h4><p>For project-specific settings, create .vscode/settings.json in your project root:</p><pre>{<br>  &quot;claude.model&quot;: &quot;eu.anthropic.claude-opus-4-8&quot;,<br>  &quot;terminal.integrated.env.osx&quot;: {<br>    &quot;AWS_PROFILE&quot;: &quot;bedrock-access-profile&quot;,<br>    &quot;AWS_REGION&quot;: &quot;eu-north-1&quot;<br>  }<br>}</pre><p>This allows you to use different models for different projects (e.g., Opus for complex projects, Sonnet for general work).</p><h4>4.4 Reload VS Code</h4><p>After configuration, reload the VS Code window:</p><ol><li>Press ⌘+Shift+P (Mac) or Ctrl+Shift+P (Windows/Linux)</li><li>Type: Developer: Reload Window</li><li>Press Enter</li></ol><p>Alternatively, press ⌘+R (Mac) or Ctrl+R (Windows/Linux).</p><h3>Step 5: Verify Installation</h3><p>Let’s verify everything is working correctly.</p><h4>5.1 Run the Test Script</h4><p>Download and run the test script (<a href="https://github.com/wdoganowski/cloud-chronicles/tree/main/10.%20Running%20Claude%20Code%20Locally%3A%20AWS%20Bedrock%20Setup%20for%20VS%20Code">included in this article’s repository</a>):</p><pre># Navigate to the article directory<br>cd &quot;path/to/cloud-chronicles/10. AWS Bedrock, Claude Code and VSCode&quot;<br><br># Make script executable<br>chmod +x test-bedrock-connection.sh<br><br># Run test<br>./test-bedrock-connection.sh</pre><p>Expected output:</p><pre>🔍 Testing AWS Bedrock Connection for Claude Code<br>==================================================<br><br>✅ AWS CLI installed<br>ℹ️  Using AWS_PROFILE: bedrock-access-profile<br>ℹ️  Using AWS_REGION: eu-north-1<br><br>🔐 Checking AWS Authentication...<br>✅ Authenticated as:<br>----------------------------------------------------<br>|            GetCallerIdentity                     |<br>+--------------------------------------------------+<br>| UserId     | AROA...@yourcompany.com             |<br>| Account    | 123456789012                         |<br>| Arn        | arn:aws:sts::123456789012:assumed... |<br>----------------------------------------------------<br><br>🤖 Checking Available Claude Models...<br>✅ Available Claude models in eu-north-1:<br>[List of models displayed in table]<br><br>🧪 Testing Bedrock API Call...<br>✅ Can access inference profile: eu.anthropic.claude-sonnet-4-6<br><br>==================================================<br>✅ All tests passed! Claude Code should work in VS Code.</pre><p>If any test fails, refer to the Troubleshooting section below.</p><h4>5.2 Open Claude Code Panel</h4><p>In VS Code:</p><ol><li>Look for the Claude icon in the left sidebar</li><li>Click it to open the Claude Code panel</li><li>Or press ⌘+Shift+P and type: Claude: Focus</li></ol><h4>5.3 Send Test Message</h4><p>In the Claude Code chat interface, type:</p><pre>Hello! Can you confirm you&#39;re running via AWS Bedrock in eu-north-1?</pre><p>If everything is configured correctly, Claude will respond, confirming the connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8n8rYPCiGUvr6Wp4.png" /></figure><h3>Step 6: Daily Workflow</h3><p>Once configured, your daily workflow is simple:</p><h4>Morning Setup</h4><pre># 1. Login to AWS SSO (once per day)<br>aws sso login --profile bedrock-access-profile<br><br># 2. Open VS Code<br>code<br><br># 3. Start using Claude Code!</pre><h4>When Session Expires</h4><p>AWS SSO sessions typically last 8–12 hours. When expired:</p><pre># 1. Re-authenticate<br>aws sso login --profile bedrock-access-profile<br><br># 2. In VS Code: Reload window<br># Press ⌘+R (Mac) or Ctrl+R (Windows/Linux)</pre><h4>Verify Session Status</h4><pre># Check if authenticated<br>aws sts get-caller-identity --profile bedrock-access-profile<br><br># If successful, you&#39;ll see your user details<br># If expired, you&#39;ll get an error</pre><h3>Model Selection Guide</h3><p>Choose the right Claude model for your task:</p><h4>Claude Sonnet 4.6 (Recommended Default)</h4><p><strong>Inference Profile ID</strong>: eu.anthropic.claude-sonnet-4-6</p><p><strong>Best for</strong>: Daily development tasks, code reviews, refactoring, general questions</p><p><strong>Characteristics</strong>:</p><ul><li>Balanced performance and cost</li><li>Fast response times</li><li>Excellent for most coding tasks</li><li>Good context understanding</li></ul><p><strong>Use when</strong>: You need reliable, quick assistance for standard development work</p><h4>Claude Opus 4.8 (Most Capable)</h4><p><strong>Inference Profile ID</strong>: eu.anthropic.claude-opus-4-8</p><p><strong>Best for</strong>: Complex architecture decisions, system design, challenging debugging</p><p><strong>Characteristics</strong>:</p><ul><li>Highest capability</li><li>Deeper reasoning</li><li>Better at complex multi-step tasks</li><li>Higher cost per request</li></ul><p><strong>Use when</strong>: Working on complex problems that require deep analysis or novel solutions</p><h4>Claude Haiku 4.5 (Fast &amp; Economical)</h4><p><strong>Inference Profile ID</strong>: eu.anthropic.claude-haiku-4-5-20251001-v1:0</p><p><strong>Best for</strong>: Quick questions, simple code generation, documentation</p><p><strong>Characteristics</strong>:</p><ul><li>Fastest responses</li><li>Most economical</li><li>Good for straightforward tasks</li><li>Lower context window</li></ul><p><strong>Use when</strong>: You need quick answers or are generating simple code snippets</p><h4>About Fable 5</h4><p><strong>Note</strong>: While Anthropic has released Claude Fable 5 as their latest model, <strong>we do not recommend using it with Bedrock</strong> for this setup. Fable 5 requires <a href="https://aws.amazon.com/blogs/aws/anthropic-claude-fable-5-on-aws-mythos-class-capabilities-with-built-in-safeguards-now-available/">data to be shared directly with Anthropic</a> rather than keeping it within your AWS environment, which defeats one of the primary benefits of using Bedrock:</p><ul><li>❌ <strong>Data leaves AWS</strong>: Requests route to Anthropic’s infrastructure, not AWS Bedrock</li><li>❌ <strong>Different compliance posture</strong>: Data governance and residency guarantees change</li><li>❌ <strong>Separate billing</strong>: Costs appear on Anthropic’s billing, not AWS consolidated billing</li></ul><p><strong>Why use Bedrock instead</strong>: When using Claude Opus 4.8, Sonnet 4.6, or Haiku 4.5 through Bedrock:</p><ul><li>✅ All data stays within your AWS environment and region</li><li>✅ Authentication through AWS SSO (no separate API keys)</li><li>✅ Costs tracked in AWS Cost Explorer alongside other services</li><li>✅ Enterprise compliance and audit requirements met</li></ul><p>For most enterprise and production use cases, <strong>Claude Opus 4.8</strong> via Bedrock provides excellent capability while maintaining data within your AWS infrastructure.</p><h3>Troubleshooting</h3><h4>❌ “Authentication Error” or “Access Denied”</h4><p><strong>Symptoms</strong>: Claude Code shows authentication errors</p><p><strong>Solutions</strong>:</p><ol><li>Check AWS session status:</li></ol><pre>aws sts get-caller-identity --profile bedrock-access-profile</pre><ol><li>If expired, re-login:</li></ol><pre>aws sso login --profile bedrock-access-profileaws sso login --profile bedrock-access-profile</pre><ol><li>Verify environment variables in VS Code terminal:</li></ol><pre>echo $AWS_PROFILE<br>echo $AWS_REGION</pre><ol><li>Reload VS Code window (⌘+R)</li></ol><h4>❌ “Model Not Found” or “Invalid Model ID”</h4><p><strong>Symptoms</strong>: Error about model not being available</p><p><strong>Solutions</strong>:</p><ol><li>Verify you’re using inference profile ID (with eu. prefix):</li></ol><ul><li>✅ Correct: eu.anthropic.claude-sonnet-4-6</li><li>❌ Wrong: anthropic.claude-sonnet-4-6</li></ul><p>2. Check model availability in your region:</p><pre>aws bedrock list-inference-profiles \<br>  --profile bedrock-access-profile \<br>  --region eu-north-1aws bedrock list-inference-profiles \ --profile bedrock-access-profile \ --region eu-north-1</pre><p>3. Update settings.json with correct inference profile ID</p><p>4. Reload VS Code window</p><h4>❌ Environment Variables Not Set in VS Code</h4><p><strong>Symptoms</strong>: Terminal shows empty $AWS_PROFILE</p><p><strong>Solutions</strong>:</p><ol><li>Verify settings in settings.json:</li></ol><ul><li>Check you’re using the correct platform key (osx, windows, or linux)</li><li>Ensure terminal.integrated.inheritEnv is true</li></ul><p>2. Close all terminal windows in VS Code</p><p>3. Fully restart VS Code (not just reload):</p><pre># Quit VS Code<br># Reopen VS Code</pre><p>4. Open a new terminal and verify:</p><pre>echo $AWS_PROFILE<br>echo $AWS_REGION</pre><h4>❌ Bedrock Access Denied</h4><p><strong>Symptoms</strong>: AWS CLI works, but Bedrock calls fail</p><p><strong>Solutions</strong>:</p><ol><li>Verify Bedrock model access was granted:</li></ol><ul><li>AWS Console → Bedrock → Model access</li><li>Check for green “Access granted” status</li></ul><p>2. Verify IAM permissions:</p><pre># Test Bedrock access directly<br>aws bedrock list-foundation-models \<br>  --profile bedrock-access-profile \<br>  --region eu-north-1</pre><p>3. Check permission set includes Bedrock actions:</p><ul><li>bedrock:InvokeModel</li><li>bedrock:ListFoundationModels</li><li>bedrock:ListInferenceProfiles</li></ul><p>4. Contact AWS administrator if permissions are missing</p><h4>❌ “Region Not Supported”</h4><p><strong>Symptoms</strong>: Error about Bedrock not available in region</p><p><strong>Solutions</strong>:</p><ol><li>Verify Bedrock availability:</li></ol><pre>aws bedrock list-foundation-models --region eu-north-1</pre><p>2. Switch to a supported region:</p><ul><li>Update claude.awsRegion in settings.json</li><li>Update AWS_REGION environment variable</li><li>Common regions: us-east-1, us-west-2, eu-west-1, eu-north-1</li></ul><p>3. Check region-specific model availability (not all models in all regions)</p><h3>Advanced Configuration</h3><h4>Multiple Profiles for Different Projects</h4><p>Create project-specific configurations in .vscode/settings.json:</p><p><strong>Production project</strong> (using production AWS account):</p><pre>{<br>  &quot;claude.model&quot;: &quot;eu.anthropic.claude-opus-4-8&quot;,<br>  &quot;terminal.integrated.env.osx&quot;: {<br>    &quot;AWS_PROFILE&quot;: &quot;production-bedrock&quot;,<br>    &quot;AWS_REGION&quot;: &quot;eu-west-1&quot;<br>  }<br>}</pre><p><strong>Development project</strong> (using dev account, cheaper model):</p><pre>{<br>  &quot;claude.model&quot;: &quot;eu.anthropic.claude-haiku-4-5-20251001-v1:0&quot;,<br>  &quot;terminal.integrated.env.osx&quot;: {<br>    &quot;AWS_PROFILE&quot;: &quot;dev-bedrock&quot;,<br>    &quot;AWS_REGION&quot;: &quot;eu-north-1&quot;<br>  }<br>}</pre><h4>Custom Claude Instructions</h4><p>Create a CLAUDE.md file in your project root to give Claude project-specific context:</p><pre># Project: Cloud Chronicles<br><br>This is a technical blog about AWS cloud architecture.<br><br>## Code Style<br>- Use clear, educational examples<br>- Include comments explaining &quot;why&quot;<br>- Prefer AWS CLI over SDK examples<br><br>## Conventions<br>- All examples use `eu-north-1` region<br>- Use IAM Identity Center, not access keys<br>- Reference previous articles when relevant</pre><p>Claude Code automatically reads this file and applies the context to all conversations.</p><h4>Cost Optimization</h4><p>Monitor and optimize Bedrock costs:</p><ol><li><strong>Use appropriate models</strong>:</li></ol><ul><li>Haiku for simple tasks</li><li>Sonnet for general work</li><li>Opus only when necessary</li></ul><p><strong>2. Check costs in AWS Console</strong>:</p><ul><li>Navigate to Cost Explorer</li><li>Filter by service: “Amazon Bedrock”</li><li>Group by: Model ID or Region</li></ul><p><strong>3. Set up billing alerts</strong>:</p><pre># Example: Create CloudWatch alarm for Bedrock costs<br>aws cloudwatch put-metric-alarm \<br>  --alarm-name bedrock-cost-alert \<br>  --alarm-description &quot;Alert when Bedrock costs exceed threshold&quot; \<br>  --metric-name EstimatedCharges \<br>  --namespace AWS/Billing \<br>  --statistic Maximum \<br>  --period 86400 \<br>  --evaluation-periods 1 \<br>  --threshold 100.0 \<br>  --comparison-operator GreaterThanThreshold</pre><h3>Security Best Practices</h3><h4>1. No Credentials to Store</h4><p><strong>This setup requires no AWS credentials files or API keys.</strong> By using AWS SSO, you authenticate through your browser, and the AWS CLI manages temporary session tokens automatically in ~/.aws/sso/cache/. These tokens:</p><ul><li>Are stored locally only during active sessions</li><li>Automatically expire after the configured session duration (typically 8–12 hours)</li><li>Never need to be committed to version control</li><li>Are managed entirely by AWS CLI</li></ul><p><strong>What you should add to </strong><strong>.gitignore</strong> (if applicable to your project):</p><pre># Only if you&#39;re working with other AWS services that generate files<br>*.pem<br>*.key<br><br># VS Code workspace settings (if they contain account-specific info)<br>.vscode/settings.local.json</pre><p><strong>Note</strong>: The ~/.aws/config file only contains profile configurations and SSO URLs - no secrets. The ~/.aws/sso/cache/ directory contains temporary tokens managed by AWS CLI.</p><h4>2. Benefits of SSO-Based Authentication</h4><p>This AWS SSO approach provides several security advantages over traditional API keys:</p><p><strong>Automatic expiry</strong>: Credentials expire after the configured session duration (typically 8–12 hours)</p><p><strong>No long-lived secrets</strong>: No API keys or access keys stored anywhere</p><p><strong>Centralized control</strong>: Access can be revoked instantly from IAM Identity Center</p><p><strong>Audit trail</strong>: All authentication events logged in AWS CloudTrail</p><h4>3. Principle of Least Privilege</h4><p>Grant only necessary Bedrock permissions:</p><pre>{<br>  &quot;Effect&quot;: &quot;Allow&quot;,<br>  &quot;Action&quot;: [<br>    &quot;bedrock:InvokeModel&quot;,<br>    &quot;bedrock:InvokeModelWithResponseStream&quot;<br>  ],<br>  &quot;Resource&quot;: [<br>    &quot;arn:aws:bedrock:eu-north-1::foundation-model/anthropic.claude-*&quot;<br>  ]<br>}</pre><h4>4. Audit Usage</h4><p>Monitor Bedrock usage with CloudTrail:</p><pre># Query recent Bedrock API calls<br>aws cloudtrail lookup-events \<br>  --lookup-attributes AttributeKey=ResourceType,AttributeValue=AWS::Bedrock::Model \<br>  --max-results 10 \<br>  --profile bedrock-access-profile</pre><h4>5. Rotate SSO Sessions</h4><p>Login fresh each day rather than relying on long-lived sessions:</p><pre># Daily routine<br>aws sso logout<br>aws sso login --profile bedrock-access-profile</pre><h3>Cost Considerations</h3><p>Understanding Bedrock pricing helps manage costs effectively.</p><h4>Pricing Model</h4><p>Bedrock charges based on:</p><ul><li><strong>Input tokens</strong>: Text sent to the model</li><li><strong>Output tokens</strong>: Text generated by the model</li></ul><p>Prices vary by model (as of June 2026):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*--W7V8_lleZlBFh-2c9jjA.png" /></figure><p><em>Note: Prices are examples and may vary by region and change over time. Check AWS Bedrock pricing for current rates.</em></p><h4>Typical Usage Scenarios</h4><p><strong>Daily development (Sonnet)</strong>:</p><ul><li>100 requests/day</li><li>~1,000 input tokens/request</li><li>~500 output tokens/request</li><li><strong>Monthly cost</strong>: ~$35</li></ul><p><strong>Heavy usage (Opus)</strong>:</p><ul><li>200 requests/day</li><li>~2,000 input tokens/request</li><li>~1,000 output tokens/request</li><li><strong>Monthly cost</strong>: ~$570</li></ul><p><strong>Light usage (Haiku)</strong>:</p><ul><li>50 requests/day</li><li>~500 input tokens/request</li><li>~250 output tokens/request</li><li><strong>Monthly cost</strong>: ~$1.50</li></ul><h4>Cost Optimization Tips</h4><ol><li><strong>Start conversations fresh</strong>: Long conversations increase token costs</li><li><strong>Use targeted questions</strong>: Be specific to get concise answers</li><li><strong>Choose appropriate models</strong>: Don’t use Opus when Sonnet suffices</li><li><strong>Monitor usage</strong>: Review AWS Cost Explorer regularly</li></ol><h3>Summary</h3><p>You’ve now successfully configured Claude Code to work with AWS Bedrock in VS Code! Here’s what we covered:</p><p>✅ Enabled Bedrock access and requested Claude model access <br>✅ Configured IAM permissions for Bedrock <br>✅ Set up AWS CLI profile with SSO authentication <br>✅ Understood inference profiles vs model IDs <br>✅ Configured VS Code with Claude Code extension <br>✅ Verified installation with test script <br>✅ Learned daily workflow and troubleshooting</p><h3>Key Takeaways</h3><ol><li><strong>Security</strong>: No API keys stored — everything authenticates through AWS SSO</li><li><strong>Flexibility</strong>: Switch models per project using workspace settings</li><li><strong>Integration</strong>: Leverages your existing AWS infrastructure and IAM policies</li><li><strong>Control</strong>: Centralized billing and usage monitoring through AWS Console</li></ol><h3>Next Steps</h3><ul><li>Explore Claude Code features: code generation, refactoring, debugging</li><li>Customize CLAUDE.md files for project-specific context</li><li>Set up billing alerts to monitor costs</li><li>Try different models to find the right balance for your needs</li></ul><h3>Related Articles</h3><ul><li><a href="https://medium.com/aws-tip/easier-access-to-multiple-accounts-with-iam-identity-center-35bc25fdb0c8?sharedUserId=dogan1971">Easier access to multiple accounts with IAM Identity Center</a></li><li><a href="https://medium.com/aws-tip/using-vscode-for-cli-and-python-tasks-on-aws-part-1-8cbcd907eb2?sharedUserId=dogan1971">Using VS Code for CLI and Python tasks on AWS — Part 1</a></li><li><a href="https://medium.com/aws-tip/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a?sharedUserId=dogan1971">Using VS Code for CLI and Python tasks on AWS — Part 2</a></li></ul><p>Happy coding with Claude!</p><p><em>Originally published at </em><a href="https://wdoganowski.github.io/cloud-chronicles/10.%20Running%20Claude%20Code%20Locally:%20AWS%20Bedrock%20Setup%20for%20VS%20Code/"><em>https://wdoganowski.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a2afb33c33" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/running-claude-code-locally-aws-bedrock-setup-for-vs-code-77a2afb33c33">Running Claude Code Locally: AWS Bedrock Setup for VS Code</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Terminal Knows Which AWS Account You’re In (And It Can Save You From Expensive Mistakes)]]></title>
            <link>https://awstip.com/your-terminal-knows-which-aws-account-youre-in-and-it-can-save-you-from-expensive-mistakes-be614d684d1d?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be614d684d1d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 08:07:50 GMT</pubDate>
            <atom:updated>2026-07-14T09:52:25.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4YpmenWgos9SbKY7phzwA.png" /><figcaption>You are looking at their terminal with an AWS-aware prompt</figcaption></figure><p>We’ve all been there. You’re knee-deep in a Terraform plan, confident you’re in UAT, and then you hit apply. Silence. Then the Slack message from your colleague: <em>“Did you just nuke the production database?”</em></p><p>And here’s another scenario that’s becoming increasingly common: you ask GitHub Copilot to run a script for you, it opens a fresh terminal, and suddenly your AWS profile is gone, your virtual environment is deactivated, and Copilot is running commands in the wrong context — or failing silently because `aws` can’t find credentials. Every new terminal Copilot spawns is a blank slate, and if your environment setup lives only in your head (or in a README you have to follow manually), you’ll be fighting that context loss constantly.</p><p>No? Just me? Either way — this article is about making sure that never happens. We’re going to build a shell prompt that constantly reminds you which AWS account and region you’re working in, auto-activates your Python virtual environments, and even switches AWS profiles automatically when you cd into the right project. All of this without slowing your terminal down.</p><p>By the end, your prompt will look like this:</p><pre>~/git/your-repo/environments/uat feat/branch-name* dev@aws-account-uat @eu-north-1<br>.venv ❯</pre><p>But with colors… and that little dev@aws-account-uat @eu-north-1 is your safety net.</p><h3>What We’re Building</h3><p>Here’s the big picture of what happens every time you open a terminal or cd into a directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*3m6W9M7clQWXnNze8vn6Xg.png" /><figcaption>Flowchart showing the AWS-aware prompt architecture</figcaption></figure><p>Three problems, solved in one hook.</p><h3>Prerequisites</h3><ul><li>macOS with <a href="https://brew.sh/">Homebrew</a></li><li><a href="https://www.zsh.org/">zsh</a> as your shell (default on macOS since Catalina)</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI v2</a> installed and configured</li><li>AWS SSO set up (see article in this series <a href="https://medium.com/aws-tip/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a">02. Using VSCode for CLI and Python tasks on AWS — part 2</a> if you haven’t done this yet)</li><li>A coffee ☕️. This is a multi-file setup.</li></ul><h3>Step 1: Pick a Prompt — Meet Pure</h3><p>The foundation of a great terminal experience on zsh is <a href="https://github.com/sindresorhus/pure">Pure</a> — a minimal, fast, and async prompt by Sindre Sorhus. It shows your path, git branch, dirty status, and execution time out of the box. We’ll extend it with AWS awareness.</p><p>The easiest way to get Pure is through <a href="https://github.com/changs/slimzsh">SlimZSH</a>, which bundles it with sane defaults:</p><pre>git clone --recursive https://github.com/changs/slimzsh.git ~/.slimzsh</pre><p>Then add this to the top of your ~/.zshrc:</p><pre>source &quot;$HOME/.slimzsh/slim.zsh&quot;</pre><p>Restart your terminal. You should now have a clean, minimal prompt. This is your canvas.</p><h3>Step 2: Fix VS Code Terminal Integration (Don’t Skip This)</h3><p>If you’re using VS Code’s integrated terminal — and you probably are — there’s a known gotcha. If your prompt makes subprocess calls (like calling aws configure get region on every render), VS Code&#39;s shell integration breaks. Agent-based tools, tasks, and terminal output parsing all start misbehaving.</p><p>The fix is simple: wrap anything that modifies the prompt in a VS Code guard.</p><p>In ~/.zprofile, set your default AWS environment variables at the top:</p><pre>export AWS_PROFILE=Admin@Bootcamp<br>export AWS_REGION=us-east-1<br>export AWS_DEFAULT_REGION=us-east-1</pre><p>Then wrap anything that modifies the prompt (like RPROMPT), in this check:</p><pre>if [[ &quot;$TERM_PROGRAM&quot; != &quot;vscode&quot; ]]; then<br>  setopt PROMPT_SUBST<br>  # ... RPROMPT setup here (for iTerm2/Terminal.app)<br>  export RPROMPT=&#39;$(print_aws_profile)&#39;<br>else<br>  export RPROMPT=&#39;&#39;<br>fi</pre><p>If you are not yet applying prompt customization, you’ll notice your ~/.zshrc already has this pattern for iTerm2 shell integration:</p><pre>if [[ &quot;$TERM_PROGRAM&quot; != &quot;vscode&quot; ]]; then<br>  test -e &quot;${HOME}/.iterm2_shell_integration.zsh&quot; &amp;&amp; source &quot;${HOME}/.iterm2_shell_integration.zsh&quot;<br>fi</pre><p>Same idea. Keep VS Code happy.</p><h3>Step 3: Embed AWS Info Directly in the Pure Prompt</h3><p>Instead of using RPROMPT and similar solutions (which bleed into terminal output and cause the VS Code issues above), we inject AWS info directly into Pure&#39;s first-line prompt — right before the execution time.</p><p>Open ~/.slimzsh/prompt_pure_setup and find the execution time line:</p><pre># Execution time.<br>[[ -n $prompt_pure_cmd_exec_time ]] &amp;&amp; preprompt_parts+=(&#39;%F{$prompt_pure_colors[execution_time]}${prompt_pure_cmd_exec_time}%f&#39;)</pre><p>Add these two lines before it:</p><pre># AWS profile / assumed role (set via $_pure_aws_info in .zshrc).<br>[[ -n $_pure_aws_info ]] &amp;&amp; preprompt_parts+=(&#39;${_pure_aws_info}&#39;)<br><br># Execution time.<br>[[ -n $prompt_pure_cmd_exec_time ]] &amp;&amp; preprompt_parts+=(&#39;%F{$prompt_pure_colors[execution_time]}${prompt_pure_cmd_exec_time}%f&#39;)</pre><p>That’s it for Pure. The $_pure_aws_info variable is a string we&#39;ll manage from .zshrc — no subprocess, no delay.</p><h3>Step 4: The AWS Prompt Hook</h3><p>Now we wire it up. Add this to your ~/.zshrc:</p><pre>function _update_aws_prompt() {<br>  if [[ -n &quot;$ASSUMED_ROLE&quot; ]]; then<br>    # Red for assumed roles — this is important to notice at a glance<br>    _pure_aws_info=&quot;%F{red}${ASSUMED_ROLE}%f&quot;<br>  elif [[ -n &quot;$AWS_PROFILE&quot; ]]; then<br>    local region=&quot;${AWS_DEFAULT_REGION:-$AWS_REGION}&quot;<br>    _pure_aws_info=&quot;%F{blue}${AWS_PROFILE}%f&quot;<br>    [[ -n &quot;$region&quot; ]] &amp;&amp; _pure_aws_info+=&quot; %F{242}@${region}%f&quot;<br>  else<br>    _pure_aws_info=&quot;&quot;<br>  fi<br>}<br>add-zsh-hook precmd _update_aws_prompt<br>_update_aws_prompt  # Set on shell start</pre><p>This runs on every prompt render but reads only environment variables — it never calls aws or any external process. Zero latency.</p><p>The result:</p><ul><li>Normal profile → dev@aws-account-uat @eu-north-1 in blue</li><li>Assumed role → the full role ARN in red (hard to miss)</li><li>No profile → nothing shown</li></ul><h3>Step 5: Auto-activate .venv and Switch AWS Profiles Per Project</h3><p>Here’s where the setup becomes genuinely useful for day-to-day work. Instead of remembering to source .venv/bin/activate and aws-set-profile every time you open a project, let the shell do it.</p><p>The key is a configurable rule table. Each entry maps a path glob to an AWS profile, evaluated from top to bottom — first match wins, so put the most specific rules first:</p><pre># AWS profile rules — most specific patterns first, first match wins.<br># Format: &quot;glob-pattern:aws-profile&quot;<br># A rule matches if $PWD equals the pattern OR is a subdirectory of it.<br># Glob characters (* ? []) are supported.<br>AWS_PROFILE_RULES=(<br>  &quot;*/sf-infra-*/environments/prod:admin@dwh-prod-strict&quot;<br>  &quot;*/sf-infra-*:admin@dwh-prod&quot;<br>  &quot;*/your-repo/environments/prod:dev@aws-account-prod&quot;<br>  &quot;*/your-repo:dev@aws-account-uat&quot;<br>  # &quot;*/git:dev@sandbox&quot;  # fallback for all projects under ~/git<br>)</pre><p>Then add the resolver and the hook:</p><pre>autoload -Uz add-zsh-hook<br><br>function _resolve_aws_profile() {<br>  local dir=&quot;$1&quot;<br>  for rule in &quot;${AWS_PROFILE_RULES[@]}&quot;; do<br>    local pattern=&quot;${rule%%:*}&quot;<br>    local profile=&quot;${rule##*:}&quot;<br>    # ${~pattern} enables glob matching of the variable&#39;s value in [[ ]]<br>    if [[ &quot;$dir&quot; == ${~pattern} || &quot;$dir&quot; == ${~pattern}/* ]]; then<br>      echo &quot;$profile&quot;<br>      return 0<br>    fi<br>  done<br>  return 1  # no match - keep current profile<br>}<br>function _project_env() {<br>  # Auto-activate .venv if one exists in the current directory<br>  local venv=&quot;$PWD/.venv/bin/activate&quot;<br>  if [[ -f &quot;$venv&quot; &amp;&amp; &quot;$VIRTUAL_ENV&quot; != &quot;$PWD/.venv&quot; ]]; then<br>    export VIRTUAL_ENV_DISABLE_PROMPT=12  # Pure handles the venv display<br>    source &quot;$venv&quot;<br>    echo &quot;Activated .venv: $PWD/.venv&quot;<br>  fi<br>  # Auto-set AWS profile based on AWS_PROFILE_RULES<br>  local matched_profile<br>  matched_profile=$(_resolve_aws_profile &quot;$PWD&quot;)<br>  if [[ -n &quot;$matched_profile&quot; &amp;&amp; &quot;$AWS_PROFILE&quot; != &quot;$matched_profile&quot; ]]; then<br>    export AWS_PROFILE=&quot;$matched_profile&quot;<br>    export AWS_REGION=$(aws configure get region 2&gt;/dev/null)<br>    export AWS_DEFAULT_REGION=&quot;$AWS_REGION&quot;<br>    echo &quot;AWS profile set to $AWS_PROFILE @ $AWS_REGION&quot;<br>    # SSO check only when the profile actually switches<br>    if ! aws sts get-caller-identity &amp;&gt;/dev/null; then<br>      echo &quot;SSO session expired, logging in...&quot;<br>      aws sso login<br>    fi<br>  fi<br>}<br>add-zsh-hook chpwd _project_env<br>_project_env  # Run on shell start</pre><p>The chpwd hook fires every time you change the directory. Combined with _project_env running at shell start, your environment is always consistent with your current project. The SSO check only runs when the profile actually changes — not on every cd — so there&#39;s no latency hit.</p><p>A note on VIRTUAL_ENV_DISABLE_PROMPT=12 — without this, activating a venv would add (.venv) to your PS1, and Pure would <em>also</em> show .venv in the prompt, giving you a redundant double label. Setting this magic number tells the activate script to stand down and let Pure handle it.</p><p>How the rule matching works: zsh’s [[ string == $pattern ]] performs glob matching when the right-hand side is unquoted. The ${~pattern} syntax forces this glob interpretation even when the value comes from a variable. So */sf-infra-* correctly matches /Users/wojtek/git/tv3/sf-infra-core and everything inside it, while */sf-infra-*/environments/prod takes precedence because it&#39;s listed first.</p><h3>Step 6: The AWS Helper Functions</h3><p>Put these in ~/.zprofile so they&#39;re available in all shells. They wrap the AWS CLI commands you use most when working across multiple accounts.</p><h3>Switch Profile and Log In</h3><pre>function aws-set-profile() {<br>  export AWS_PROFILE=$1<br>  export AWS_REGION=$(aws configure get region)<br>  export AWS_DEFAULT_REGION=$AWS_REGION<br>  echo &quot;Switching profile to ${AWS_PROFILE} @ ${AWS_REGION}&quot;<br>  aws sso login<br>}</pre><p>Usage: aws-set-profile admin@dwh-prod</p><p>This switches your profile, picks up the configured region, and triggers SSO login. Use this when you need to manually switch between accounts.</p><h3>Assume a Role</h3><pre>function aws-assume-role() {<br>  OUT=$(aws sts assume-role --role-arn $1 --role-session-name $2)<br>  export AWS_ACCESS_KEY_ID=$(echo $OUT | jq -r &#39;.Credentials.AccessKeyId&#39;)<br>  export AWS_SECRET_ACCESS_KEY=$(echo $OUT | jq -r &#39;.Credentials.SecretAccessKey&#39;)<br>  export AWS_SESSION_TOKEN=$(echo $OUT | jq -r &#39;.Credentials.SessionToken&#39;)<br>  export ASSUMED_ROLE=$1<br>  aws sts get-caller-identity<br>}</pre><p>Usage: aws-assume-role arn:aws:iam::123456789012:role/MyRole my-session</p><p>When ASSUMED_ROLE is set, your prompt turns red. This is intentional — assumed roles often have elevated permissions, and you want a constant visual reminder.</p><h3>Return to Base Profile</h3><pre>function aws-return-role() {<br>  unset ASSUMED_ROLE AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN<br>  aws sts get-caller-identity<br>}</pre><p>Usage: aws-return-role</p><p>Clears the assumed role credentials and drops back to your base profile. Your prompt goes back to blue.</p><h3>Putting It All Together</h3><p>Here’s how the pieces fit across your shell config files:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*JBrt-6C8DQHy6CW7C1wuZA.png" /><figcaption>The flowchart showing the interaction between .zprofile, .zshrc, and Pure</figcaption></figure><p>The flow: .zprofile sets defaults and tools → .zshrc reacts to directory changes and updates _pure_aws_info → Pure renders it in the prompt.</p><h3>The Final Result</h3><p>Open a new terminal in any sf-infra-* project directory:</p><pre>~/git/tv3/sf-infra-core/environments/uat feat/svc_nexus_api_user* admin@dwh-prod @eu-north-1 3s<br>.venv ❯</pre><p>Open one in snowflake-scripts:</p><pre>~/git/tv3/snowflake-scripts master Admin@Bootcamp @us-east-1<br>.venv ❯</pre><p>Assume a role:</p><pre>~/git/tv3/sf-infra-core master arn:aws:iam::123456789012:role/MyRole<br>.venv ❯</pre><p>The assumed role will be displayed in red. This red profile name is your “wait, double-check before you apply” moment. It’s saved more than a few Friday afternoons.</p><h3><strong>Bonus: It Plays Well With GitHub Copilot</strong></h3><p>If you use GitHub Copilot in VS Code — especially the agent mode — you’ve probably noticed that Copilot frequently opens a <em>new</em> terminal to run its commands. And every time it does, it starts completely fresh: no AWS profile, no region, and your Python virtual environment is nowhere to be seen.</p><p>This is actually where this setup earns its keep beyond just aesthetics. Because both .zprofile and .zshrc run on every new shell, Copilot&#39;s terminal inherits everything automatically: the right AWS_PROFILE, the correct AWS_REGION, and if the project has a .venv, it gets activated immediately. The _project_env function fires on shell start (not just on cd), so even a brand-new terminal spawned mid-session lands in the right context. Copilot can run aws commands and Python scripts without you needing to manually set up the environment each time it decides to open a fresh shell.</p><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*ipYodrIhpHUGbXkx_iJqsQ.png" /><figcaption>Summary of the solution in one table</figcaption></figure><p>The whole setup is about 50 lines of shell script spread across three files. In return, you get a terminal that knows where it is and tells you about it — loudly, in colour, every single time.</p><p>Stay safe out there. And always check the prompt before you terraform apply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be614d684d1d" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/your-terminal-knows-which-aws-account-youre-in-and-it-can-save-you-from-expensive-mistakes-be614d684d1d">Your Terminal Knows Which AWS Account You’re In (And It Can Save You From Expensive Mistakes)</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Invoice Forwarding from Gmail with Google Apps Script]]></title>
            <link>https://medium.com/@dogan1971/automating-invoice-forwarding-from-gmail-with-google-apps-script-99860638ffdd?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/99860638ffdd</guid>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[accounting-software]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[bookkeeping]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 10:30:14 GMT</pubDate>
            <atom:updated>2025-11-10T10:30:14.138Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I bypassed Gmail’s forwarding restrictions and built a simple, self-running workflow.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XJ_b4-rBUsPxnpRO7xFow.png" /></figure><p>If you use a financial or accounting platform that accepts invoices via email, you’ve probably run into Gmail’s frustrating forwarding restriction. Gmail requires a verification step for every forwarding address, which is impossible when your destination inbox is automated or unattended (for example, QuickBooks or any other bookkeeping portal).</p><p>That was exactly my situation. My accounting platform processes invoices sent to a <a href="/service/mailto:doganowski.wojciech@inbox.portalbiura.pl">p</a>redefined email address, but Gmail refused to automatically forward messages there because the address couldn’t confirm the forwarding request.</p><p>The workaround? A simple yet powerful Google Apps Script that automatically forwards any emails tagged as “new_invoice” to the accounting system — and then replaces the label with “sent_invoice” to prevent duplicates. Combined with a Gmail filter that labels incoming invoices, this solution is completely automatic, secure, and runs in the background using Google’s own infrastructure.</p><p>Gmail’s forwarding confirmation process makes sense from a security standpoint — it prevents unauthorized forwarding of private emails.<br>But in the case of automated invoice collection systems, there’s no way to click the confirmation link because those inboxes are not monitored by humans.</p><p>This makes the “Forward to accounting” use case surprisingly difficult — unless you build your own workflow.</p><h4>The Solution</h4><p>The goal was simple:<br> 1. Automatically detect invoices arriving in Gmail<br> 2. Forward them to the bookkeeping system<br> 3. Prevent duplicates by tracking what’s already sent</p><p>To achieve this, I combined three Google tools:<br> • Gmail labels and filters to mark new invoices<br> • Google Apps Script to forward and relabel them<br> • Time-based triggers to make it run automatically</p><p>Everything runs inside Google’s ecosystem — no external integrations or APIs required.</p><p>If you would like to use this solution, here is the step-by-step instruction.</p><h4>Step 1: Create Gmail Labels</h4><p>In Gmail:<br> 1. Create a label called <em>new_invoice</em><br> 2. Create another label called <em>sent_invoice</em></p><p>These will mark which messages are waiting to be forwarded and which ones are already processed.</p><h4>Step 2: Create a Gmail Filter</h4><p>Go to:<br>Settings ⚙️ → See all settings → Filters and Blocked Addresses → Create a new filter</p><p>You can filter invoices by:<br> • Has the words: invoice<br> • or From: invoice@</p><p>Then click Create filter, and under “Apply the label” select <em>new_invoice</em>.</p><p>Now Gmail will automatically tag new invoice messages with <em>new_invoice</em>.</p><h4>Step 3: Add the Apps Script</h4><p>1. Go to <a href="http://script.google.com/">script.google.com</a><br> 2. Click New Project<br> 3. Paste this code:</p><pre>function forwardInvoices() {<br>  const forwardTo = &quot;doganowski.wojciech@inbox.portalbiura.pl&quot;;<br><br>  // Ensure labels exist<br>  let sourceLabel = GmailApp.getUserLabelByName(&quot;new_invoice&quot;);<br>  if (!sourceLabel) sourceLabel = GmailApp.createLabel(&quot;new_invoice&quot;);<br><br>  let sentLabel = GmailApp.getUserLabelByName(&quot;sent_invoice&quot;);<br>  if (!sentLabel) sentLabel = GmailApp.createLabel(&quot;sent_invoice&quot;);<br><br>  const threads = sourceLabel.getThreads();<br><br>  for (let i = 0; i &lt; threads.length; i++) {<br>    const thread = threads[i];<br>    const messages = thread.getMessages();<br><br>    for (let j = 0; j &lt; messages.length; j++) {<br>      const message = messages[j];<br>      try {<br>        message.forward(forwardTo, {<br>          subject: &quot;FWD: &quot; + message.getSubject(),<br>          body: &quot;Automatically forwarded invoice:\n\n&quot; + message.getBody(),<br>        });<br>      } catch (err) {<br>        Logger.log(&quot;Error forwarding message: &quot; + err);<br>      }<br>    }<br><br>    thread.removeLabel(sourceLabel);<br>    thread.addLabel(sentLabel);<br>  }<br>}</pre><p>Then click <strong>Run ▶</strong> and authorize the script when prompted.</p><p>After the first run, check that messages labeled new_invoice are forwarded correctly and relabeled as sent_invoice.</p><h4>Step 4: Automate with a Trigger</h4><p>You don’t need to deploy anything — just set a trigger:<br> 1. Click the clock icon 🕒 in the left sidebar (Triggers)<br> 2. Add a new trigger:<br> • Function: forwardInvoices<br> • Event source: Time-driven<br> • Type: every 15 minutes (or hourly)<br> 3. Save and grant permission</p><p>Function: forwardInvoices<br> • Event source: Time-driven<br> • Type: every 15 minutes (or hourly)<br> 3. Save and grant permission</p><p>Now Google will automatically run your script on schedule — even if your computer is off.</p><p>⸻</p><p>Optional Enhancements<br> • Add a daily summary email:</p><pre>MailApp.sendEmail(&quot;your@email.com&quot;, &quot;Invoice Forwarding Summary&quot;,<br>  &quot;Forwarded &quot; + count + &quot; invoices today.&quot;);</pre><p>• Add error notifications if forwarding fails<br> • Automatically archive processed threads to keep your inbox clean</p><h4>Summary</h4><p>With just a few lines of Google Apps Script and one Gmail filter, you can fully automate invoice forwarding — no third-party extensions or risky forwarding rules required.</p><p>Here’s what the setup does:<br> • A Gmail filter tags new invoices with new_invoice<br> • The Apps Script scans for that label, forwards each email (with attachments) to your accounting inbox<br> • After successful forwarding, it changes the label to sent_invoice<br> • A time-based trigger keeps it running automatically in the background</p><p>It’s a clean, Google-native solution that bypasses Gmail’s forwarding limitations while giving you full control and transparency.</p><p>If your business tools require unattended email addresses, this lightweight automation can save you hours of manual forwarding — and ensure your invoices always reach their destination on time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99860638ffdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transforming Call Center Analytics with AWS Bedrock]]></title>
            <link>https://awstip.com/transforming-call-center-analytics-with-aws-bedrock-fd08d498e16f?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd08d498e16f</guid>
            <category><![CDATA[call-center]]></category>
            <category><![CDATA[transcript]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[bedrock]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 18:07:05 GMT</pubDate>
            <atom:updated>2024-06-15T18:07:05.764Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0h03kvMT3ex6WXCkxgesUw.jpeg" /><figcaption>Generated by DALL-E 3 and enhanced with Adobe Photoshop</figcaption></figure><h4>Introduction</h4><p>Analyzing and improving call scripts is crucial for enhancing sales conversions in the dynamic and customer-centric world of call centers. The Go3 OTT video service, which operates across the Baltic countries of Lithuania, Latvia, and Estonia, faced a not-unique challenge: their call center needed to review calls made in multiple languages to provide consistent and effective guidelines to their agents. To address this, an AWS-based application was developed leveraging AWS Bedrock to analyze and translate call transcripts, ensuring that the Go3 call center can maintain high-quality interactions and boost sales performance.</p><h3>Problem Statement</h3><p>The Go3 call center handles various customer inquiries across different languages. The call center manager required a solution to analyze real-time calls, translate the transcripts, and provide actionable insights to improve call scripts. The primary challenges included:</p><ul><li>Multilingual support for call transcription and translation.</li><li>Accurate analysis of call content to derive meaningful insights.</li><li>Seamless integration with existing call center operations.</li></ul><p>The goal was to create an application that could automate the transcription and translation process, enabling the manager to review calls and refine the call scripts to enhance sales conversion rates.</p><h3>Solution Approach</h3><p>We leveraged several AWS services, including AWS Bedrock, to tackle these challenges to build a robust solution. The key components of the application included:</p><ul><li><strong>Amazon S3</strong>: This is for storing the call audio files and transcripts.</li><li><strong>AWS Lambda</strong>: For orchestrating the process.</li><li><strong>Amazon Transcribe</strong>: This is used to create the transcription of the call recordings.</li><li><strong>Amazon Bedrock</strong>: To analyze and translate the transcribed text.</li><li><strong>Simple Notification Service</strong>: To send out the call analysis.</li></ul><p>This combination of services allowed us to create a scalable and efficient system capable of handling the Go3 call center’s requirements.</p><h3>Application Architecture</h3><p>The solution&#39;s architecture is designed to be modular and scalable, leveraging AWS services to their full potential. Here’s a high-level overview of the architecture:</p><ol><li><strong>Audio Storage</strong>: Call audio files are stored in an S3 bucket in recordings directory.</li><li><strong>Transcription</strong>: When a new audio file is uploaded, an S3 event triggers a Lambda function that initiates the transcription process, which result is stored in an S3 bucket in transcribed directory.</li><li><strong>Translation and Analysis</strong>: When the transcribed text is uploaded, the S3 event triggers Lambda again, which initiates the AWS Bedrock to convert it into the desired language and analyze the content. The result is saved on S3 in output directory.</li><li><strong>Sendout of Result</strong>: When the results are uploaded, again the S3 event triggers the Lambda, which sends out the result to the SNS topic.</li><li><strong>Review</strong>: The translated transcript and analysis results are emailed for review.</li></ol><p>The architecture of the solution is presented on the below diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8CzP-OlYLb2Vl7qXH9IIQ.png" /><figcaption>Simplified architecture diagram of the Call Center Analyzer application</figcaption></figure><p>Note that there are potentially two possible solutions: using a bucket for all the operations or one bucket per operation. The first solution makes it cleaner regarding the S3 resources (only a single bucket is created for the application). However, due to the limitations of the S3 events, it can work only with one Lambda function, which has to perform all the tasks depending on the directory in which the file is created.</p><p>Another solution would be to use several buckets and separate Lambda for each operation. This would be cleaner from the Lambda code standpoint, but as this is hidden from the user, I have decided to use a single-bucket approach.</p><p>In the above diagram, there are three instances of the bucket and lambda; however, they are all implemented as one bucket with several directories and one Lambda with the handler dispatching the requests.</p><h3>Example of Result</h3><p>Here is an example of the email containing the result of the process:</p><pre>1. Sentiment and Quality Analysis:</pre><pre>The conversation seems to be a call from a customer service agent trying to assist a customer who had registered on the Go3 platform but did not complete the process fully. The agent is polite and professional, informing the customer about call recording and trying to understand the issue. However, the customer appears uninterested and dismissive, providing short responses indicating they do not need any assistance. The customer sentiment seems neutral to slightly negative, while the agent maintains a positive and helpful tone throughout the interaction.</pre><pre>2. Speaker Analysis:</pre><pre>Based on the conversation, it appears that spk_1 is the agent from Go3, and spk_0 is the customer who registered on the platform.</pre><pre>3. Translated Conversation:</pre><pre>0.93    Customer: Hello<br>1.98    Agent: Hello, greetings? This is Nore calling from Go3 regarding your registration on our Go3 platform. Please let me know if you have a moment to talk.<br>15.479  Customer: Not right now.<br>17.059  Agent: Hmm, when would be a better time for you to talk?<br>21.42   Customer: What is this conversation about?<br>23.42   Agent: Yes, before we continue the conversation, I want to inform you that this call will be recorded, okay?<br>31.62   Customer: Hmm.<br>33.279  Agent: Yes, I&#39;m calling you because I see that you had completed this Go3 registration, but you didn&#39;t fully complete it. So I&#39;m calling to see how I can assist you.<br>47.83   Customer: I don&#39;t need any assistance.<br>50.169  Agent: Yes, were you able to complete the registration? Did you manage to do everything?<br>56.54   Customer: Yes, everything is done.<br>58.259  Agent: Hmm.</pre><pre>4. Original Call Transcribe</pre><pre>0.93    spk_0   hallo<br>1.98    spk_1   hallo sveicināti? teams zvana Nore no Gtries par jūsu veikto reģistrāciju mūsu Gtris platformā, sakiet, vai būs mirklis sarunai.<br>15.479  spk_0   ne šobrīd<br>17.059  spk_1   mhm, kurā laikā jums būtu arāk runāt?<br>21.42   spk_0   par ko es sarunu?<br>23.42   spk_1   jā es pirms mēs turpinām sarunu, es vēlos painformēt, ka mums zvans tiks ierakstīts, labi?<br>31.62   spk_0   mhm.<br>33.279  spk_1   jā, zvanīju jums jo redzu, ka bijāt veicis šo te go tris reģistrāciju, bet kaut ko nebijāt līdz galam norādījis, tad es zvanīju, lai zinātu kā man jums palīdzēt.<br>47.83   spk_0   nevajag nekā palīdzēt.<br>50.169  spk_1   jā, jums viss sanāca veicāt reģistrāciju? izdevās visu izdarīt?<br>56.54   spk_0   jā, viss sanāk,<br>58.259  spk_1   mhm</pre><h3>Code Explanation</h3><h3>Handler</h3><p>The core logic of the application is implemented in the handler.py file, which contains the Lambda handler function. Below are the key components and functionalities:</p><pre>import boto3<br>from botocore.config import Config<br>import os<br>import uuid<br>import logging<br>import json<br>import time<br><br>import instructions<br># Initiate the logging module<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br># Define the directories<br>TRANSCRIBE_DIR = &#39;recordings/&#39;<br>TRANSCRIBE_EXT = &#39;.mp3&#39;<br>ANALYZE_DIR = &#39;transcripts/&#39;<br>ANALYZE_EXT = &#39;.json&#39;<br>OUTPUT_DIR = &#39;output/&#39;<br>OUTPUT_EXT = &#39;.txt&#39;<br>handled_event_names = [&#39;ObjectCreated:Copy&#39;, &#39;ObjectCreated:Put&#39;]<br>&quot;&quot;&quot;<br>Transcribe an audio file stored in an S3 bucket using Amazon Transcribe.<br>&quot;&quot;&quot;<br>def transcribe(input_s3_bucket: str, input_s3_key: str) -&gt; dict:<br>    ...<br>&quot;&quot;&quot;<br>Analyze a transcript file stored in an S3 bucket using Amazon Bedrock.<br>&quot;&quot;&quot;<br>def analyze(input_s3_bucket: str, input_s3_key: str) -&gt; dict:<br>    ...<br>&quot;&quot;&quot;<br>Send a notification message to an Amazon SNS topic.<br>&quot;&quot;&quot;<br>def send_notification(subject: str, message: str) -&gt; dict:<br>    ...<br>&quot;&quot;&quot;<br>Notify about a file processed by the Call Center Analyzer.<br>&quot;&quot;&quot;<br>def notify(input_s3_bucket: str, input_s3_key: str) -&gt; dict:<br>    ...<br>&quot;&quot;&quot;<br>AWS Lambda function to handle S3 object creation events.<br>&quot;&quot;&quot;<br>def handler(event, context):<br>    # Retrieve the S3 bucket and object information from the event<br>    try:<br>        event_name = event[&#39;Records&#39;][0][&#39;eventName&#39;]<br>        input_s3_bucket = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;bucket&#39;][&#39;name&#39;]<br>        input_s3_key = event[&#39;Records&#39;][0][&#39;s3&#39;][&#39;object&#39;][&#39;key&#39;]<br>    except KeyError:<br>        logger.warning(f&quot;Invalid event data {event}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: &#39;Invalid event data&#39;<br>        }<br>    logger.debug(event)<br>    # Process the file based on the directory<br>    if event_name in handled_event_names:<br>        if input_s3_key.startswith(TRANSCRIBE_DIR):<br>            response = transcribe(input_s3_bucket, input_s3_key)<br>        elif input_s3_key.startswith(ANALYZE_DIR):<br>            response = analyze(input_s3_bucket, input_s3_key)<br>        elif input_s3_key.startswith(OUTPUT_DIR):<br>            response = notify(input_s3_bucket, input_s3_key)<br>        else:<br>            logger.warning(<br>                f&quot;Invalid file path: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br>            return {<br>                &#39;statusCode&#39;: 400,<br>                &#39;body&#39;: &#39;Invalid file path&#39;<br>            }<br>    else:<br>        logger.info(f&quot;This is {event_name} and is not ObjectCreated:Put event&quot;)<br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: &#39;Skipped&#39;<br>        }<br>    if response[&#39;statusCode&#39;] != 200:<br>        send_notification(f&quot;Error processing file: s3://{input_s3_bucket}/{input_s3_key}&quot;, f&quot;status code {response[&#39;statusCode&#39;]}/n{response[&#39;body&#39;]}&quot;)<br>        return response<br>        <br>    return response</pre><p>This function is the main entry point for the AWS Lambda function that processes files uploaded to an S3 bucket. S3 object creation events trigger it and performs the following steps:</p><ol><li>Retrieves the S3 bucket name and object key from the event data.</li><li>Determines the type of file based on the object key and calls the appropriate processing function (transcribe, analyze, or notify).</li><li>If the file is successfully processed, the function returns the response from the processing function.</li><li>If there is an error during the processing, the function sends a notification to an SNS topic and returns the error response.</li></ol><p>The function supports the following file types:</p><ul><li>.mp3 files: Transcribed using Amazon Transcribe</li><li>.json files: Analyzed using Amazon Bedrock</li><li>.txt files: Notifications are sent for these files</li></ul><p>If the event is not an ObjectCreated:Put event or the file type is not supported, the function skips the processing and returns a success response.</p><p>Following is the explanation of each processing function.</p><h3>Transcribe</h3><p>Transcribe an audio file stored in an S3 bucket using Amazon Transcribe.</p><pre>def transcribe(input_s3_bucket: str, input_s3_key: str) -&gt; dict:        <br>    # Verify if it is an mp3 file<br>    if not input_s3_key.endswith(TRANSCRIBE_EXT):<br>        logger.warning(<br>            f&quot;Invalid file type: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: &#39;Invalid file type&#39;<br>        }<br>    logger.info(f&quot;Transcribing file: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br><br>    # Generate a unique job name and output file name<br>    job_name = str(uuid.uuid4())<br>    output_s3_bucket = input_s3_bucket  # Use the same S3 bucket for output<br>    output_s3_key = input_s3_key.replace(<br>        TRANSCRIBE_DIR, ANALYZE_DIR, 1).replace(TRANSCRIBE_EXT, ANALYZE_EXT)<br>    logger.info(f&quot;Job name: {job_name}&quot;)<br>    logger.info(f&quot;Output file name: s3://{output_s3_bucket}/{output_s3_key}&quot;)<br>    # Create an Amazon Transcribe client<br>    try:<br>        transcribe_client = boto3.client(&#39;transcribe&#39;)<br>    except Exception as e:<br>        logger.error(f&quot;Error creating Amazon Transcribe client: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error creating Amazon Transcribe client: {e}&#39;<br>        }<br>    # Set the S3 URI for the input audio file<br>    s3_uri = f&quot;s3://{input_s3_bucket}/{input_s3_key}&quot;<br>    # Start the transcription job<br>    try:<br>        response = transcribe_client.start_transcription_job(<br>            TranscriptionJobName=job_name,<br>            IdentifyLanguage=True,  # Auto detect the language<br>            # Specify the languages you expect to be present<br>            LanguageOptions=[&#39;en-US&#39;, &#39;lt-LT&#39;, &#39;lv-LV&#39;, &#39;et-ET&#39;, &#39;ru-RU&#39;],<br>            MediaFormat=&#39;mp3&#39;,<br>            Media={<br>                &#39;MediaFileUri&#39;: s3_uri<br>            },<br>            OutputBucketName=output_s3_bucket,<br>            OutputKey=output_s3_key,<br>            Settings={<br>                &#39;ShowSpeakerLabels&#39;: True,  # Enable speaker identification<br>                &#39;MaxSpeakerLabels&#39;: 4,  # Specify the maximum number of speakers to identify<br>                &#39;ShowAlternatives&#39;: True,  # Enable alternative transcriptions<br>                &#39;MaxAlternatives&#39;: 2  # Generate 2 alternative transcriptions<br>            }<br>        )<br>    except Exception as e:<br>        logger.error(f&quot;Error starting transcription job: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error starting transcription job: {e}&#39;<br>        }<br>    logger.info(f&quot;Transcription job started with name: {job_name}&quot;)<br>    logger.debug(response)<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: &#39;OK&#39;<br>    }</pre><p>This function takes an S3 bucket name and an S3 key (file path) as input and initiates an Amazon Transcribe job to transcribe the audio file. The function generates a unique job name, sets the output file name and location, and configures the Transcribe job with the appropriate settings.</p><p>The function returns an error response if the input file is not an MP3 file. If any errors are creating the Transcribe client or starting the transcription job, the function returns an error response.</p><p>Upon successfully initiating the transcription job, the function returns a successful response.</p><h3>Analyze</h3><p>Analyze a transcript file stored in an S3 bucket using Amazon Bedrock. It also uses a subfunction to format the content of a transcription result from Amazon Transcribe.</p><pre>def format_content(data: dict) -&gt; str:<br>    lines = []<br>    line = &#39;&#39;<br>    speaker = &#39;spk_1&#39;<br>    most_recent_speaker = &#39;spk_1&#39;<br>    # Loop through the speakers and add them to the transcription.<br>    try:<br>        items = data[&#39;results&#39;][&#39;items&#39;]<br>        <br>        for item in items:<br>            if item.get(&#39;start_time&#39;):  # This is a spoken item<br>                speaker = item[&#39;speaker_label&#39;]<br><br>                if speaker == most_recent_speaker:<br>                    # Append the content to line and repeat<br>                    line+=f&quot; {item[&#39;alternatives&#39;][0][&#39;content&#39;]}&quot;<br>                else:<br>                    # New speaker<br>                    lines.append(f&#39;{line}\n\n&#39;)<br>                    most_recent_speaker = speaker<br>                    line=f&quot;{item[&#39;start_time&#39;]}\t{speaker}\t{item[&#39;alternatives&#39;][0][&#39;content&#39;]}&quot;<br>            elif item[&#39;type&#39;] == &#39;punctuation&#39;:<br>                line+=item[&#39;alternatives&#39;][0][&#39;content&#39;]<br>        lines.append(line)<br>            <br>    except Exception as e:<br>        logger.error(f&quot;Error parsing result items: {e}&quot;)<br>        return &quot;&quot;<br>    speaker_formatted_content = &#39;&#39;<br>    for line in lines:<br>        speaker_formatted_content+=line<br>        <br>    return speaker_formatted_content</pre><pre>def analyze(input_s3_bucket: str, input_s3_key: str) -&gt; dict:<br>    # Verify if it is an json file<br>    if not input_s3_key.endswith(ANALYZE_EXT):<br>        logger.warning(<br>            f&quot;Invalid file type: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: &#39;Invalid file type&#39;<br>        }<br>    logger.info(f&quot;Analyzing file: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br>    # Generate a unique job name and output file name<br>    output_s3_bucket = input_s3_bucket  # Use the same S3 bucket for output<br>    output_s3_key = input_s3_key.replace(<br>        ANALYZE_DIR, OUTPUT_DIR, 1).replace(ANALYZE_EXT, OUTPUT_EXT)<br>    logger.info(f&quot;Output file name: s3://{output_s3_bucket}/{output_s3_key}&quot;)<br>    # Read the input json file from s3<br>    try:<br>        s3 = boto3.resource(&#39;s3&#39;)<br>    except Exception as e:<br>        logger.error(f&quot;Error creating Amazon S3 client: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error creating Amazon S3 client: {e}&#39;<br>        }<br>    try:<br>        obj = s3.Object(input_s3_bucket, input_s3_key)<br>    except Exception as e:<br>        logger.error(f&quot;Error reading input file: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error reading input file: {e}&#39;<br>        }<br>    try:<br>        json_data = obj.get()[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>        json_data = json.loads(json_data)<br>    except Exception as e:<br>        logger.error(f&quot;Error decoding input file: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error decoding input file: {e}&#39;<br>        }<br>            <br>    # Get the language of the transcript<br>    try:<br>        language_code = json_data[&#39;results&#39;][&#39;language_code&#39;]<br>    except KeyError:<br>        logger.error(&quot;Error getting language code&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: &#39;Internal server error: Error getting language code&#39;<br>        }<br>    logger.info(f&quot;Input data is in language {language_code}&quot;)<br>    <br>    # Get the transcript from the Amazon Transcribe job<br>    speaker_formatted_content = format_content(json_data)<br>    if speaker_formatted_content == &quot;&quot;:<br>        logger.error(&quot;Error formatting content&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: &#39;Internal server error: Error formatting content&#39;<br>        }<br>    logger.info(f&quot;Formatted content: {speaker_formatted_content}&quot;)<br>    # Create an Amazon Bedrock client<br>    try:<br>        config = Config( # https://github.com/boto/boto3/issues/2424<br>            read_timeout=900,<br>            connect_timeout=900,<br>            retries={&quot;max_attempts&quot;: 0}<br>        )<br>        bedrock_client = boto3.client(&#39;bedrock-runtime&#39;, config=config)<br>        logger.info(&quot;Amazon Bedrock client created&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;Error creating Amazon Bedrock client: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error creating Amazon Bedrock client: {e}&#39;<br>        }<br>    <br>    # Use the provided instructions to provide the summary. Use a default if no intructions are provided.<br>    SUMMARY_INSTRUCTIONS = os.getenv(&#39;SUMMARY_INSTRUCTIONS&#39;,instructions.get_instructions(language_code))<br>    logger.info(f&quot;SUMMARY_INSTRUCTIONS: {SUMMARY_INSTRUCTIONS}&quot;)<br>    <br>    # Use the provided model ID to invoke the model.<br>    try:<br>        BEDROCK_MODEL_ID = os.getenv(&#39;BEDROCK_MODEL_ID&#39;, &#39;anthropic.claude-3-sonnet-20240229-v1:0&#39;)<br>    except KeyError:<br>        logger.error(&quot;Error getting BEDROCK_MODEL_ID&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: &#39;Internal server error: Error getting BEDROCK_MODEL_ID&#39;<br>        }<br>    logger.info(f&quot;BEDROCK_MODEL_ID: {BEDROCK_MODEL_ID}&quot;)<br>    # Launch the bedrock to analyze the json_data to detect who is the agent and who is the customer, the customer sentiment and the agent quality<br>    try:<br>        # Create the payload to provide to the Anthropic model.<br>        messages = [{ &quot;role&quot;:&quot;user&quot;, &quot;content&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;: SUMMARY_INSTRUCTIONS + &quot;\n&quot; + <br>                                                 &quot;&lt;transcribe&gt;\n&quot; + speaker_formatted_content + &quot;&lt;/transcribe&gt;&quot;}]}]<br>        body=json.dumps(<br>            {<br>                &quot;anthropic_version&quot;: &quot;bedrock-2023-05-31&quot;,<br>                &quot;max_tokens&quot;: 4096,<br>                &quot;messages&quot;: messages,<br>                &quot;temperature&quot;: 0,<br>                &quot;top_p&quot;: 1.<br>            }<br>        )<br>        start_time = time.time()<br>        response = bedrock_client.invoke_model(body=body, modelId=BEDROCK_MODEL_ID)<br>        end_time = time.time()<br>        logger.info(f&quot;Bedrock total time spent thinking: {round(end_time - start_time, 2)}s&quot;)<br>        logger.debug(response)<br>    except Exception as e:<br>        logger.error(f&quot;Error analyzing transcript: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error analyzing transcript: {e}&#39;<br>        }<br>    <br>    # Decode the response from the Anthropic model<br>    try:<br>        analyzer_response = json.loads(response.get(&#39;body&#39;).read())<br>        logger.info(f&#39;analyzer_response: {analyzer_response}&#39;)<br>    except Exception as e:<br>        logger.error(f&quot;Error decoding analyzer response: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error decoding analyzer response: {e}&#39;<br>        }<br>    # Save the response value in S3.<br>    try:<br>        obj = s3.Object(output_s3_bucket, output_s3_key)<br>        obj.put(Body=analyzer_response[&#39;content&#39;][0][&#39;text&#39;] + &quot;\n\n4. Original Call Transcribe&quot; + speaker_formatted_content)<br>    except Exception as e:<br>        logger.error(f&quot;Error saving analyzer response: {e}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error saving analyzer response: {e}&#39;<br>        }<br>    logger.info(f&quot;Response saved in s3://{output_s3_bucket}/{output_s3_key}&quot;)<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: &#39;OK&#39;<br>    }</pre><p>The first function takes a dictionary containing the results of an Amazon Transcribe job and formats the content into a human-readable format. The function loops through the individual items in the transcription result, grouping the content by the speaker and adding timestamps and labels to each line.</p><p>The function is based on the example provided in the Amazon Bedrock samples repository: <a href="https://github.com/aws-samples/amazon-bedrock-samples/blob/main/generative-ai-solutions/recordings-summary-generator/recordings-summary-generation.yaml">https://github.com/aws-samples/amazon-bedrock-samples/blob/main/generative-ai-solutions/recordings-summary-generator/recordings-summary-generation.yaml</a>.</p><p>The main functionality consists of taking an S3 bucket name and an S3 key (file path) as input, reading the transcript file from the specified location, formatting the content of the transcript, and then employing the Amazon Bedrock service to analyze the transcript and generate a summary.</p><p>The function first verifies that the input file is a JSON file and then reads the file from the S3 bucket. It extracts the language code from the transcript data and formats the content using the format_content function.</p><p>Next, the function creates an Amazon Bedrock client and invokes the appropriate model to analyze the transcript. The analysis result is then saved back to the S3 bucket.</p><h3>Instructions</h3><p>The instrunctions for the Amazon Bedrock model are kept in a separate module instructions.py, to make it easier to modify them.</p><pre>&quot;&quot;&quot;<br>This file contains the instructions for the gen AI model to translate the conversation of the customer.<br>&quot;&quot;&quot;<br><br>text = &quot;&quot;&quot;<br>You are responsible for translating the conversation of the call center agent<br>of the OTT video service called Go3 with a customer.<br>You need to provide all the answers in English.<br>The Transcribe service generates the conversation and is provided in the following format:<br>&lt;transcribe&gt;<br>time_stamp  speaker_label   text<br>time_stamp  speaker_label   text<br>&lt;/transcribe&gt;<br>1. Summarize the conversation and analyze the customer sentiment and the agent quality. Provide the summary and analyses in English.<br>Label it &quot;1. Sentiment and Quality Analysis:&quot;<br>2. Analyze the speakers and decide who the agent and customer are. Note that there may be more than one customer speaking.<br>Label it &quot;2. Speaker Analysis:&quot;<br>3. Analyze the conversation made in {language_code} and, if needed, translate it to English so conversation makes sense.<br>Provide translated conversation with labels changed to &quot;Customer&quot; and &quot;Agent.&quot;<br>Include the original time stamps.<br>Label it &quot;3. Translated Conversation:&quot;<br>Here is the transcribed conversation in {language_code}:<br>&quot;&quot;&quot;<br><br>def get_instructions(language_code):<br>    return text.format(language_code=language_code)</pre><h3>Send Notification</h3><p>This helper function sends the result or an error to the SNS topic.</p><pre>def send_notification(subject: str, message: str) -&gt; dict:<br>    # Send the text to the SNS topic<br>    sns = boto3.client(&#39;sns&#39;)<br>    sns_topic_arn = os.getenv(&#39;OUTPUTNOTIFICATIONTOPIC_TOPIC_ARN&#39;)<br>    logger.info(f&quot;SNS topic ARN: {sns_topic_arn}&quot;)<br>    <br>    if sns_topic_arn:<br>        try:<br>            sns.publish(TopicArn=sns_topic_arn, Message=message, Subject=subject[:100])<br>            logger.info(f&quot;Text sent to SNS topic: {sns_topic_arn}&quot;)<br>            return {<br>                &#39;statusCode&#39;: 200,<br>                &#39;body&#39;: &#39;OK&#39;<br>            }<br>        except Exception as e:<br>            logger.error(f&quot;Error sending text to SNS topic: {e}&quot;)<br>            return {<br>                &#39;statusCode&#39;: 500,<br>                &#39;body&#39;: f&#39;Internal server error: Error sending text to SNS topic: {e}&#39;<br>            }<br>        <br>    else:<br>        logger.error(&quot;OUTPUTNOTIFICATIONTOPIC_TOPIC_ARN not set&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: &#39;Internal server error: OUTPUTNOTIFICATIONTOPIC_TOPIC_ARN not set&#39;<br>        }</pre><p>This function takes a subject and a message as input and sends the message to an Amazon SNS topic. The topic ARN is retrieved from an environment variable named OUTPUTNOTIFICATIONTOPIC_TOPIC_ARN.</p><p>If the topic ARN is not set, the function logs an error and returns an error response. If there is an exception while publishing the message to the topic, the function logs the error and returns an error response.</p><p>If the message is successfully published on the SNS topic, the function returns a successful response.</p><h3>Notify</h3><p>Send the notification with the results of the analyses.</p><pre>def notify(input_s3_bucket: str, input_s3_key: str) -&gt; dict:<br>    # Verify if it is an txt file<br>    if not input_s3_key.endswith(OUTPUT_EXT):<br>        logger.warning(<br>            f&quot;Invalid file type: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: &#39;Invalid file type&#39;<br>        }<br>    logger.info(f&quot;Notifying file: s3://{input_s3_bucket}/{input_s3_key}&quot;)<br><br>    # Generate the original input file name<br>    original_input_s3_key = input_s3_key.replace(OUTPUT_DIR, &quot;&quot;, 1).replace(OUTPUT_EXT, TRANSCRIBE_EXT)<br>    logger.info(f&quot;Original input file name: s3://{input_s3_bucket}/{original_input_s3_key}&quot;)<br>    # Read the input txt file from s3<br>    try:<br>        s3 = boto3.resource(&#39;s3&#39;)<br>        msg = s3.Object(input_s3_bucket, input_s3_key)<br>        text = msg.get()[&#39;Body&#39;].read().decode(&#39;utf-8&#39;)<br>        response = send_notification(f&quot;Call Center Analyzer - {input_s3_key}&quot;, text)<br>    except Exception as e:<br>        logger.error(f&quot;Error reading input file: {e}&quot;)<br>        response = {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: f&#39;Internal server error: Error reading input file: {e}&#39;<br>        }<br>    finally:<br>        return response</pre><p>This function is responsible for handling the notification process after a file has been processed by the Call Center Analyzer. It performs the following steps:</p><ol><li>Verifies that the input file is a text file (with the .txt extension).</li><li>Generates the original input file name by replacing the output directory and extension with the corresponding transcription directory and extension.</li><li>Reads the content of the input text file from the S3 bucket.</li><li>Sends a notification message to an Amazon SNS topic, using the send_notification function.</li></ol><p>If the input file is not a text file, the function returns an error response. If there is an exception while reading the input file, the function logs the error and returns an error response.</p><h3>SAM Template</h3><p>The template.yml file defines the AWS SAM template for deploying the application.</p><pre>Transform: AWS::Serverless-2016-10-31<br><br>Parameters:<br>  Environment:<br>    Type: String<br>    Default: dev<br>    AllowedValues:<br>      - dev<br>      - uat<br>      - prod<br>  Owner:<br>    Type: String<br>    # Use sam deploy --parameter-overrides Owner={your-email} to set this value<br><br>Resources:<br>  #----<br>  # InputBucket<br>  #----<br>  InputBucket:<br>    Type: AWS::S3::Bucket<br>    Properties:<br>      BucketName: !Sub ${AWS::StackName}-input-bucket-${AWS::AccountId}<br>      BucketEncryption:<br>        ServerSideEncryptionConfiguration:<br>          - ServerSideEncryptionByDefault:<br>              SSEAlgorithm: aws:kms<br>              KMSMasterKeyID: alias/aws/s3<br>      PublicAccessBlockConfiguration:<br>        IgnorePublicAcls: true<br>        RestrictPublicBuckets: true<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br><br>  InputBucketBucketPolicy:<br>    Type: AWS::S3::BucketPolicy<br>    Properties:<br>      Bucket: !Ref InputBucket<br>      PolicyDocument:<br>        Id: RequireEncryptionInTransit<br>        Version: &#39;2012-10-17&#39;<br>        Statement:<br>          - Principal: &#39;*&#39;<br>            Action: &#39;*&#39;<br>            Effect: Deny<br>            Resource:<br>              - !GetAtt InputBucket.Arn<br>              - !Sub ${InputBucket.Arn}/*<br>            Condition:<br>              Bool:<br>                aws:SecureTransport: &#39;false&#39;<br><br>  #----<br>  # OutputNotificationTopic<br>  #----<br>  OutputNotificationTopic:<br>    Type: AWS::SNS::Topic<br>    Properties:<br>      DisplayName: Call Center Analytics<br>      TopicName: !Sub ${AWS::StackName}-notification-topic-${AWS::AccountId}<br>      Subscription:<br>        - Protocol: email<br>          Endpoint: !Ref &#39;Owner&#39;<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br><br>  #----<br>  # AnalyzeFunction<br>  #----<br>  AnalyzeFunctionRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      AssumeRolePolicyDocument:<br>        Version: &#39;2012-10-17&#39;<br>        Statement:<br>          - Effect: Allow<br>            Principal:<br>              Service: lambda.amazonaws.com<br>            Action: sts:AssumeRole<br>      ManagedPolicyArns:<br>        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole<br>      Policies:<br>        - PolicyName: AnalyzeFunctionPolicy<br>          PolicyDocument:<br>            Version: &#39;2012-10-17&#39;<br>            Statement:<br>              - Sid: S3Policy<br>                Effect: Allow<br>                Action:<br>                  - s3:GetObject<br>                  - s3:GetObjectAcl<br>                  - s3:GetObjectLegalHold<br>                  - s3:GetObjectRetention<br>                  - s3:GetObjectTorrent<br>                  - s3:GetObjectVersion<br>                  - s3:GetObjectVersionAcl<br>                  - s3:GetObjectVersionForReplication<br>                  - s3:GetObjectVersionTorrent<br>                  - s3:ListBucket<br>                  - s3:ListBucketMultipartUploads<br>                  - s3:ListBucketVersions<br>                  - s3:ListMultipartUploadParts<br>                  - s3:AbortMultipartUpload<br>                  - s3:DeleteObject<br>                  - s3:DeleteObjectVersion<br>                  - s3:PutObject<br>                  - s3:PutObjectLegalHold<br>                  - s3:PutObjectRetention<br>                  - s3:RestoreObject<br>                Resource:<br>                  - !Sub arn:${AWS::Partition}:s3:::${InputBucket}<br>                  - !Sub arn:${AWS::Partition}:s3:::${InputBucket}/*<br>              - Sid: TranscriptionPolicy<br>                Effect: Allow<br>                Action:<br>                  - transcribe:StartTranscriptionJob<br>                Resource: &#39;*&#39;<br>              - Sid: BedrockPolicy<br>                Effect: Allow<br>                Action:<br>                  - bedrock:InvokeModel<br>                Resource: &#39;*&#39;<br>              - Sid: SNSPublishMessagePolicy<br>                Effect: Allow<br>                Action:<br>                  - sns:Publish<br>                Resource:<br>                  - !Ref OutputNotificationTopic<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br><br>  AnalyzeFunctionLogGroup:<br>    Type: AWS::Logs::LogGroup<br>    DeletionPolicy: Delete<br>    UpdateReplacePolicy: Retain<br>    Properties:<br>      LogGroupName: !Sub /aws/lambda/${AnalyzeFunction}<br>      RetentionInDays: 30<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br><br>  AnalyzeFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Description: !Sub<br>        - Stack ${AWS::StackName} Function ${ResourceName}<br>        - ResourceName: AnalyzeFunction<br>      CodeUri: src/analyze<br>      Handler: handler.handler<br>      Runtime: python3.11<br>      MemorySize: 3008<br>      Timeout: 900 # 15 minutes<br>      Tracing: Active<br>      Role: !GetAtt AnalyzeFunctionRole.Arn<br>      # Events:<br>      #   InputBucketTrigger:<br>      #     Type: S3<br>      #     Properties:<br>      #       Bucket: !Ref InputBucket<br>      #       Events:<br>      #         - s3:ObjectCreated:*<br>      Architectures:<br>        - arm64<br>      Environment:<br>        Variables:<br>          OUTPUTNOTIFICATIONTOPIC_TOPIC_NAME: !GetAtt OutputNotificationTopic.TopicName<br>          OUTPUTNOTIFICATIONTOPIC_TOPIC_ARN: !Ref OutputNotificationTopic<br>      Tags:<br>        AppManagerCFNStackKey: !Ref &#39;AWS::StackId&#39;<br>        Project: !Ref &#39;AWS::StackName&#39;<br>        Environment: !Ref &#39;Environment&#39;<br>        Owner: !Ref &#39;Owner&#39;<br><br>  AnalyzeFunctionInputBucketPermission:<br>    Type: AWS::Lambda::Permission<br>    Properties:<br>      FunctionName: !Ref AnalyzeFunction<br>      Action: lambda:InvokeFunction<br>      Principal: s3.amazonaws.com<br>      SourceAccount: !Ref AWS::AccountId<br>      SourceArn: !GetAtt InputBucket.Arn<br><br>  #----<br>  # ApplyNotification<br>  #<br>  # To avoid the cirtular dependency between AnalyzeFunction and InputBucket, <br>  # we need to apply the notification in runtime.<br>  # Reference: https://aws.amazon.com/blogs/mt/resolving-circular-dependency-in-provisioning-of-amazon-s3-buckets-with-aws-lambda-event-notifications/<br>  #----<br>  ApplyNotificationFunctionRole:<br>    Type: AWS::IAM::Role<br>    Properties:<br>      AssumeRolePolicyDocument:<br>        Version: &#39;2012-10-17&#39;<br>        Statement:<br>          - Effect: Allow<br>            Principal:<br>              Service: lambda.amazonaws.com<br>            Action: sts:AssumeRole<br>      ManagedPolicyArns:<br>        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole<br>      Path: /<br>      Policies:<br>        - PolicyName: S3BucketNotificationPolicy<br>          PolicyDocument:<br>            Version: &#39;2012-10-17&#39;<br>            Statement:<br>              - Sid: AllowBucketNotification<br>                Effect: Allow<br>                Action: s3:PutBucketNotification<br>                Resource:<br>                  - !Sub arn:aws:s3:::${InputBucket}<br>                  - !Sub arn:aws:s3:::${InputBucket}/*<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br><br>  ApplyBucketNotificationFunctionLogGroup:<br>    Type: AWS::Logs::LogGroup<br>    DeletionPolicy: Delete<br>    UpdateReplacePolicy: Retain<br>    Properties:<br>      LogGroupName: !Sub /aws/lambda/${ApplyBucketNotificationFunction}<br>      RetentionInDays: 30<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br><br>  ApplyBucketNotificationFunction:<br>    Type: AWS::Lambda::Function<br>    Properties:<br>      Description: https://aws.amazon.com/blogs/mt/resolving-circular-dependency-in-provisioning-of-amazon-s3-buckets-with-aws-lambda-event-notifications/<br>      # CodeUri: src/apply-notification<br>      Handler: index.handler<br>      Runtime: python3.11<br>      MemorySize: 3008<br>      Timeout: 240<br>      # Tracing: Active<br>      Role: !GetAtt ApplyNotificationFunctionRole.Arn<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br>      Code:<br>        ZipFile: |<br>          import boto3<br>          import logging<br>          import json<br>          import cfnresponse<br>          s3Client = boto3.client(&#39;s3&#39;)<br>          logger = logging.getLogger()<br>          logger.setLevel(logging.DEBUG)<br>          def addBucketNotification(bucketName, notificationId, functionArn):<br>            notificationResponse = s3Client.put_bucket_notification_configuration(<br>              Bucket=bucketName,<br>              NotificationConfiguration={<br>                &#39;LambdaFunctionConfigurations&#39;: [<br>                  {<br>                    &#39;Id&#39;: notificationId,<br>                    &#39;LambdaFunctionArn&#39;: functionArn,<br>                    &#39;Events&#39;: [<br>                      &#39;s3:ObjectCreated:*&#39;<br>                    ]<br>                  },<br>                ]<br>              }<br>            )<br>            return notificationResponse<br>          def create(properties, physical_id):<br>            bucketName = properties[&#39;S3Bucket&#39;]<br>            notificationId = properties[&#39;NotificationId&#39;]<br>            functionArn = properties[&#39;FunctionARN&#39;]<br>            response = addBucketNotification(bucketName, notificationId, functionArn)<br>            logger.info(&#39;AddBucketNotification response: %s&#39; % json.dumps(response))<br>            return cfnresponse.SUCCESS, physical_id<br>          def update(properties, physical_id):<br>            return cfnresponse.SUCCESS, None<br>          def delete(properties, physical_id):<br>            return cfnresponse.SUCCESS, None<br>          def handler(event, context):<br>            logger.info(&#39;Received event: %s&#39; % json.dumps(event))<br>            status = cfnresponse.FAILED<br>            new_physical_id = None<br>            try:<br>              properties = event.get(&#39;ResourceProperties&#39;)<br>              physical_id = event.get(&#39;PhysicalResourceId&#39;)<br>              status, new_physical_id = {<br>                &#39;Create&#39;: create,<br>                &#39;Update&#39;: update,<br>                &#39;Delete&#39;: delete<br>              }.get(event[&#39;RequestType&#39;], lambda x, y: (cfnresponse.FAILED, None))(properties, physical_id)<br>            except Exception as e:<br>              logger.error(&#39;Exception: %s&#39; % e)<br>              status = cfnresponse.FAILED<br>            finally:<br>              cfnresponse.send(event, context, status, {}, new_physical_id)<br>        <br>  ApplyNotification:<br>    Type: Custom::ApplyNotification<br>    Properties:<br>      ServiceToken: !GetAtt ApplyBucketNotificationFunction.Arn<br>      S3Bucket: !Ref InputBucket<br>      FunctionARN: !GetAtt AnalyzeFunction.Arn<br>      NotificationId: S3ObjectCreatedEvent<br>      Tags:<br>        - Key: AppManagerCFNStackKey<br>          Value: !Ref &#39;AWS::StackId&#39;<br>        - Key: Project<br>          Value: !Ref &#39;AWS::StackName&#39;<br>        - Key: Environment<br>          Value: !Ref &#39;Environment&#39;<br>        - Key: Owner<br>          Value: !Ref &#39;Owner&#39;<br>#----<br># Outputs<br>#----<br>Outputs:<br>  OutputNotificationTopic:<br>    Description: Notification Topic for Call Center Analytics<br>    Value: !Ref OutputNotificationTopic<br>    Export:<br>      Name: !Sub ${AWS::StackName}-OutputNotificationTopic<br>  AnalyzeFunction:<br>    Description: AnalyzeFunction ARN<br>    Value: !GetAtt AnalyzeFunction.Arn<br>    Export:<br>      Name: !Sub ${AWS::StackName}-AnalyzeFunction<br>  InputBucket:<br>    Description: InputBucket ARN<br>    Value: !Ref InputBucket<br>    Export:<br>      Name: !Sub ${AWS::StackName}-InputBucket</pre><p>This template defines resources for an AWS serverless application modeled using the AWS Serverless Application Model (SAM). It specifies a collection of AWS resources, properties, and relationships.</p><h4>Parameters</h4><pre>Parameters:<br>  Environment:<br>    Type: String<br>    Default: dev<br>    AllowedValues:<br>      - dev<br>      - uat<br>      - prod<br>  Owner:<br>    Type: String</pre><p>These are input parameters that can be passed during deployment.</p><ul><li>Environment: A string parameter with allowed values &#39;dev&#39;, &#39;uat&#39;, or &#39;prod&#39;, by default set to &#39;dev&#39;.</li><li>Owner: A string parameter to specify the owner&#39;s email, typically used for tagging resources and setting notification endpoints.</li></ul><h4>Resources</h4><ol><li><strong>S3 Bucket Policy</strong> (InputBucketBucketPolicy): Creates a bucket policy on InputBucket that denies any non-secure transport requests to the bucket, enforcing encryption in transit.</li><li><strong>SNS Topic</strong> (OutputNotificationMetricFilterTopic): Defines an Amazon SNS topic for posting notifications, named according to the stack name and account ID. Subscriptions can be made to notify endpoints such as the email of the Owner.</li><li><strong>IAM Role</strong> (AnalyzeFunctionRole): Specifies an IAM role assumed by the Lambda function AnalyzeFunction. It grants permissions for accessing AWS services like S3, Transcribe, and for publishing messages to SNS topics.</li><li><strong>CloudWatch Log Group</strong> (AnalyzeFunctionLogGroup): Establishes a log group in Amazon CloudWatch Logs for storing logs from AnalyzeFunction.</li><li><strong>Lambda Function</strong> (AnalyzeFunction): Deploys an AWS Lambda function with Python runtime, configured with appropriate memory size, timeout settings, and environment variables. Its associated IAM role permits actions on S3 and the SNS topic.</li><li><strong>Lambda Permission</strong> (AnalyzeFunctionInputBucketPermission): Assigns permission for AnalyzeFunction Lambda function to be invoked by events originating from InputBucket.</li><li><strong>IAM Role</strong> (ApplyNotificationFunctionRole): Allocates an IAM role to be assumed by the Lambda function ApplyBucketNotificationFunction, which is responsible for applying bucket notifications. It specifically allows updating the S3 bucket notification configuration.</li><li><strong>CloudWatch Log Group </strong>(ApplyBucketNotificationFunctionLogGroup): Sets up a log group in Amazon CloudWatch Logs for the ApplyBucketNotificationFunction, including retention policies.</li><li><strong>Lambda Function</strong> (ApplyBucketNotificationFunction): Implements a Lambda function with inline Python code designed to add a bucket notification configuration to InputBucket. This function addresses circular dependencies between the Lambda function and the S3 bucket.</li><li><strong>Custom Resource</strong> (ApplyNotification): Activates ApplyBucketNotificationFunction to establish the intended S3 bucket notification linkage between InputBucket and AnalyzeFunction.</li><li><strong>Outputs</strong>: Provides key references to resources created by the template, available for usage in other stacks or applications.</li></ol><ul><li>OutputNotificationTopic: The ARN of the SNS topic.</li><li>AnalyzeFunction: The ARN of AnalyzeFunction.</li><li>InputBucket: The ARN of the S3 bucket (InputBucket).</li></ul><h3>Installation Guide</h3><p>To deploy this application on your AWS account using AWS SAM, follow these steps:</p><ol><li><strong>Prerequisites</strong>: Ensure you have AWS CLI and AWS SAM CLI installed and configured on your machine. Also, request the access to Anthropic Claude 3 Sonnet Amazon Bedrock base model.</li><li><strong>Clone the Repository</strong>: Download the project files by cloning the GitHub repository:</li></ol><pre>git clone https://github.com/wdoganowski/tv3_call_center_analyzer.git</pre><p>3. <strong>Update Parameters</strong>: In template.yml change Environment and optionally set the Owner parameter.</p><p>4. <strong>Build the Project</strong>: Build the project using AWS SAM:</p><pre>sam build</pre><p>5. <strong>Test</strong>: Optionally test the build. Before update the events\ and environments\ json files with the arns of your test resources and run the following:</p><pre>sam local invoke AnalyzeFunction --event events/analyze.json --env-vars environments/dev.json <br>sam local invoke AnalyzeFunction --event events/transcribe.json --env-vars environments/dev.json <br>sam local invoke AnalyzeFunction --event events/notify.json --env-vars environments/dev.json</pre><p>6. <strong>Deploy</strong>: If the Owner parameter has no default value, you need to specify it here:</p><pre>sam deploy --parameter-overrides Owner={your-email-address}</pre><p>Otherwise, deploy without any parameters:</p><pre>sam deploy</pre><p>7. <strong>Accept the SNS Notifications</strong>: An email requesting you to accept the notifications should be in your inbox. Accept it.</p><p>8. <strong>Verify Deployment</strong>: Upload an mp3 file with the call recording to the InputBucket into recordings directory.</p><h4>Environment Variables</h4><p>The process may be modified using environemnt variables:</p><ol><li>SUMMARY_INSTRUCTIONS Modify the instruction,</li><li>BEDROCK_MODEL_ID Modify the Amazon Medrock base model,</li><li>OUTPUTNOTIFICATIONTOPIC_TOPIC_ARN Modify the SNS topic.</li></ol><h3>Next Steps to Expand the Project</h3><p>We are considering the following next steps in application development. If you have other ideas, please share.</p><ol><li><strong>Real-time Processing</strong>: Implement real-time analytics by connecting the call center’s telephony system with an AWS Kinesis stream that feeds into Amazon Transcribe. Employ Amazon Bedrock in real-time to provide instant feedback and guidance to agents during calls.</li><li><strong>Quality Assurance Dashboard</strong>: Develop a quality assurance dashboard for supervisors using Amazon QuickSight. This dashboard would provide insights into call quality, sentiment trends, and agent performance metrics over time.</li><li><strong>Agent Training Module</strong>: Create an agent training module based on the analysis results to provide personalized coaching and best practice recommendations. Incorporate gamification to motivate continuous improvement among call center staff.</li><li><strong>Multichannel Support</strong>: Expand the solution to analyze and summarize text interactions from chat, email, and social media platforms, offering a comprehensive view of customer engagements across all channels.</li><li><strong>Predictive Analytics</strong>: Incorporate predictive analytics to anticipate customer issues and proactively resolve them before they escalate, thereby reducing call volumes and improving customer experience.</li><li><strong>Integration with CRM Systems</strong>: Integrate the application with Customer Relationship Management (CRM) systems to provide agents with contextual information and historical interactions, enabling them to personalize the conversation.</li><li><strong>Detect Call Issues: </strong>Implement automated summary reporting sent to stakeholders for the calls with potential issues in the communication between the customer and the agent.</li></ol><h3>Conclusions</h3><p>By leveraging AWS services, including AWS Bedrock, we developed an efficient and scalable solution for the Go3 call center to analyze and translate multilingual call transcripts. This solution addressed the immediate needs of call analysis and provided a foundation for future enhancements such as real-time analytics and sentiment analysis.</p><p>Here are the key takeaways:</p><ul><li><strong>Multilingual Analysis</strong>: The ability to handle multiple languages was crucial given the diverse customer base across the Baltic countries.</li><li><strong>AWS Infrastructure</strong>: Utilized various AWS services like Amazon S3, AWS Lambda, Amazon Transcribe, and Amazon SNS to build a modular and scalable application architecture.</li><li><strong>Functionality</strong>: Automated transcription and translation process enabled the call center manager to review calls and optimize scripts effectively.</li><li><strong>Customizable Workflow</strong>: Allowed tuning via environment variables like SUMMARY_INSTRUCTIONS and BEDROCK_MODEL_ID.</li></ul><p>The solution not only enhances the operational efficiency of the Go3 call center but also opens avenues for continuous improvement in service quality and customer experience through advanced analytics and automation.</p><p>Feedback and suggestions are encouraged for further improvements to make the solution even more robust and tailored to evolving call center needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd08d498e16f" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/transforming-call-center-analytics-with-aws-bedrock-fd08d498e16f">Transforming Call Center Analytics with AWS Bedrock</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Impressions from AWS Summit Stockholm 2024]]></title>
            <link>https://medium.com/@dogan1971/impressions-from-aws-summit-stockholm-2024-61101c18fceb?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/61101c18fceb</guid>
            <category><![CDATA[amazon-q]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 17:03:16 GMT</pubDate>
            <atom:updated>2024-06-05T17:03:16.064Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeQTkPIZoSJNjtnQLTh6DA.jpeg" /><figcaption>Generated by bing.com</figcaption></figure><p>The AWS Summit Stockholm 2024 showcased a variety of sessions with a strong emphasis on generative AI. While the topics were fascinating, the depth of content in some sessions could have been better. Below are detailed impressions from the sessions I attended.</p><h4>Opening Keynote</h4><p>The opening keynote provided a comprehensive introduction to the summit, featuring real customer cases highlighting AWS’s impact across different industries. Keynote speakers included notable figures such as Becky Weiss, VP Distinguished Engineer at AWS, and Dag Lindbo, Head of Software Technology at Ericsson, who shared insights on AWS’s role in driving innovation and digital transformation in the Nordics.</p><h4>Build a Data Foundation to Fuel Generative AI</h4><p>This session offered a solid introduction to Retrieval-Augmented Generation (RAG), explaining its mechanism and the benefits and limitations. The speaker emphasized that sometimes prompt engineering suffices, eliminating the need for RAG. A notable demo featured Amazon Bedrock and its Knowledge Base, illustrating how to set up RAG on AWS. RAG enhances generative AI by retrieving relevant data to improve the generated content’s accuracy and relevance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdzrBeVxboYXF4PL2iN1tg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVYG4h1RFHYnFWdi_1IoxA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-BUAa-q-vNvBs4hkP2dBw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoCORWE6c6ubPKNbWmsAkg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SmohNLudSVPo8c-C1b0Grw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF1snHarhTKT7DXOZUippQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rLqfAD4RUR_9SA8e_p75w.jpeg" /></figure><p>Notabene, I plan to develop an application using Retrieval-Augmented Generation (RAG) soon. This application will initially be enhanced with technical documentation. However, I aim to expand its functionality by integrating an API to interact with external data sources.</p><p>For those new to RAG, it is an advanced Natural Language Processing (NLP) technique that enhances generative models by incorporating relevant information retrieved from external sources. In RAG, a retrieval mechanism first searches a database or document repository for pertinent data based on a user query. This information is then fed into a generative model, which uses it to produce a more accurate and contextually rich response.</p><p>RAG is particularly effective for applications requiring real-time access to up-to-date information, such as question answering and interactive dialogue systems. By combining retrieval and generation, RAG systems can provide detailed and reliable responses, making them ideal for tasks involving dynamic and extensive data.</p><p>More information is available online, e.g. here: <a href="https://aws.amazon.com/blogs/aws/build-generative-ai-applications-with-amazon-bedrock-studio-preview/">https://aws.amazon.com/blogs/aws/build-generative-ai-applications-with-amazon-bedrock-studio-preview/</a>.</p><h4>Use RAG to Improve Responses in Generative AI Applications</h4><p>Though it began with an overview similar to the previous session, this session distinguished itself with a practical case study presented by Canfang Feng, Senior Data Scientist at KONE. Feng discussed how KONE uses RAG in their online support application for elevator service staff, demonstrating the real-world applicability of the technology in improving customer support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oo8bX7VxUBz0Qh3CLzslfQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJ4o6TOen0R86uwJmUCYKA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8dB8yagS0UBzSwhRGsIP8Q.jpeg" /></figure><h4>Understand Your Customers Better with a Modern Data Strategy</h4><p>This session was somewhat disappointing, as it merely covered generic concepts of Data Lakes and Modern Data Architecture without offering new insights. The material presented is readily available in AWS’s existing <a href="https://docs.aws.amazon.com/whitepapers/latest/derive-insights-from-aws-modern-data/modern-data-architecture-on-aws.html">whitepapers and documentation</a>, adding little value for attendees already familiar with these concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXFjGEfVQWYCStB-KAx7cg.jpeg" /></figure><h4>Threat Modeling Your Generative AI Workload to Evaluate Security Risk</h4><p>This session was engaging and practical, focusing on the security risks associated with generative AI applications. The presenters outlined how to develop a threat model and create threat statements, providing concrete examples of risk mitigations. This session’s pragmatic approach was particularly beneficial for understanding the security aspects of deploying generative AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-1dOYS0p26rqvNO8Q0qWw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXWbuwwGITuxtUt-C25sCA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpAOY-a1WfjlDog_ABrzPA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFMjS4ZUL42DC14E9FH7Vw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mknlauZFnnlMtMoC9ApZRw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlSht3AkRRDUS3gCsFwWEA.jpeg" /></figure><h4>Bring the Power of Generative AI to Your Employees with Amazon Q</h4><p>This intriguing session highlighted how Amazon Q can be expanded to function as an internal assistant for employees. Amazon Q integrates with various platforms like Slack, Jira, MS Exchange, and SharePoint, enabling seamless augmentation with existing documents. However, it was disappointing to learn that Amazon Q is not yet available in Europe, and no timeline for its release was provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7lQsre93Ky5_jGfDe1L0Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6bZ9D0KrkerScDD5KA4Qg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ej4gtR9-Z_O3WUZopCFpQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HECULcILNrilRXZJBJ_fg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OOh1tJvWId4ssEa_L0ZxuQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vgM86PYJyIbpHoxM9uJTw.jpeg" /></figure><h4>Generative BI in Amazon QuickSight</h4><p>The final session demonstrated the use of Amazon QuickSight and how it can help data engineers and dashboard users. QuickSight facilitates a shorter learning curve for dashboard development and enhances users’ ability to understand, summarize, and describe data more effectively. This session provided practical insights into leveraging QuickSight for better business intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ligorxpPRCT6S733HI-JEA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ac5SNzWPPH6nTvsn1zV7Og.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbV9ASv3mM3sjRuSPt3I0Q.jpeg" /></figure><h4>Conclusion</h4><p>The AWS Summit Stockholm 2024 highlighted AWS’s ongoing advancements in generative AI and cloud solutions. While the keynote and certain sessions like those on RAG and security were particularly informative, others fell short in providing new or detailed content. Overall, the summit reinforced AWS’s commitment to innovation but also underscored the need for more depth in session content to cater to experienced users.</p><p>For more details on the sessions, you can refer to the <a href="https://aws.amazon.com/events/summits/emea/stockholm/agenda/">AWS Summit Stockholm Agenda</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61101c18fceb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlined AWS Management: Efficient, Cost-Effective Alternative to Scheduler — Guide]]></title>
            <link>https://awstip.com/streamlined-aws-management-efficient-cost-effective-alternative-to-scheduler-guide-a59c701ae7e0?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59c701ae7e0</guid>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[efficiency]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[amazon-eventbridge]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 17:49:38 GMT</pubDate>
            <atom:updated>2024-01-26T15:34:00.973Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Streamlined AWS Management: Efficient, Cost-Effective Alternative to Scheduler — Guide</h3><h3>Introduction</h3><p>Managing Amazon Web Services (AWS) resources efficiently is paramount for businesses aiming to optimize costs while ensuring uninterrupted service in the dynamic landscape of cloud computing. A common challenge AWS users face is the effective scheduling of EC2 instances — a task that directly impacts operational costs and system performance. While AWS offers its native Instance Scheduler solution, designed for automating the start and stop of EC2 instances, this tool may sometimes be overkill, particularly for smaller systems due to its relative complexity and cost of AWS Instance Scheduler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kyBej0DnkYw08AQLLwwQEQ.png" /><figcaption>Generated with DALL·E</figcaption></figure><p>In this context, an alternative approach leveraging AWS Lambda functions and Amazon EventBridge emerges as a compelling solution. This method provides a more granular, flexible, and cost-effective way to manage EC2 instance schedules. This approach can lead to significant cost savings and operational efficiency, especially for smaller or more dynamic environments, where a lighter and more adaptable tool is advantageous.</p><p>This article proposes a practical solution based on AWS Lambda, triggered by EventBridge schedules, which can be tailored to specific needs. This approach ensures a high degree of customization in how and when EC2 instances are managed and offers a more economical and less complex alternative to the AWS Instance Scheduler. By harnessing the power of AWS Lambda and EventBridge, users can create a system that responds dynamically to their operational requirements, ensuring that resources are utilized effectively and that costs are kept under control.</p><p>The following sections will delve into the details of this solution, providing a step-by-step guide on setting it up, discussing its advantages and limitations, and exploring potential avenues for further customization and enhancement.</p><h3>The Proposed Solution: Automating EC2 Instance Scheduling with AWS Lambda and EventBridge</h3><p>In addressing the need for a more streamlined and cost-effective solution for EC2 instance scheduling, we propose a method that leverages AWS Lambda and Amazon EventBridge. This approach allows for creating a highly customizable and scalable system for managing EC2 instances based on specific scheduling requirements.</p><h3>Key Components</h3><ol><li>AWS Lambda: A serverless computing service that lets you run code without provisioning or managing servers.</li><li>Amazon EventBridge: A serverless event bus service that enables you to connect your applications with data from various sources.</li></ol><h3>How It Works</h3><p>The core of this solution is a Lambda function triggered by an EventBridge schedule, which performs start or stop actions on EC2 instances based on specified tags. This setup provides the flexibility to manage instance schedules according to diverse operational patterns, whether weekly, daily, or any other custom schedule.</p><h3>Implementing the Lambda Function</h3><p>The Lambda function is written in Python and uses the Boto3 AWS SDK to interact with EC2 instances. Below is the essential code snippet for the Lambda function:</p><pre>import boto3<br><br>region = &#39;eu-north-1&#39;<br>ec2 = boto3.client(&#39;ec2&#39;, region_name=region)<br><br>def lambda_handler(event, context):<br>    # Define the tag key and value to filter by<br>    tag_key = event.get(&#39;tag_key&#39;)<br>    tag_value = event.get(&#39;tag_value&#39;)<br>    action = event.get(&#39;action&#39;)<br><br>    # Describe instances that have the specified tag<br>    response = ec2.describe_instances(<br>        Filters=[<br>            {<br>                &#39;Name&#39;: f&#39;tag:{tag_key}&#39;,<br>                &#39;Values&#39;: [tag_value]<br>            }<br>        ]<br>    )<br><br>    # Extract instance IDs<br>    instances = [instance[&#39;InstanceId&#39;] for reservation in response[&#39;Reservations&#39;] for instance in reservation[&#39;Instances&#39;]]<br>    <br>    # Perform the specified action on the instances<br>    if instances:<br>        if action == &#39;start&#39;:<br>            ec2.start_instances(InstanceIds=instances)<br>            print(&#39;Started your instances: &#39; + str(instances))<br>        elif action == &#39;stop&#39;:<br>            ec2.stop_instances(InstanceIds=instances)<br>            print(&#39;Stopped your instances: &#39; + str(instances))<br>        else:<br>            print(&#39;Unknown action: &#39; + action)<br>    else:<br>        print(&#39;No instances found with the specified tag, action &#39; + action + &#39; not performed&#39;)</pre><p>This function checks for EC2 instances with specified tags and performs the desired action (start or stop) based on the EventBridge event details.</p><h3>Flexibility and Scalability</h3><p>This solution stands out for its flexibility. By modifying the EventBridge rules or the tags on the EC2 instances, you can adjust the scheduling to suit different requirements. It’s equally scalable — the process remains the same whether you’re managing a few instances or several hundred.</p><p>In the following sections, we will delve deeper into the setup process, including configuring IAM roles and permissions, setting up EventBridge, and discussing the advantages and limitations of this approach.</p><h3>Step-by-Step Configuration for EC2 Scheduling Using AWS Lambda and EventBridge</h3><p>To implement the proposed solution for managing EC2 instances, follow these detailed steps:</p><h4>1. Configuring IAM Role and Permissions</h4><p>Create an IAM Role:</p><ul><li>Go to the IAM console and create a new role.</li><li>Select AWS Lambda as the service that will use this role.</li></ul><p>Attach Required Policies:</p><ul><li>Attach policies granting permission for Lambda to interact with EC2 and CloudWatch Logs.</li><li>Ensure the role has permissions like ec2:StartInstances, ec2:StopInstances, and ec2:DescribeInstances for EC2 management and permissions for log creation and management in CloudWatch.</li><li>For more details, consult the <a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-permissions.html">AWS Lambda Permissions Documentation</a> and the <a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/ec2-api-permissions.html">EC2 Permissions Documentation</a>.</li><li>Here is an example of such a policy:</li></ul><pre>{   <br>   &quot;Version&quot;: &quot;2012-10-17&quot;,   <br>   &quot;Statement&quot;: [<br>       {<br>           &quot;Effect&quot;: &quot;Allow&quot;,<br>           &quot;Action&quot;: [<br>               &quot;logs:CreateLogGroup&quot;,<br>               &quot;logs:CreateLogStream&quot;,<br>               &quot;logs:PutLogEvents&quot;<br>           ],<br>           &quot;Resource&quot;: &quot;arn:aws:logs:*:*:*&quot;<br>       },<br>       {<br>           &quot;Effect&quot;: &quot;Allow&quot;,<br>           &quot;Action&quot;: [<br>               &quot;ec2:StartInstances&quot;,<br>               &quot;ec2:StopInstances&quot;,<br>               &quot;ec2:DescribeInstances&quot;<br>           ],<br>           &quot;Resource&quot;: &quot;*&quot;<br>       }<br>    ]<br> }</pre><h4>2. Setting Up AWS Lambda</h4><p>Create a Lambda Function:</p><ul><li>Navigate to the AWS Lambda console and create a new function.</li><li>Choose Python as the runtime environment.</li><li>Paste the provided Lambda function code into the editor.</li><li>Select “Change default execution role” and “Use an existing role,” then select the role created in the previous step.</li></ul><h4>3. Configuring EventBridge</h4><p>Create an EventBridge Rule:</p><ul><li>In the Amazon EventBridge console, create a new rule.</li><li>Define a schedule using cron expressions for the times you want your Lambda function to run (e.g., for weekly schedules).</li><li>In the target section, select your Lambda function.</li></ul><p>Configure Input Parameters:</p><ul><li>Choose the option to configure input parameters (like tag_key, tag_value, and action) that the Lambda function will use.</li><li>Here is and example:</li></ul><pre>{<br>   &quot;tag_key&quot;: &quot;InstanceScheduler&quot;,<br>   &quot;tag_value&quot;: &quot;Weekdays&quot;,<br>   &quot;action&quot;: &quot;start&quot;<br>}</pre><h4>4. Testing and Verification</h4><p>Test the Function:</p><ul><li>Manually invoke the Lambda function with test events to verify that it behaves as expected.</li><li>Check CloudWatch Logs to confirm that the function is executing without errors and is performing the intended actions on your EC2 instances.</li></ul><h4>5. Monitoring and Logging</h4><p>Set Up CloudWatch Logs:</p><ul><li>Ensure that logs are enabled for your Lambda function to monitor its activity and troubleshoot any potential issues.</li><li>Regularly review the logs to ensure the system is operating correctly.</li></ul><p>Following these steps, you will have set up an efficient and customizable solution for scheduling your AWS EC2 instances. This method provides the flexibility required for various operational scenarios and helps optimize costs by ensuring instances are not running when they’re not needed.</p><h3>Pros and Cons of the Lambda and EventBridge EC2 Scheduling Solution</h3><h4>Pros</h4><ol><li><strong>Cost-Effectiveness</strong>: This approach significantly reduces costs, particularly for small to medium-sized systems, by eliminating the need for continuous instance running.</li><li><strong>Scalability</strong>: Easily adaptable to scale up or down according to the number of EC2 instances without additional setup complexities.</li><li><strong>Customizability</strong>: Offers high flexibility in scheduling, allowing for specific, tag-based instance management.</li><li><strong>Reduced Complexity</strong>: More straightforward than comprehensive solutions like AWS Instance Scheduler, especially for smaller setups.</li><li><strong>Automation and Efficiency</strong>: Improves operational efficiency by automating routine tasks and reducing manual intervention.</li></ol><h4>Cons</h4><ol><li><strong>Initial Setup Requirement</strong>: Requires an initial setup and a basic understanding of AWS services and Lambda functions.</li><li><strong>Limited to AWS Ecosystem</strong>: As a native AWS solution, it is unsuitable for managing instances across different cloud platforms.</li><li><strong>Monitoring and Maintenance</strong>: Requires regular monitoring and potential updates to the Lambda function for changing requirements or AWS service updates.</li></ol><h3>Expansion and Follow-Up Steps</h3><p>I suggest further expanding this approach, giving it more reliability and flexibility. How would you expand it further?</p><ol><li><strong>Enhanced Scheduling Options</strong>: Introduce more complex scheduling capabilities, like conditional triggers based on resource utilization or specific events.</li><li><strong>Integration with Other AWS Services</strong>: Expand the solution with services like AWS Auto Scaling, AWS S3, or RDS for a more comprehensive resource management system.</li><li><strong>Improved Error Handling and Notifications</strong>: Implement advanced error handling and notifications through Amazon SNS or CloudWatch alarms for better oversight.</li><li>Prepare Cloudformation Template: The Cloudformation template would help copy this solution to different accounts, avoiding simple mistakes and saving time.</li></ol><h3>Conclusion</h3><p>The Lambda and EventBridge solution for EC2 scheduling is a compelling alternative to more complex and expensive options like AWS Instance Scheduler. It balances functionality, cost, and ease of use, particularly for smaller or more dynamic AWS environments. By following the steps outlined in this article, AWS users can efficiently manage their EC2 instances, optimizing both operational performance and cost.</p><p>While this approach is highly effective, it is crucial to consider the initial setup requirements and ongoing maintenance. Keeping the Lambda function and related components up-to-date as AWS continues to evolve will ensure the system remains efficient and secure. This solution demonstrates the power and flexibility of AWS services and highlights the potential for creative and cost-effective cloud resource management strategies.</p><h4>References</h4><ul><li><a href="https://aws.amazon.com/solutions/implementations/instance-scheduler-on-aws/">AWS Instance Scheduler</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-permissions.html">AWS Lambda Permissions</a></li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/APIReference/ec2-api-permissions.html">EC2 Permissions</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59c701ae7e0" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/streamlined-aws-management-efficient-cost-effective-alternative-to-scheduler-guide-a59c701ae7e0">Streamlined AWS Management: Efficient, Cost-Effective Alternative to Scheduler — Guide</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Tutorial: How to Secure AWS S3 with MFA and SSO]]></title>
            <link>https://awstip.com/step-by-step-tutorial-how-to-secure-aws-s3-with-mfa-and-sso-0b258a330caf?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b258a330caf</guid>
            <category><![CDATA[multi-factor-auth]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[single-sign-on]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Tue, 10 Oct 2023 20:24:52 GMT</pubDate>
            <atom:updated>2023-10-10T20:24:52.057Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p><em>Unlock the Power of AWS S3 Security: A Comprehensive Guide to Safeguarding Your Data with Multi-Factor Authentication (MFA) and Single Sign-On (SSO)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MjD_E1XCpjV4THYFDkojmA.png" /><figcaption>Created with Generative AI</figcaption></figure><p>In the ever-evolving landscape of cloud security, safeguarding sensitive data stored in Amazon Web Services (AWS) S3 buckets is paramount. I’m sure you’re well aware that the foundation of cloud security lies not only in robust encryption and access controls but also in ensuring that only authorized users can access your valuable assets.</p><p>This article delves into an advanced yet crucial aspect of AWS security — configuring your S3 bucket to grant access solely to users who have authenticated using Multi-Factor Authentication (MFA) or have logged in through Single Sign-On (SSO) with MFA authentication. We’ll navigate through the intricacies of this setup, equipping you with the knowledge and expertise to fortify your AWS environment against unauthorized access.</p><p>If you are interested in finding out how to set your AWS account to allow accessing it using the AWS IAM Identity Center SSO instead of logging to the individual accounts in your AWS Organisation (which requires you to remember multiple users and passwords), please read my another article <a href="https://medium.com/aws-tip/easier-access-to-multiple-accounts-with-iam-identity-center-35bc25fdb0c8">Access to multiple accounts with IAM Identity Center</a>.</p><p>Coming back to enforcing MFA, in a world where security breaches and data leaks are ever-present threats, our journey to secure AWS S3 buckets begins with a deeper understanding of MFA, SSO with MFA, and the pivotal role they play in enhancing your cloud security posture. Let’s embark on this exploration together and empower ourselves with the knowledge and tools to safeguard our digital assets effectively.</p><p>So, dear AWS aficionados, fasten your seatbelts as we unlock the secrets to enforcing MFA and SSO authentication in your AWS S3 bucket, ensuring that only the right keys can unlock the treasure chest of your cloud data. In the next few minutes, you’ll be well on your way to becoming an expert in securing your AWS S3 resources like a pro.</p><h3>Setting the Stage</h3><p>The digital age has ushered in a transformative era for businesses, enabling them to store, manage, and share data with unprecedented ease and efficiency. One of the cornerstones of this data-driven revolution is the adoption of cloud computing, and Amazon Web Services (AWS) has emerged as a leading player in this domain. AWS S3 (Simple Storage Service) stands as a linchpin in this cloud ecosystem, serving as a secure and scalable storage solution for countless organizations worldwide.</p><p>As organizations migrate their data and workloads to AWS S3, the question of security takes center stage. The cloud, while offering remarkable advantages in terms of accessibility and scalability, also introduces a host of new security challenges. In this landscape, the protection of your S3 buckets becomes a critical concern. Unprotected or inadequately secured S3 buckets can lead to unauthorized access, data breaches, compliance violations, and reputational damage.</p><h3>The Stakes Are High</h3><p>Imagine your S3 buckets as digital treasure chests, holding valuable assets such as sensitive customer data, intellectual property, confidential documents, and critical backups. Unauthorized access to these buckets can have dire consequences, ranging from financial losses to legal ramifications and a tarnished brand image. Furthermore, with the ever-increasing sophistication of cyber threats, the importance of a robust defense cannot be overstated.</p><p>To underscore the significance of securing your S3 buckets, consider the following scenarios:</p><p>Data Privacy Regulations: As global data privacy regulations like GDPR and CCPA become more stringent, organizations face hefty fines for data breaches. A well-secured S3 bucket is your first line of defense against costly compliance violations.</p><p>Corporate Espionage: Competitors or malicious actors may attempt to gain unauthorized access to your confidential information, jeopardizing your organization’s strategic advantages.</p><p>Data Integrity: Unauthorized tampering with your data could lead to misinformation, damaged trust, and compromised decision-making.</p><h3>AWS Shared Responsibility Model</h3><p>In the AWS cloud, security is a shared responsibility between AWS and its customers. While AWS is responsible for the security of the cloud infrastructure, including the physical facilities and network infrastructure, customers are responsible for securing their data and applications within AWS. This means that you have a crucial role to play in implementing effective security measures for your AWS resources, including S3 buckets.</p><h3>The Need for Strong Authentication</h3><p>Authentication is a fundamental building block of any security strategy, and when it comes to AWS S3, enforcing strong authentication mechanisms is imperative. This is where Multi-Factor Authentication (MFA) and Single Sign-On (SSO) with MFA authentication come into play.</p><p>In the next sections of this article, we will explore in detail how to configure your S3 buckets to allow access only to users who have authenticated through MFA or SSO with MFA authentication. By the time we’re done, you’ll be well-equipped to bolster your AWS security posture and ensure that your S3 buckets are protected from unauthorized access.</p><p>So, fasten your seatbelts as we embark on this journey to fortify your AWS environment and safeguard your digital assets. We’re about to dive deep into the world of MFA and SSO authentication, empowering you with the expertise to secure your AWS S3 resources like a seasoned professional.</p><h3>Applying the Policy to Your S3 Bucket</h3><p>Now that we’ve crafted a robust IAM policy enforcing Multi-Factor Authentication (MFA) or Single Sign-On (SSO) with MFA authentication, it’s time to apply this policy to your AWS S3 bucket. This step is crucial to ensure that only authorized users with the appropriate authentication credentials can access your valuable data.</p><h4>Step 1: Navigate to Your S3 Bucket</h4><p>Log in to your AWS Management Console with the appropriate credentials.</p><p>From the AWS dashboard, navigate to the S3 service.</p><p>Select the specific S3 bucket to which you want to apply the IAM policy. Keep in mind that you should have the necessary IAM permissions to make changes to the bucket’s access policies.</p><h4>Step 2: Access Permissions Configuration</h4><p>Once you’ve selected the desired bucket, click on the “Permissions” tab. Here, you’ll be able to manage the bucket’s access control settings.</p><h4>Step 3: Edit Bucket Policy</h4><p>Under the “Permissions” tab, you’ll see several sections related to access control. Look for the “Bucket Policy” section and click on “Edit.”</p><h4>Step 4: Paste Your IAM Policy</h4><p>In the policy editor, paste the IAM policy listed below. This policy explicitly specifies that only authenticated users with MFA or SSO-MFA authentication are granted access. Be careful when pasting the policy to ensure there are no formatting errors. Remember to replace the your-bucket-name.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Deny&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: &quot;*&quot;<br>            },<br>            &quot;Action&quot;: [<br>                &quot;s3:ListBucket&quot;,<br>                &quot;s3:PutObject&quot;,<br>                &quot;s3:GetObject&quot;,<br>                &quot;s3:DeleteObject&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::your-bucket-name&quot;,<br>                &quot;arn:aws:s3:::your-bucket-name/*&quot;<br>            ],<br>            &quot;Condition&quot;: {<br>                &quot;Null&quot;: {<br>                    &quot;aws:MultiFactorAuthPresent&quot;: &quot;true&quot;<br>                }<br>            }<br>        }<br>    ]<br>}</pre><p>You can also upload the policy using the CLI, assuming you are logged in with enough permissions:</p><pre>$ aws s3api create-bucket --bucket your-bucket-name --region us-east-1<br>{<br>    &quot;Location&quot;: &quot;/your-bucket-name&quot;<br>}<br>$ aws s3api put-bucket-policy --bucket your-bucket-name --policy file://bucket_require_mfa_policy.json</pre><p>Remember to save the above policy to <a href="https://raw.githubusercontent.com/wdoganowski/cloud-chronicles/adf6a50e57faa2697f3e6a68a6729e4b218fc929/04.%20Securing%20Your%20AWS%20S3%20Bucket-%20Enforcing%20MFA%20or%20SSO%20Authentication/bucket_require_mfa_policy.json">bucket_require_mfa_policy.json</a> file.</p><p>Note that you can employ an MFA condition in a policy to assess the following attributes:</p><p>Presence — to confirm that the user has authenticated using MFA, you can verify the existence of the aws:MultiFactorAuthPresent key by employing a Boolean condition. This key is exclusively present when the user has authenticated using short-term credentials. It is important to note that long-term credentials, such as access keys, do not include this key.</p><p>Duration — if your objective is to permit access only within a specified time frame after MFA authentication, you can utilize a numeric condition type to compare the age of the aws:MultiFactorAuthAge key to a specified value (e.g., 3600 seconds). It&#39;s worth mentioning that the aws:MultiFactorAuthAge key is absent if MFA has not been utilized.</p><h4>Step 5: Test the Configuration</h4><p>Before your setup is complete, it’s essential to test the configuration thoroughly. Try accessing the S3 bucket with different IAM user accounts and confirm that only those with MFA or SSO-MFA authentication can access the contents. This testing phase ensures that your security measures are functioning as intended.</p><p><strong>Testing using SSO user</strong></p><p>To test the configuration using the CLI, you can first log in to the account having full access to S3 using SSO. Ensure you log in using MFA (this is the standard practice) and you will be able to access your test bucket without any issues.</p><pre>$ aws sso login --profile your-profile</pre><p>Follow the login process. Then you can try to upload a test file:</p><pre>$ touch testfile.txt<br>$ aws s3 cp testfile.txt s3://your-bucket-name<br>upload: ./testfile.txt to s3://your-bucket-name/testfile.txt</pre><p>There should be no error displayed.</p><p><strong>Testing using the user without MFA enabled</strong></p><p>Now create a user with full S3 access but without MFA enabled. Accessing the bucket by this user should not be allowed.</p><p>The following are required commands.</p><pre>$ aws iam create-user --user-name test-user<br>{<br>    &quot;User&quot;: {<br>        &quot;Path&quot;: &quot;/&quot;,<br>        &quot;UserName&quot;: &quot;test-user&quot;,<br>        &quot;UserId&quot;: &quot;XXXXXXXXXXXXXXXXXXXXX&quot;,<br>        &quot;Arn&quot;: &quot;arn:aws:iam::123456789000:user/test-user&quot;,<br>        &quot;CreateDate&quot;: &quot;2023-10-07T18:27:07+00:00&quot;<br>    }<br>}<br>$ aws iam attach-user-policy --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess --user-name test-user<br>$ aws iam create-access-key --user-name test-user<br>{<br>    &quot;AccessKey&quot;: {<br>        &quot;UserName&quot;: &quot;test-user&quot;,<br>        &quot;AccessKeyId&quot;: &quot;XXXXXXXXXXXXXXXXXXXXX&quot;,<br>        &quot;Status&quot;: &quot;Active&quot;,<br>        &quot;SecretAccessKey&quot;: &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;,<br>        &quot;CreateDate&quot;: &quot;2023-10-07T18:28:27+00:00&quot;<br>    }<br>}</pre><p>Create a profile for the test user and use the access keys generated earlier</p><pre>$ aws configure --profile test-user<br>AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXXX<br>AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX<br>Default region name [None]: us-east-1<br>Default output format [None]: json</pre><p>Now try to upload the testfile.txt using the test-user account:</p><pre>$ aws s3 cp testfile.txt s3://your-bucket-name --profile test-user<br>upload failed: ./testfile.txt to s3://your-bucket-name/testfile.txt An error occurred (AccessDenied) when calling the PutObject operation: Access Denied</pre><p>Note the operation failed.</p><p><strong>Testing using the user with MFA enabled</strong></p><p>First, we need to create a virtual MFA device:</p><pre>$ aws iam create-virtual-mfa-device --virtual-mfa-device-name test-user-mfa-device --outfile qr.png --bootstrap-method QRCodePNG<br>{<br>    &quot;VirtualMFADevice&quot;: {<br>        &quot;SerialNumber&quot;: &quot;arn:aws:iam::123456789000:mfa/test-user-mfa-device&quot;<br>    }<br>}</pre><p>This command will create the qr.png with the QR code and return the ARN of the virtual device. You need to display the qr.png and scan it with e.g. Google Authenticator. Remember to delete the qr.pnp after it has been used.</p><p>Once you’ve generated a fresh virtual MFA device, you have the option to link it to a user using enable-mfa-device. This command ensures synchronization with AWS by incorporating the initial two codes in sequence from the virtual MFA device.</p><pre>$ aws iam enable-mfa-device --user-name test-user --serial-number arn:aws:iam::123456789000:mfa/test-user-mfa-device --authentication-code1 448283 --authentication-code2 032162</pre><p>Finally, we can acquire the temporary session for the test-user logged-in with MFA. Of course, you need to replace the codes and the token with your own values from the authenticator app.</p><pre>$ aws sts get-session-token --serial-number arn:aws:iam::123456789000:mfa/test-user-mfa-device --token-code 567843 --profile test-user<br>{<br>    &quot;Credentials&quot;: {<br>        &quot;AccessKeyId&quot;: &quot;XXXXXXXXXXXXXXXXXXXXX&quot;,<br>        &quot;SecretAccessKey&quot;: &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;,<br>        &quot;SessionToken&quot;: &quot;XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&quot;,<br>        &quot;Expiration&quot;: &quot;2023-10-08T07:27:46+00:00&quot;<br>    }<br>}<br>$ export AWS_ACCESS_KEY_ID=XXXXXXXXXXXXXXXXXXXXX<br>$ export AWS_SECRET_ACCESS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX<br>$ export AWS_SESSION_TOKEN=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</pre><p>Now, attempt to upload a file from the AWS CLI again, without specifying the profile. You can log out from SSO to ensure that you are using the temporary session. On top, you can call get-caller-idendity to double-check.</p><pre>$ aws sso logout<br>$ aws sts get-caller-identity<br>{<br>    &quot;UserId&quot;: &quot;XXXXXXXXXXXXXXXXXXXXX&quot;,<br>    &quot;Account&quot;: &quot;123456789000&quot;,<br>    &quot;Arn&quot;: &quot;arn:aws:iam::123456789000:user/test-user&quot;<br>}<br>$ aws s3 cp testfile.txt s3://your-bucket-name<br>upload: ./testfile.txt to s3://your-bucket-name/testfile.txt</pre><p>Full success.</p><p>By following these steps, you’ve successfully applied a stringent IAM policy to your AWS S3 bucket, ensuring that only authenticated users with MFA or SSO-MFA authentication can access your data. This granular control over access helps fortify your cloud security, making it significantly more challenging for unauthorized users to breach your S3 bucket.</p><h3>Testing and Verification in Production Environment</h3><p>Now that we’ve configured your AWS S3 bucket to enforce Multi-Factor Authentication (MFA), it’s crucial to thoroughly test and verify the setup. This phase ensures that your security measures are effective and that only authorized users gain access.</p><h4>User Testing</h4><p>Begin by selecting a few representative users from your organization. These users should have the necessary permissions to access the S3 bucket.</p><p>Ask these users to log in and attempt to access the S3 bucket. Make sure they follow the MFA or SSO-MFA authentication process as required.</p><p>Verify that users who haven’t completed the MFA or SSO-MFA authentication process are denied access to the S3 bucket.</p><h4>Access Logging</h4><p>Enable access logging for your S3 bucket, if it’s not already enabled. This allows you to monitor who is attempting to access your bucket.</p><p>Review the access logs to confirm that only authenticated users with MFA or SSO-MFA authentication are successfully accessing the bucket. Look for any unauthorized access attempts or anomalies.</p><h4>Periodic Testing</h4><p>Regularly conduct testing and verification to ensure the continued effectiveness of your security setup. As your organization evolves, so may your user base and access requirements.</p><p>By diligently testing and verifying your MFA and SSO-MFA authentication setup, you can be confident that your S3 bucket remains protected against unauthorized access. Regular monitoring and periodic testing are essential components of a robust security strategy.</p><h3>Additional Considerations</h3><p>In addition to the core implementation steps, there are several best practices and further considerations to enhance your AWS S3 bucket security:</p><ol><li>Regular Policy Reviews Regularly review and update your IAM policies to align with changing security requirements. This proactive approach ensures that your security measures remain effective over time.</li><li>Logging and Monitoring Implement robust logging and monitoring practices. Set up alerts to notify you of any suspicious activity in your S3 bucket, such as repeated failed access attempts.</li><li>Least Privilege Principle Follow the principle of least privilege when assigning permissions. Only grant users and applications the minimum access necessary to perform their tasks, reducing the potential attack surface.</li><li>Auditing and Compliance Consider conducting regular security audits and assessments to ensure compliance with industry regulations and internal security standards.</li><li>Multi-Layered Security Implement a multi-layered security approach that includes encryption, access controls, and regular backups to safeguard your data comprehensively.</li></ol><p>By incorporating these best practices and additional considerations into your AWS S3 bucket security strategy, you can fortify your defenses and stay resilient against evolving security threats.</p><h3>Conclusions</h3><p>In this journey toward securing your AWS S3 bucket with Multi-Factor Authentication (MFA) and Single Sign-On (SSO) with MFA authentication, you’ve acquired valuable insights and practical knowledge. Let’s recap the key takeaways:</p><p>Security Imperative: The need to secure your S3 buckets cannot be overstated, given the potential risks and consequences of unauthorized access.</p><p>Shared Responsibility: In the AWS cloud, security is a shared responsibility between AWS and customers. You play a pivotal role in securing your data.</p><p>MFA and SSO-MFA: Multi-Factor Authentication (MFA) and Single Sign-On with MFA authentication are powerful tools to enhance security.</p><p>Configuration and Testing: Configuring your IAM policies, testing user access, and verifying security measures are critical steps.</p><p>Troubleshooting: Be prepared to troubleshoot common issues that may arise during implementation.</p><p>Best Practices: Embrace best practices, including policy reviews, logging, least privilege, auditing, and a multi-layered security approach.</p><p>As an AWS Solution Architect Associate, you now have the expertise to secure your AWS S3 resources with confidence. Remember that security is an ongoing process, and staying vigilant is key to protecting your digital assets in the ever-evolving cloud landscape. Continue to adapt and refine your security strategy to address emerging threats and safeguard your organization’s data and reputation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b258a330caf" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/step-by-step-tutorial-how-to-secure-aws-s3-with-mfa-and-sso-0b258a330caf">Step-by-Step Tutorial: How to Secure AWS S3 with MFA and SSO</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Visual Studio Code for CLI and Python tasks on AWS — part 4 — VSCode extensions]]></title>
            <link>https://awstip.com/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-4-vscode-extensions-aebd1d551bb1?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/aebd1d551bb1</guid>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 13:17:58 GMT</pubDate>
            <atom:updated>2023-05-08T17:00:21.067Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Use Visual Studio Code for CLI and Python tasks on AWS — part 4 — VSCode extensions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Jpcke2LJaHMDgxY.png" /></figure><p>In the first part of this article <a href="https://medium.com/@dogan1971/using-vscode-for-cli-and-python-tasks-on-aws-part-1-8cbcd907eb2">Ue Visual Studio Code for CLI and Python tasks on AWS — part 1</a> I have covered the installation of Python3 and Visual Studio Code. In the second part <a href="https://medium.com/@dogan1971/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a">Use Visual Studio Code for CLI and Python tasks on AWS — part 2 — CLI</a> I have covered the installation and configuration of AWS CLI. In the third part <a href="https://medium.com/@dogan1971/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-3-boto3-2d1f647ed95b">Use Visual Studio Code for CLI and Python tasks on AWS — part 3 — Boto3</a> I have covered the installation of the Boto3 library. Finally, let’s add some useful extensions.</p><h3>Visual Studio Code extensions</h3><p>The Visual Studio Code extensions provide a powerful way to customize and enhance VS Code for specific programming languages, workflows, and development environments.</p><p>I suggest installing the <a href="https://marketplace.visualstudio.com/items?itemName=donjayamanne.python-extension-pack">Python Extension Pack</a>, which is a collection of extensions for Visual Studio Code that is focused on Python development. The extension pack includes several popular extensions for Python developers, such as:</p><ol><li>Python — Linting, Debugging (multi-threaded, remote), Intellisense, code formatting, refactoring, unit tests, snippets, Data Science (with Jupyter), PySpark, and more.</li><li>Jinja — Jinja template language support for Visual Studio Code.</li><li>Django — Beautiful syntax and scoped snippets for perfectionists with deadlines.</li><li>Visual Studio IntelliCode — Provides AI-assisted productivity features for Python developers in Visual Studio Code with insights based on understanding your code combined with machine learning.</li><li>Python Environment Manager — Provides the ability to view and manage all of your Python environments &amp; packages from a single place.</li><li>Python Docstring Generator — Quickly insert Python comment blocks with contextually inferred parameters for classes and methods based on multiple, selectable template patterns.</li><li>Python Indent — Correct Python indentation in Visual Studio Code.</li><li>Jupyter — Provides Jupyter notebook support for Python language, used for data science, scientific computing, and machine learning.</li></ol><p>As you can see the Python Extension Pack provides a convenient way for Python developers to quickly set up a productive development environment in Visual Studio Code</p><h3>Installing Python Extension Pack</h3><p>To install the Python Extension Pack in Visual Studio Code, you can follow these steps:</p><ol><li>In Visual Studio Code click on the <em>Extensions</em> icon on the left-hand side of the window, or press Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS) to open the Extensions view.</li><li>In the search bar, type <em>Python Extension Pack</em> and press Enter.</li><li>The extension pack should appear in the search results. Click on the <em>Install</em> button to install it.</li><li>After installation, you may be prompted to reload VSCode for the changes to take effect. If so, click on the <em>Reload</em> button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XLbl_8IShEDn0-kv.png" /><figcaption>Python Extension Pack</figcaption></figure><p>That’s it! The Python Extension Pack is now installed and ready to use in Visual Studio Code. You can start using the Python-specific features and functionality provided by the extensions included in the pack.</p><h3>Installing autopep8 extension</h3><p>The <em>autopep8</em> extension for Visual Studio Code is a tool that automatically formats Python code to conform to the PEP8 style guide described here <a href="https://peps.python.org/pep-0008/">https://peps.python.org/pep-0008/</a>.</p><p>PEP8 is a set of guidelines for writing Python code that was developed by Guido van Rossum, the creator of Python, along with other Python developers. PEP stands for <em>Python Enhancement Proposal</em>, and PEP8 is one such proposal that was created to provide a consistent and standardized approach to writing Python code.</p><p>PEP8 covers a wide range of topics related to Python code style, including indentation, line length, naming conventions, comments, and more. The guidelines are designed to make Python code more readable and easier to understand, both for the original author and for other developers who may need to work with the code in the future.</p><p>Following the PEP8 guidelines is not mandatory, but it is considered a best practice for Python development. Adhering to the guidelines can help improve the readability and maintainability of your code, and can make it easier for other developers to collaborate with you on your projects. There are also many tools and extensions available that can automatically check your code for PEP8 compliance, such as the <em>pycodestyle</em> and <em>flake8</em> tools.</p><p>When you open a Python file in Visual Studio Code and save it, the <em>autopep8</em> extension automatically formats the code in accordance with the pep8 style guide. This includes things like indentations, spacing, line breaks, and more.</p><p>To install the autopep8 in Visual Studio Code, you can follow these steps:</p><ol><li>In Visual Studio Code click on the <em>Extensions</em> icon on the left-hand side of the window, or press Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS) to open the Extensions view.</li><li>In the search bar, type <em>autopep8</em> and press Enter.</li><li>The extension pack should appear in the search results. Click on the <em>Install</em> button to install it.</li></ol><p>Using the <em>autopep8</em> extension can help ensure that your Python code is consistent, easy to read, and conforms to best practices. It can also save you time by automating the process of formatting your code. To format the document using autopep8, you can do this by using the context menu (right-click on an open Python file in the editor) and selecting <em>Format Document With…</em>.</p><h3>Installing Python Snippets Pack</h3><p>The <em>Python Snippets Pack</em> is a collection of pre-written code snippets that can be used in Python programming. These snippets are designed to save time and effort when writing Python code, as they provide templates or examples of commonly used code patterns or functions.</p><p>Once installed, the extension provides a collection of Python snippets that can be accessed through the Visual Studio Code editor’s IntelliSense feature.</p><p>Some examples of snippets included in the Python Snippets Pack are:</p><ul><li><em>for</em> loop: Creates a basic for loop structure.</li><li><em>if</em> statement: Creates a basic if/else statement structure.</li><li><em>try</em> statement: Creates a basic try/except statement structure.</li><li><em>function</em>: Creates a basic function definition structure.</li></ul><p>Using these snippets can save time and reduce the amount of typing required when writing Python code, especially for common code patterns that are used frequently.</p><p>To install the Python Snippets Pack in Visual Studio Code, you can follow these steps:</p><ol><li>In Visual Studio Code click on the <em>Extensions</em> icon on the left-hand side of the window, or press Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS) to open the Extensions view.</li><li>In the search bar, type <em>python snippets</em> and press Enter.</li><li>The extension pack should appear in the search results. Click on the <em>Install</em> button to install it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*VM_1dQUnUeFAOj2Y.png" /></figure><h3>Installing AWS extension</h3><p>The AWS Toolkit for Visual Studio Code is an extension that provides a set of tools and features for developing, testing, and deploying applications on Amazon Web Services (AWS) from within the VSCode editor. The extension enables developers to work with a wide range of AWS services, including Lambda, DynamoDB, S3, and more.</p><p>Some of the key functionalities provided by the AWS Toolkit for VSCode include:</p><p>Create, configure, and deploy AWS resources: The extension provides wizards and templates to help you create and configure AWS resources, such as Lambda functions, API Gateway endpoints, and DynamoDB tables, directly from within the VSCode editor. You can also deploy your applications to AWS from within the editor, without having to switch to the AWS Management Console.</p><p>Debug AWS applications: The extension enables you to debug your AWS applications locally or remotely using the VSCode debugger. You can set breakpoints, inspect variables, and step through code as it executes on AWS.</p><p>Manage AWS credentials: The extension makes it easy to manage your AWS credentials and profiles directly from within the VSCode editor. You can configure multiple AWS profiles and easily switch between them as needed.</p><p>Monitor AWS resources: The extension provides real-time monitoring and logging of your AWS resources, allowing you to quickly identify and troubleshoot issues.</p><p>Work with AWS CDK: The extension supports AWS Cloud Development Kit (CDK), a framework for defining cloud infrastructure using code. You can use the extension to generate, deploy, and manage CDK applications directly from within VSCode.</p><p>To install the AWS Toolkit in Visual Studio Code, you can follow these steps:</p><ol><li>In Visual Studio Code click on the <em>Extensions</em> icon on the left-hand side of the window, or press Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (macOS) to open the Extensions view.</li><li>In the search bar, type <em>aws toolkit</em> and press Enter.</li><li>The extension pack should appear in the search results. Click on the <em>Install</em> button to install it.</li><li>Select the <em>AWS</em> icon from the left menu.</li><li>In the AWS Explorer choose to <em>Select a</em> <em>connection…</em> and then follow the instructions.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*p1CSD8GoZ2UuS3YH.png" /></figure><p>In case you followed the instruction from <a href="https://medium.com/@dogan1971/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a">Using Visual Studio Code for CLI and Python tasks on AWS — part 2 — AWS CLI</a>, you can use the IAM Identity Center user you created before. Otherwise, if you have decided to use the key pair, you can select the IAM credentials.</p><p>There is also one more option to use the AWS Builder ID, which I do not cover here.</p><p>Once connected, you can explore the AWS resources in the AWS Explorer panel.</p><h3>Installing Genie AI — ChatGPT</h3><p>The <em>Genie AI</em> extension for Visual Studio Code is a tool that provides AI-powered code completions and suggestions based on the context of your code. It uses machine learning algorithms to analyze your code and provide relevant suggestions for code completion, helping you to write code faster and with fewer errors.</p><p>The Genie AI extension uses a deep learning model to understand the semantics of your code, and it can provide code completions for a wide range of programming languages, including Python, JavaScript, TypeScript, and more. It can also suggest code snippets and templates based on your current code, making it easier to write code that follows best practices and design patterns.</p><p>To use the Genie AI extension, you need to have an API key, which can be obtained by signing up for an Open AI account. The key can be generated here <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a>. When you try to use the extension the first time, it will prompt for the API key and once it has been provided, you can install the extension in Visual Studio Code and configure it to use your API key. The extension will then start providing code completions and suggestions as you write code in your preferred programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3wLa6pNKblUz_3vx.png" /></figure><p>The Genie AI extension has several use cases:</p><ol><li>Code completion: Genie AI uses machine learning algorithms to analyze your code and provide relevant suggestions for code completion. This can help you write code faster and with fewer errors.</li><li>Code generation: Genie AI can suggest code snippets and templates based on your current code, making it easier to write code that follows best practices and design patterns.</li><li>Debugging assistance: Genie AI can assist with debugging code, by identifying errors and suggesting fixes.</li><li>Documentation: Genie AI can suggest documentation for code elements, such as functions or classes, making it easier to understand how to use them.</li><li>Refactoring: Genie AI can suggest ways to improve your code, such as by identifying duplicated code or suggesting better variable names.</li><li>Learning: Genie AI can help developers learn new programming concepts and techniques by providing relevant code examples and explanations.</li></ol><p>Overall, the Genie AI extension can help you save time and improve the quality of your code by providing intelligent code suggestions and assistance within the VSCode editor.</p><p>Now you can work with Visual Studio Code to learn AWS and Python. I hope this environment works for you and will be very useful. You can try developing and deploying Python applications to AWS e.g. Lambda functions. Serverless architectures are becoming increasingly popular, and VSCode has excellent support for Lambda functions and other serverless services on AWS.</p><p>I suggest you explore further, e.g. by adding AWS Serverless Application Model (SAM) CLI. It is an open-source framework that allows developers to easily build and deploy serverless applications on AWS, using AWS Lambda, Amazon API Gateway, Amazon DynamoDB, and other services. SAM provides a simplified way of defining the resources needed for your application, including APIs, database tables, and event sources, as well as the code for your Lambda functions. With SAM, you can test your serverless applications locally before deploying them to AWS, and you can use popular tools like Visual Studio Code for development and debugging.</p><p>Keep exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aebd1d551bb1" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-4-vscode-extensions-aebd1d551bb1">Use Visual Studio Code for CLI and Python tasks on AWS — part 4 — VSCode extensions</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Visual Studio Code for CLI and Python tasks on AWS — part 3 — Boto3]]></title>
            <link>https://awstip.com/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-3-boto3-2d1f647ed95b?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d1f647ed95b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 10:49:51 GMT</pubDate>
            <atom:updated>2023-05-15T16:50:45.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use Visual Studio Code for CLI and Python tasks on AWS — part 3 — Boto3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysatEIMqWaXuSB5sK4fXkw.png" /><figcaption>Visual Studio Code example</figcaption></figure><p>In the first part of this article <a href="https://medium.com/@dogan1971/using-vscode-for-cli-and-python-tasks-on-aws-part-1-8cbcd907eb2">Use Visual Studio Code for CLI and Python tasks on AWS — part 1</a> I have covered the installation of Python3 and Visual Studio Code. In the second part <a href="https://medium.com/@dogan1971/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a">Use Visual Studio Code for CLI and Python tasks on AWS — part 2</a> I have covered the installation and configuration of AWS CLI. Now let’s install the Boto3 library, so we will be able to connect to AWS resources from Python code.</p><h3>AWS SDK for Python (Boto3)</h3><p>Boto3 is the AWS Software Development Kit (SDK) for Python, which allows developers to write Python scripts to interact with AWS services programmatically. Here are some of the main use cases for Boto3:</p><p>Automating AWS infrastructure: Boto3 can be used to automate the creation, modification, and deletion of AWS resources, such as EC2 instances, S3 buckets, and RDS databases. This can save time and reduce errors that can occur when creating and managing resources manually.</p><p>Data processing and analysis: Boto3 can be used to retrieve data from AWS services, such as S3, DynamoDB, and Kinesis, and process it using Python libraries and tools, such as NumPy and Pandas. This can be useful for performing data analysis, machine learning, and other tasks that require processing large amounts of data.</p><p>DevOps automation: Boto3 can be used to automate tasks related to DevOps, such as deploying code to AWS services using tools like CodeDeploy and CodePipeline. This can streamline the deployment process and reduce the time and effort required to deploy code to AWS.</p><p>Cloud management and monitoring: Boto3 can be used to manage and monitor AWS services, such as CloudWatch, CloudFormation, and AWS Config. This can help ensure that AWS resources are running smoothly and within expected parameters and can help identify issues before they become critical.</p><h3>Install Boto3 on macOS</h3><p>On macOS, if you followed the Python installation steps from the link provided above, you will have already installed the <em>pip3</em> package manager, so we just need to run the following command:</p><pre>pip3 install boto3</pre><p>It will install the Boto3 library.</p><h3>Install Boto3 on Ubuntu</h3><p>To install Boto3 on Linux, we need to install the <em>pip3</em> explicitly unless you have installed it already before. In the VSCode terminal window run:</p><pre>sudo apt-get install python3-pip<br>pip3 install boto3</pre><p>Above code will install the <em>pip3</em> package manager and then the Boto3 library.</p><h3>Install Boto3 on Windows</h3><p>In the case of Windows, the process is similar to macOS and the <em>pip3</em> package manager should come together with Python installation. Just run:</p><pre>pip3 install boto3</pre><p>OK, we have the CLI and Boto3 installed, we just need to test Boto3 in a real application. Create a new Python file named <em>boto_test.py</em> by selecting from <em>File</em> menu <em>New File…</em> and copy the following code to the window on the right side:</p><pre>import boto3<br><br># Retrieve the list of existing buckets<br>s3 = boto3.client(&#39;s3&#39;)<br>response = s3.list_buckets()<br><br># Output the bucket names<br>print(&#39;Existing buckets:&#39;)<br>for bucket in response[&#39;Buckets&#39;]:<br>    print(f&#39;  {bucket[_Name_]}&#39;)</pre><p>You should be asked to install the Python extension of Visual Studio Code. This is a good moment to do it, as we will need it to be able to run the Python code within the Visual Studio Code IDE. Just press install and after the installation is finished, close the <em>Extension: Python</em> file, which will open.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJ85WxaIcIbguBOYupHbkA.png" /><figcaption>Python extension prompt</figcaption></figure><p>Then save the file by selecting <em>Save</em> from the <em>File</em> menu and we are ready to run it by selecting <em>Run Without Debugging</em> from <em>Run</em> menu. You should see something similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WanvpIfhQjWGJ3N8nhMw-w.png" /><figcaption>Example of Boto3 Python code</figcaption></figure><p>Remember to log in to AWS SSO, otherwise, you will receive the following error:</p><pre>botocore.exceptions.SSOTokenLoadError: Error loading SSO Token: Token for my-sso does not exist</pre><p>Up to now, we have the Python and Visual Studio Code installed together with two methods to access the AWS resources: AWS CLI and the Boto3 library. In the next part of this article — <a href="https://medium.com/@dogan1971/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-4-vscode-extensions-aebd1d551bb1">Use Visual Studio Code for CLI and Python tasks on AWS — part 4</a> — we will add some fun extensions, which maybe are not crucial, but help in the daily tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d1f647ed95b" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-3-boto3-2d1f647ed95b">Use Visual Studio Code for CLI and Python tasks on AWS — part 3 — Boto3</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Visual Studio Code for CLI and Python tasks on AWS — part 2 — AWS CLI]]></title>
            <link>https://awstip.com/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a?source=rss-7fc0c9d83b9f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2e324f122a</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[identity]]></category>
            <dc:creator><![CDATA[Wojciech (Dogan) Doganowski]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 12:02:43 GMT</pubDate>
            <atom:updated>2025-02-04T07:10:00.403Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Use Visual Studio Code for CLI and Python tasks on AWS — part 2 — AWS CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yCazhXyAEmdlDt1i.png" /></figure><p>In the first part of this article <a href="https://medium.com/@dogan1971/using-vscode-for-cli-and-python-tasks-on-aws-part-1-8cbcd907eb2">Use Visual Studio Code for CLI and Python tasks on AWS — part 1</a> I have covered the installation of Python3 and Visual Studio Code. Now we will focus on the installation of AWS CLI. Thanks to this, we will be able to connect to AWS resources from our local machine.</p><h3>AWS CLI</h3><p>The AWS CLI (Command Line Interface) is a powerful tool for managing your AWS resources and services through a command-line interface. It allows you to interact with AWS resources using commands in your terminal (or Command Prompt on Windows) rather than using the AWS Management Console or SDK.</p><p>The AWS CLI can be useful in a variety of scenarios, including:</p><p>Automating repetitive tasks: If you have to perform the same AWS-related tasks regularly, you can use the AWS CLI to automate these tasks by writing scripts that perform the required actions.</p><p>Developing and testing applications: Developers can use the AWS CLI to test and deploy their applications using scripts or automation tools. This can help streamline the development and deployment process.</p><p>Managing AWS resources in a serverless environment: The AWS CLI is especially useful for managing AWS resources in a serverless environment, where you might be creating and deploying Lambda functions, API Gateway, S3 buckets, and other serverless components using the AWS CLI.</p><p>Managing AWS resources across multiple accounts and regions: With the AWS CLI, you can manage AWS resources across multiple accounts and regions using a single tool, making it easy to automate and manage complex AWS environments.</p><p>Integrating with other tools and services: The AWS CLI can be integrated with other tools and services, such as Jenkins, Git, and Docker, to automate the deployment and management of AWS resources in these environments.</p><h3>Install AWS CLI on macOS</h3><p>If you have <em>sudo</em> permissions, you can install the AWS CLI for all users on the computer:</p><pre>curl &quot;https://awscli.amazonaws.com/AWSCLIV2.pkg&quot; -o &quot;AWSCLIV2.pkg&quot;<br>sudo installer -pkg AWSCLIV2.pkg -target /</pre><p>In case you are not able to do this, you can follow the instructions from AWS: <a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html</a>.</p><h3>Install AWS CLI on Ubuntu</h3><p>Just run:</p><pre>sudo apt install awscli</pre><h3>Install AWS CLI on Windows</h3><p>Download the MSI installer from the official website: <a href="https://aws.amazon.com/cli/">https://aws.amazon.com/cli/</a> and run the installer. Make sure to select <em>Add Python to environment variables</em> during the installation process.</p><h3>Configure AWS access</h3><p>Before we can use AWS CLI we need to set up the necessary configuration settings to communicate with the AWS services. There are two methods of achieving this. First is to use the <em>access key ID</em> and <em>secret access key,</em> however this is not recommended anymore. Instead, we can enable authentication through a user in IAM Identity Center.</p><h3>Configuring AWS access using IAM Identity Center (recommended)</h3><p>To configure AWS CLI to authenticate through a user in IAM Identity Center, you need to have to enable access through the IAM Identity Center. You can follow my article <a href="https://github.com/wdoganowski/cloud-chronicles/blob/main/02.%20Easier%20access%20to%20your%20accounts%20with%20IAM%20Identity%20Center/README.md">Easier access to multiple accounts with IAM Identity Center</a>.</p><h4>Creating PowerUser</h4><p>Once you established access through IAM Identity Center, you can follow these steps:</p><ol><li>Log in to the AWS Management Console using your AWS account credentials. If you have multiple accounts, ensure you are logging into your management account using the root user.</li><li>Navigate to the IAM Identity Center by clicking on the <em>Services</em> dropdown in the top left corner, selecting <em>IAM Identity Center (successor to AWS Single Sign-On)</em> under <em>Security, Identity &amp; Compliance</em>. Alternatively, you can type <em>IAM Identity Center</em> in the services search prompt. Create a new permission set that grants PowerUserAccess permissions:</li></ol><ul><li>Click on the <em>Create new permission set</em> button in the upper right-hand corner of the page.</li><li>Select <em>Predefined permission set</em> as the type of permission set.</li><li>Select <em>PowerUserAccess</em> as the predefined permission set to create.</li><li>Enter a name and description for the permission set, if desired.</li><li>Review the details of the permission set, and click the <em>Create</em> button.</li></ul><p>3. Assign the newly created user to the account:</p><ul><li>Click on <em>AWS accounts</em> in the left panel. You should be presented with the list of the accounts.</li><li>Select the accounts you want to access.</li><li>Press <em>Assign users and groups</em> and select the <em>Users</em> tab.</li><li>Select the desired user and press <em>Next</em>.</li><li>Select the PowerUserAccess permission set and press <em>Next</em>.</li><li>Review and press <em>Submit</em>.</li></ul><blockquote><em>Unlike the administrative permission set, which uses AdministratorAccess permissions, the PowerUserAccess permission set doesn’t allow management of users and groups.</em></blockquote><h4>Configuring the profile with the AWS configure SSO wizard</h4><p>Once we have the user with PowerUserAccess permissions created, you can configure the AWS CLI using the following commands:</p><pre>$ aws configure sso <br>SSO session name (Recommended): my-sso<br>SSO start URL [None]: https://my-sso-portal.awsapps.com/start<br>SSO region [None]: eu-north-1<br>SSO registration scopes [None]: sso:account:access<br>Attempting to automatically open the SSO authorization page in your default <br>browser.<br>If the browser does not open or you wish to use a different device <br>to authorize this request, open the following URL:<br><br>https://device.sso.eu-north-1.amazonaws.com/<br>Then enter the code:</pre><p>You will see your browser opening and you will need to log in to your PowerUserAccess account. Then you will need to allow CLI (called botocore-client) to access AWS IAM Identity Center accounts and permission sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tgNE4awaCg9n3r1v.png" /></figure><p>After this, you will be presented with the account, to which you want to log in to your AWS CLI. You need to select one.</p><pre>SQTM-CXXB<br>There are 6 AWS accounts available to you.<br>&gt; Bootcamp (123456789011)                 <br>  Bootcamp-PROD (123456789012)       <br>  Backups (123456789013)                   <br>  BootcampSandbox (123456789014)   <br>  Wojciech Doganowski (123456789015)               <br>  Liczyrzepa-PROD (123456789016)</pre><p>After selecting the account, you will be prompted to which region you want the CLI to be logged in:</p><pre>Using the account ID 123456789011<br>The only role available to you is: PowerUserAccess<br>Using the role name &quot;PowerUserAccess&quot;<br>CLI default client Region [None]: eu-north-1<br>CLI default output format [None]: YAML<br>CLI profile name [PowerUserAccess-123456789011]:</pre><p>To use this profile, specify the profile name using — profile, as shown:</p><pre>$ aws s3 ls --profile PowerUserAccess-123456789011</pre><p>That’s it! You have now configured AWS CLI to authenticate through a user in IAM Identity Center using access keys. Let’s try to access S3:</p><pre>$ aws s3 ls --profile PowerUserAccess-123456789011<br>2023-04-01 19:24:29 python-session-1-dogan</pre><p>This results in creating the sso-session section and named profile in ~/.aws/config that looks like the following:</p><pre>[profile PowerUserAccess-123456789011]<br>sso_session = my-sso<br>sso_account_id = 123456789011<br>sso_role_name = PowerUserAccess<br>region = eu-north-1<br><br>[sso-session my-sso]<br>sso_start_url = https://my-sso-portal.awsapps.com/start<br>sso_region = eu-north-1<br>sso_registration_scopes = sso:account:access</pre><h4>Logging in with IAM Identity Center</h4><p>To be able to use the AWS CLI next time, you will need to login to SSO using the following command:</p><pre>aws sso login --profile PowerUserAccess-123456789011</pre><p>You will be asked to login into the browser window again, the same way as while creating the SSO account.</p><p>To avoid adding <em>— profile PowerUserAccess-123456789011</em> to each AWS CLI command, you can set the AWS_PROFILE variable in the following way:</p><p>On Linux or Mac:</p><pre>export AWS_PROFILE=PowerUserAccess-123456789011</pre><p>On Windows:</p><pre>SET AWS_PROFILE=PowerUserAccess-123456789011</pre><p>Then you can run AWS CLI commands like this:</p><pre>$ aws s3 ls<br>2023-04-01 19:24:29 python-session-1-dogan</pre><p>To logout the AWS CLI session, you need to use:</p><pre>aws sso logout</pre><p>You have configured the AWS CLI to use the IAM Identity Center as the SSO.</p><h3>Configuring AWS access using the access key (not recommended option)</h3><blockquote><em>It’s important to note that the </em>access key ID<em> and </em>secret access key<em> are sensitive information that should be kept secure. For that reason, we should avoid using them as if someone will get the access to this key pair, would have the same access to your account as you.</em></blockquote><p>Following are the steps to get the <em>access key ID</em> and <em>secret access key</em>:</p><ol><li>Log in to the AWS Management Console using your AWS account credentials.</li><li>Open the IAM console.</li><li>In the navigation pane, choose <em>Users</em>.</li><li>Select your IAM user name.</li><li>Choose the <em>Security credentials</em> tab.</li><li>Expand the <em>Access keys</em> section.</li><li>Choose the <em>Create access key</em> button.</li><li>Select <em>Command Line Interface (CLI)</em>.</li><li>Download and save the access key file.</li><li>Use the access key ID and secret access key from the file to complete the <em>aws configure</em> command.</li></ol><blockquote><em>Note that you should treat your access key ID and secret access key as sensitive information and keep them secure. Do not share them with others, and rotate them regularly to ensure the security of your AWS account.</em></blockquote><p>Configure the AWS CLI: Run the following command in the terminal or command prompt window: <em>aws configure</em>. This will launch a wizard that will guide you through the process of configuring the AWS CLI:</p><pre>$ aws configure<br>AWS Access Key ID [None]: ********************<br>AWS Secret Access Key [None]: ********************<br>Default region name [None]: us-east-1<br>Default output format [None]: YAML</pre><ol><li>Enter your AWS <em>access key ID</em> and <em>secret access key</em>: you will need to enter your access key ID and secret access key, which you have obtained from the AWS Management Console.</li><li>Choose your default region: You will need to choose a default region for the AWS CLI. This is the region that the CLI will use by default for all AWS services.</li><li>Choose your default output format: You will need to choose a default output format for the AWS CLI. This is the format that the CLI will use to display output from AWS services. You can choose between JSON and YAML or leave it empty, to let AWS decide.</li></ol><h3>Testing the CLI</h3><p>Test the AWS CLI: Once the AWS CLI is configured, you can test it by running a command such as <em>aws s3 ls</em>. This will list the contents of your default S3 bucket (assuming you have one).</p><pre>$ aws s3 ls<br>2023-04-01 19:21:39 python-session-1-dogan</pre><p>Great, we have the development IDE and the AWS CLI installed.</p><p>Up to now, we have the Python and Visual Studio Code installed together with AWS CLI. In the next part of this article — <a href="https://medium.com/@dogan1971/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-3-boto3-2d1f647ed95b">Use Visual Studio Code for CLI and Python tasks on AWS — part 3</a> — we will install the Boto3 library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2e324f122a" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/using-visual-studio-code-for-cli-and-python-tasks-on-aws-part-2-aws-cli-e2e324f122a">Use Visual Studio Code for CLI and Python tasks on AWS — part 2 — AWS CLI</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>