<?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 Andres Solorzano on Medium]]></title>
        <description><![CDATA[Stories by Andres Solorzano on Medium]]></description>
        <link>https://medium.com/@aosolorzano?source=rss-b15bb6bd7ea7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SpSoeWf8b1I7IkBZAxbRnQ.png</url>
            <title>Stories by Andres Solorzano on Medium</title>
            <link>https://medium.com/@aosolorzano?source=rss-b15bb6bd7ea7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:47:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aosolorzano/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[Beyond Control Tower: Customizing AWS Identity Center with CloudFormation and ABAC.]]></title>
            <link>https://aosolorzano.medium.com/beyond-control-tower-customizing-aws-identity-center-with-cloudformation-and-abac-758fcc8e5a6c?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/758fcc8e5a6c</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 21:41:43 GMT</pubDate>
            <atom:updated>2026-08-07T21:41:43.884Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2RmjQ0cE1GOcwV5dOt65UQ.png" /></figure><h3>Introducción.</h3><p>In our <a href="https://aosolorzano.medium.com/integrating-aws-identity-center-with-entra-id-for-enterprise-sso-5ef360cd5648">previous article</a>, we configured an integration with Entra ID for the IAM Identity Center service. Identity Center, in turn, was configured through a Landing Zone, which we discussed in <a href="https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">another article</a>. Now it’s time to personalize the Identity Center instance with custom resources based on our needs.</p><h4>Prerequisites.</h4><ol><li><strong>AWS CLI v2</strong> installed and configured.</li><li><strong>Identity Center</strong>: Please follow the <a href="https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">previous article</a> to configure a multi-account environment using Control Tower. You can use your manually created instance in Control Tower, but you will lose the remaining recommended configurations.</li></ol><h4>Source Code.</h4><p>You can download the source code used to implement the lab shown in this article in my <a href="https://github.com/aosolorzano/iac-aws-identity-center">GitHub repo</a>. I’m using <a href="https://kiro.dev/cli/">Kiro CLI</a> as an AI agent to help and guide me in some parts of the project, so you can see the Steering folder inside the project with the objective that you can add your own implementations and not start from scratch.</p><h3>What is IAM Identity Center?</h3><p>AWS IAM Identity Center is the recommended service for managing access to AWS accounts at scale. Instead of creating IAM users in each account, Identity Center provides a single entry point where users authenticate once and gain access to multiple accounts with the appropriate permissions.</p><p>The service sits on top of AWS Organizations and works with the account structure you already have. Once configured, users log in through a web portal or the AWS CLI, select the account they want to work in, and assume a temporary role. No long-lived credentials, no per-account IAM users to manage.</p><p>Identity Center organizes access around three concepts:</p><ul><li><strong>Permission-Sets</strong>: define what a user can do inside an account. Think of them as reusable IAM role templates that get deployed to target accounts automatically.</li><li><strong>Groups</strong>: containers for users that share the same functional role in your organization. You assign access to groups, not to individual users.</li><li><strong>Assignments</strong>: the link that connects a group, a Permission-Set, and a specific AWS account. One assignment says: this group gets this level of access in this account.</li></ul><p>This model keeps identity management centralized while enforcement happens locally in each account. When a user logs in and assumes a role, Identity Center creates a temporary session in the target account with exactly the permissions defined in the Permission-Set, scoped to that user, for a fixed duration.</p><h4>Where does the identity come from?</h4><p>Identity Center supports three identity sources:</p><ul><li><strong>Built-in Directory: </strong>users and groups managed directly in Identity Center.</li><li><strong>Active Directory</strong>: synchronized from AWS Managed Microsoft AD or a self-managed AD via AD Connector.</li><li><strong>External identity provider</strong>: federated via SAML 2.0 with providers like Microsoft Entra ID, Okta, or Google Workspace.</li></ul><p>The <a href="https://aosolorzano.medium.com/integrating-aws-identity-center-with-entra-id-for-enterprise-sso-5ef360cd5648">previous article</a> integrated Microsoft Entra ID as an external IdP. <strong><em>Entra ID handles authentication</em></strong>. It validates who the user is and issues a SAML assertion. <strong><em>Identity Center handles authorization</em></strong>. It reads that assertion, maps the user to their groups, and grants access to the right accounts with the right permissions.</p><h3>What Control Tower gives you out of the box.</h3><p>When you deploy a Landing Zone with AWS Control Tower, it does not just create OUs and accounts. It also configures a baseline in IAM Identity Center. This baseline is intentional: it gives the Management account operator enough access to operate the environment from day one, without requiring any manual Identity Center setup.</p><p>Here is what Control Tower creates automatically:</p><h4>Permission-Sets.</h4><p>Control Tower provisions several Permission-Sets that cover common access patterns:</p><ul><li><strong>AWSAdministratorAccess: </strong>full administrative access, based on the AWS-managed AdministratorAccess policy.</li><li><strong>AWSReadOnlyAccess: </strong>read-only access across all services.</li><li><strong>AWSPowerUserAccess: </strong>full access except IAM management.</li><li><strong>AWSOrganizationsFullAccess: </strong>for managing the organization structure.</li><li><strong>AWSServiceCatalogAdminFullAccess</strong> and <strong>AWSServiceCatalogEndUserAccess</strong>: for Account Factory operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPnjp3AqCn6ELNonipUhpA.png" /></figure><h4>Groups.</h4><p>Control Tower creates several groups and assigns the Management account user to them:</p><ul><li><strong>AWSControlTowerAdmins: </strong>assigned AWSAdministratorAccess to the Management account.</li><li><strong>AWSAccountFactory: </strong>assigned AWSServiceCatalogEndUserAccess to the Management account, used for provisioning accounts.</li><li><strong>AWSAuditAccountAdmins</strong>, <strong>AWSLogArchiveAdmins</strong>, <strong>AWSLogArchiveViewers</strong>, <strong>AWSSecurityAuditPowerUsers</strong>, <strong>AWSSecurityAuditors</strong>: for the Security OU accounts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zBCpDeAWDgcSYGjWWNs2YA.png" /></figure><h4>Account assignments.</h4><p>For each account created via Account Factory, Control Tower assigns the account’s SSO user to the <strong>AWSAdministratorAccess</strong> Permission-Set for that specific account. This is how worker users each have admin access to their respective accounts right after provisioning.</p><h4>What this means for your project.</h4><p>The Control Tower baseline covers the operator and the security accounts. It does not cover your team’s day-to-day access patterns. There are no groups for your developers, no Permission-Sets scoped, and no cross-environment access policies.</p><p>That gap is exactly what the Identity domain fills. The rule is simple: never modify or delete anything prefixed with AWS. Those resources belong to Control Tower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-NNEwb2dO2clJ8-8U-Yfg.png" /><figcaption>Contrast between AWS* groups (CT-managed) and project-managed groups after deployment.</figcaption></figure><h3>Designing group-based access for a multi-account environment.</h3><p>The costs associated with this domain come from the underlying services that Identity Center depends on or interacts with:</p><p><strong>AWS Organizations</strong>: no additional charge for using Organizations features (SCPs, RCPs, OUs). The accounts themselves may incur costs depending on what runs inside them.</p><p><strong>Microsoft Entra ID</strong>: the SAML 2.0 federation used in this article is available on the free tier of Entra ID (included with Office 365 Business Standard and above). SCIM provisioning, which would automate user and group synchronization, requires Entra ID P1.</p><p><strong>CloudTrail</strong>: Identity Center login events are recorded in CloudTrail. If you have a trail configured (which Control Tower sets up by default), standard CloudTrail pricing applies for management events.</p><p>In practice, for a small team using a single region, the identity layer adds no meaningful cost to the monthly AWS bill.</p><h3>Designing group-based access for a multi-account environment.</h3><p>Control Tower gives you a working baseline, but your team needs a model that reflects how your organization actually works, who owns which environment, and what level of access makes sense for each role.</p><h4>Why groups instead of direct user assignments.</h4><p>You could assign Permission-Sets directly to individual users. For a team of four, that might seem simpler, but it creates a maintenance problem: every time someone joins, leaves, or changes roles, you need to update individual assignments across multiple accounts. Groups decouple identity from access. You define the access policy once on the group, and membership drives who gets what.</p><p>This is also the foundation for scaling. When SCIM synchronization is available (it requires Entra ID P1), groups defined in your identity provider sync automatically to Identity Center. Even without SCIM, managing four groups is far more maintainable than managing per-user assignments as the team grows.</p><h4>Mapping teams to accounts.</h4><p>A useful starting point is to ask: which team owns which account? In a multi-account setup, each account tends to have a primary owner. The team responsible for what runs there. That ownership maps naturally to a group with full access in their account.</p><p>The more interesting design question is cross-environment access. Consider two teams that both need visibility across environments:</p><ul><li>Developers need to iterate freely in the development environment, but should not be able to accidentally change something in production (full access in Dev, read-only in Prod).</li><li>Operations manages what runs in production and needs full control there. But they also need to observe the development environment to validate changes before they reach production. Full access in Prod, read-only in Dev.</li></ul><p>This cross-environment pattern prevents accidental production changes while preserving full observability in both directions, a common requirement in environments where the same team does not own both Dev and Prod.</p><h4>Keeping your groups separate from Control Tower’s.</h4><p>One naming discipline worth establishing early: prefix all your project-owned resources so they are immediately distinguishable from what Control Tower manages. Control Tower uses AWS as a prefix for everything it creates. Your project should use a consistent prefix of your own.</p><p>This matters in practice because both sets of groups live in the same Identity Center instance. When you browse the Groups list, you need to know at a glance which ones are yours to manage and which ones belong to Control Tower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-NNEwb2dO2clJ8-8U-Yfg.png" /><figcaption>Showing the clear visual separation between CT-managed and project-managed groups.</figcaption></figure><h3>Permission Sets: from managed policies to custom ABAC.</h3><p>Permission Sets are where you define what a user can actually do once they are inside an account. The simplest approach is to attach an AWS managed policy (<strong>AdministratorAccess</strong> for full access, <strong>ReadOnlyAccess</strong> for audit) and call it done. For most roles, that is entirely sufficient.</p><p>The interesting case is when you need something in between: a role that can deploy and operate application resources, but cannot touch IAM, billing, or anything that could escalate privileges or generate unexpected costs. That is where a custom inline policy becomes necessary.</p><h4>Three tiers of access.</h4><p>A practical model for most multi-account environments uses three Permission-Sets:</p><ul><li><strong>Full admin</strong>: based on ‘AdministratorAccess’. Assigned to the teams that own their accounts (infrastructure engineers, platform engineers). They need unrestricted access to build and manage the environment.</li><li><strong>Service-scoped developer access</strong>: a custom inline policy that grants access to the services your developers actually use, with an explicit deny on IAM and billing. This is the most important Permission-Set to get right, and the one worth investing design time in.</li><li><strong>Read-only</strong>: based on ‘ReadOnlyAccess’. Assigned for cross-environment observability. Developers monitoring production, operations reviewing development. Anyone who needs to see but not touch.</li></ul><p>Session duration is worth configuring explicitly. Admin and developer sessions can be 8 hours to avoid interrupting long work sessions. Read-only sessions can be shorter (4 hours is a reasonable default for access that carries lower risk).</p><h4>Designing the developer policy.</h4><p>The goal of a service-scoped policy is to be permissive enough for real work while preventing the two most common categories of accidental damage: privilege escalation through IAM changes, and cost surprises from unintended resource creation.</p><p>A clean structure splits the policy into<strong> 4 statements</strong> with distinct purposes:</p><pre>Statement:<br><br>   # READ — unrestricted within allowed services<br>   - Sid: AllowReadPlatformServices<br>     Effect: Allow<br>     Action: [ read-only actions across all allowed services ]<br>     Resource: &#39;*&#39;<br><br>   # CREATE — enforced via request tag<br>   - Sid: AllowCreateOwnedResources<br>     Effect: Allow<br>     Action: [ creation actions ]<br>     Resource: &#39;*&#39;<br>     Condition:<br>       StringEquals:<br>         aws:RequestTag/owner: &#39;${aws:PrincipalTag/email}&#39;<br><br>   # MODIFY / DELETE — enforced via resource tag<br>   - Sid: AllowModifyOwnedResources<br>     Effect: Allow<br>     Action: [ update and delete actions ]<br>     Resource: &#39;*&#39;<br>     Condition:<br>       StringEquals:<br>         aws:ResourceTag/owner: &#39;${aws:PrincipalTag/email}&#39;<br><br>   # DENY — always active, regardless of ownership<br>   - Sid: DenyIAMAndBilling<br>     Effect: Deny<br>     Action: [ iam:*, billing:*, organizations:*, ... ]<br>     Resource: &#39;*&#39;</pre><ul><li><strong>Read operations are unrestricted</strong>: developers need full visibility for debugging and collaboration. Write operations are split into creation and modification, each with a different ABAC condition. The deny at the end is a hard guardrail that cannot be overridden by any allow statement.</li></ul><h4>ABAC: enforcing resource ownership.</h4><p>The ${aws:PrincipalTag/email}condition key is what makes this policy enforce ownership rather than just service scope. When a developer creates a resource, the policy requires the request to include an owner tag matching their email. When they modify an existing resource, the resource itself must carry that tag.</p><p>The result: developers have full autonomy within the allowed services, but only over resources they created. A developer cannot modify another developer’s Lambda functions or delete a DynamoDB table that belongs to someone else, not because of explicit denies, but because the resource tag does not match their session.</p><p>This pattern also creates a natural audit trail. Every resource carries the email of the person who created it, visible in the AWS console and queryable via the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXDTas5OOME5eZuxQMbBeA.png" /></figure><p>The four-statement policy structure showing the ABAC conditions:</p><pre>InlinePolicy:<br>  Version: &#39;2012-10-17&#39;<br>  Statement:<br>    <br>  # 1. READ — unrestricted within allowed services<br>  - Sid: AllowReadPlatformServices<br>    Effect: Allow<br>    Action:<br>      - lambda:Get*<br>      - lambda:List*<br>      - dynamodb:Get*<br>      - dynamodb:List*<br>      - dynamodb:Query<br>      # ... other read actions<br>    Resource: &#39;*&#39;<br>    <br>    # 2. CREATE — requires owner tag on the request<br>    - Sid: AllowCreateOwnedResources<br>      Effect: Allow<br>      Action:<br>        - lambda:CreateFunction<br>        - dynamodb:CreateTable<br>        # ... other creation actions<br>      Resource: &#39;*&#39;<br>      Condition:<br>        StringEquals:<br>          aws:RequestTag/owner: &#39;${aws:PrincipalTag/email}&#39;<br>    <br>    # 3. MODIFY / DELETE — requires owner tag on the existing resource<br>    - Sid: AllowModifyOwnedResources<br>      Effect: Allow<br>      Action:<br>        - lambda:UpdateFunctionCode<br>        - lambda:DeleteFunction<br>        - dynamodb:PutItem<br>        - dynamodb:DeleteTable<br>        # ... other modify/delete actions<br>      Resource: &#39;*&#39;<br>      Condition:<br>        StringEquals:<br>          aws:ResourceTag/owner: &#39;${aws:PrincipalTag/email}&#39;<br>    <br>    # 4. DENY — always active, regardless of resource ownership<br>    - Sid: DenyIAMAndBilling<br>      Effect: Deny<br>      Action:<br>        - iam:*<br>        - billing:*<br>        - organizations:*<br>        # ... other denied services<br>      Resource: &#39;*&#39;</pre><p>The ABAC conditions only work if the email attribute is actually injected into the session context. That setup is covered in the next section.</p><h3>Identity-enhanced sessions with an external IdP.</h3><p>The ABAC conditions in the previous section reference <strong>${aws:PrincipalTag/email}</strong>. For that condition key to have a value at runtime, something needs to inject the user’s email into the session context when they assume a role. That is what identity-enhanced sessions do.</p><h4>How it works.</h4><p>When a user logs in through Identity Center and selects an account, Identity Center creates a temporary IAM role session in that account. Identity-enhanced sessions allow you to configure attributes that get attached to that session as principal tags, key-value pairs that become available as condition keys in IAM policies.</p><p>You configure the mapping once at the Identity Center instance level: a tag key and the source attribute that should populate it. From that point on, every session created through Identity Center carries those tags automatically.</p><h4>The external IdP constraint.</h4><p>The configuration differs depending on your identity source. When using the built-in Identity Center directory, you can reference internal user attributes (including the user’s Identity Center ID) using the ${identitystore:UserId} prefix.</p><p>With an external identity provider like Entra ID, that prefix is not valid. The session context is built from the SAML assertion that the IdP sends during authentication, and only attributes available in that assertion can be used as sources.</p><p>The supported format for external IdP attributes follows the SCIM attribute path syntax:</p><p><strong>${path:emails[primary eq true].value}</strong> → primary email address.<br><strong>${path:givenName}</strong> → first name.<br><strong>${path:name.familyName}</strong> → last name.<br><strong>${path:userName}</strong> → username.</p><p>For the ownership pattern described in the previous section, the primary email is the right choice. It’s stable, unique per user, and available in every SAML assertion from Entra ID.</p><h4>Configuring the attribute mapping.</h4><p>The CLI command to enable identity-enhanced sessions checks whether a configuration already exists and either creates or updates it:</p><pre>ABAC_STATUS=$(aws sso-admin describe-instance-access-control-attribute-configuration \<br>  --instance-arn &quot;$INSTANCE_ARN&quot; \<br>  --region &quot;$REGION&quot; \<br>  --query &#39;InstanceAccessControlAttributeConfiguration.Status&#39; \<br>  --output text 2&gt;/dev/null || echo &quot;NOT_FOUND&quot;)<br><br>ABAC_CONFIG=&#39;{<br>  &quot;AccessControlAttributes&quot;: [<br>    {<br>      &quot;Key&quot;: &quot;email&quot;,<br>      &quot;Value&quot;: {<br>        &quot;Source&quot;: [&quot;${path:emails[primary eq true].value}&quot;]<br>      }<br>    }<br>  ]<br>}&#39;<br>  <br>if [ &quot;$ABAC_STATUS&quot; = &quot;NOT_FOUND&quot; ] || [ -z &quot;$ABAC_STATUS&quot; ]; then<br>  aws sso-admin create-instance-access-control-attribute-configuration \<br>    --instance-arn &quot;$INSTANCE_ARN&quot; \<br>    --instance-access-control-attribute-configuration &quot;$ABAC_CONFIG&quot; \<br>    --region &quot;$REGION&quot;<br>else<br>  aws sso-admin update-instance-access-control-attribute-configuration \<br>    --instance-arn &quot;$INSTANCE_ARN&quot; \<br>    --instance-access-control-attribute-configuration &quot;$ABAC_CONFIG&quot; \<br>    --region &quot;$REGION&quot;<br>fi</pre><p>The key value (email) becomes the principal tag key available in policies as ${aws:PrincipalTag/email}. The source is what Identity Center reads from the SAML assertion to populate that tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEqhUESGxBkeX9U-csiWKg.png" /><figcaption>Attributes for access control showing the email attribute configured.</figcaption></figure><h4>What this enables downstream.</h4><p>Once the attribute is configured, the ownership conditions in the developer policy become active. A session created for any user will carry their email as a principal tag, and the policy evaluates it automatically on every API call.</p><p>This also opens the door to more sophisticated patterns in future domains. For example, restricting access to infrastructure resources based on team membership, or enforcing data isolation at the resource level by requiring tags that match the caller’s organizational unit.</p><h3>CloudFormation templates: the three-layer model.</h3><p>One design decision in this implementation is splitting the Identity Center configuration across three separate CloudFormation stacks rather than putting everything in a single template. The separation follows the same logic as the access model itself. Each layer has a distinct purpose and evolves independently.</p><ul><li><strong>1-permission-sets.yaml</strong> → What users can do.</li><li><strong>2-groups.yaml</strong> → Who users are.</li><li><strong>3-assignments.yaml</strong> → Where users can go.</li></ul><h4>Why three stacks instead of one?</h4><p>A single template would work, but it creates operational friction. Consider what changes in practice:</p><ul><li><strong>You add a new service to the developer policy</strong>: only the Permission-Sets stack changes.</li><li><strong>A new team member joins</strong>: you update group membership in the script (CFN cannot manage memberships), but the stacks are untouched.</li><li><strong>You provision a new AWS account</strong>: you add an assignment in the assignments stack without touching permissions or groups.</li></ul><p>When stacks are independent, a change in one does not risk breaking the others. CloudFormation also enforces this at the export level. You cannot delete the groups stack while the assignments stack still imports its outputs.</p><h4>How the stacks connect.</h4><p>The three stacks communicate through CloudFormation exports and imports. The Permission-Sets stack exports the ARN of each Permission- Set. The groups stack exports the ID of each group. The assignments stack imports both (plus the account IDs from the Organizations domain) and combines them into the actual access grants.</p><pre># In 3-assignments.yaml: everything is dynamic, nothing hardcoded<br>- Type: AWS::SSO::Assignment<br>  Properties:<br>    InstanceArn: !Ref InstanceArn<br>    PermissionSetArn: !ImportValue DeveloperAccessPermissionSetArn<br>    PrincipalType: GROUP<br>    PrincipalId: !ImportValue DevelopersGroupId<br>    TargetType: AWS_ACCOUNT<br>    TargetId: !ImportValue DevAccountId</pre><p>This means the assignments template has no hardcoded IDs. It resolves everything at deploy time from the outputs of the other stacks. If you ever recreate the groups stack, the group IDs change, and the next deployment of the assignments stack picks up the new values automatically.</p><h4>What CloudFormation cannot do?</h4><p>There is one operation that falls outside what CloudFormation can model: group memberships. AWS::IdentityStore::Group creates the group, but there is no CloudFormation resource type for adding a user to a group.</p><p>This is handled in the deployment script after the stacks are deployed. The script resolves each user’s ID from Identity Store by email, reads the group IDs from the stack outputs, and creates the memberships via the AWS CLI, with an idempotency check so re-running the script does not create duplicates:</p><pre>add_member() {<br>  local GROUP_ID=&quot;$1&quot;<br>  local USER_ID=&quot;$2&quot;<br><br>  EXISTING=$(aws identitystore list-group-memberships \<br>    --identity-store-id &quot;$IDENTITY_STORE_ID&quot; \<br>    --group-id &quot;$GROUP_ID&quot; \<br>    --query &quot;GroupMemberships[?MemberId.UserId==&#39;$USER_ID&#39;].MembershipId&quot; \<br>    --output text)<br><br>  if [ -n &quot;$EXISTING&quot; ] &amp;&amp; [ &quot;$EXISTING&quot; != &quot;None&quot; ]; then<br>    echo &quot;Already a member, skipping.&quot;<br>  else<br>    aws identitystore create-group-membership \<br>      --identity-store-id &quot;$IDENTITY_STORE_ID&quot; \<br>      --group-id &quot;$GROUP_ID&quot; \<br>      --member-id &quot;UserId=$USER_ID&quot;<br>  fi<br>}</pre><h3>Orchestrating deployments with Bash scripts.</h3><p>CloudFormation handles the resource definitions, but there are steps it cannot model on its own, resolving dynamic values at runtime, calling APIs that have no CloudFormation resource type, and coordinating the deployment sequence across multiple stacks. That is where the Bash scripts come in.</p><p>The scripts in this domain are not replacements for CloudFormation. They are thin orchestrators that do three things: resolve runtime values, invoke aws cloudformation deploy in the right order, and handle the steps CFN cannot. In this case, creating group memberships.</p><h4>The deployment menu.</h4><p>Each domain exposes a simple menu with three standard operations and any domain-specific extras:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1Lb4kYy0ur_eukOFgAbnw.png" /></figure><p>This menu pattern is consistent across all domains in the project. Selecting an option launches the corresponding script as a subprocess. If a script fails, the menu survives, and the operator can retry without restarting the session.</p><h4>Sequential execution.</h4><p>The create script runs eight steps in order, each with a clear label so the operator knows exactly where the deployment is at any point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj4TqANLUMLvf7QAp4YFAw.png" /></figure><p>The sequence matters. Permission Sets must exist before assignments can reference their ARNs. Groups must exist before memberships can be created. The script enforces this order and stops immediately if any step fails, preventing partial deployments that are difficult to reason about.</p><h4>What the script handles that CloudFormation cannot.</h4><p>One operation falls outside what CloudFormation can model: adding users to groups. There is no AWS::IdentityStore::GroupMembership resource type. The script resolves each user’s ID from the Identity Store by email, reads the group IDs from the stack outputs, and creates the memberships via the AWS CLI, with an idempotency check so re-running the script does not create duplicates.</p><p>The update script follows the same pattern but uses no-fail-on-empty-changeset, making it safe to run at any time. If nothing changed in the templates, CloudFormation silently skips the deployment, and the script continues to the next step.</p><h3>Verifying access: portal and CLI.</h3><p>Deploying the configuration is only half the job. The other half is confirming that each user can access what they should, and cannot access what they should not.</p><h4>Verifying access through the portal.</h4><p>The AWS access portal gives each user a visual confirmation of what they can access. After logging in, users see only the accounts and roles assigned to them, nothing more. This makes it a quick sanity check after deploying the Identity domain.</p><p>To test, open a private browser window and navigate to your Identity Center portal URL. Log in as each user and observe:</p><ul><li>Which AWS accounts appear in the list.</li><li>Which roles are available under each account.</li><li>That accounts not assigned to that user are completely invisible.</li></ul><p>For a user with access to two accounts with different roles, the portal reflects that asymmetry directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-mxKTLTLtedShBKJXIEew.png" /><figcaption>Portal showing two accounts for a developer. Full access role in Dev, read-only role in Prod.</figcaption></figure><p>For a user in the operations role, the same accounts appear but with the roles inverted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-QjhctwNs4JjVZRwvqNOA.png" /><figcaption>Portal showing two accounts for an operations user. Full access role in Prod, read-only role in Dev.</figcaption></figure><p>The portal view confirms the group assignments are working correctly. What it does not confirm is whether the permissions inside each role are correctly scoped. That requires the CLI tests in the next section.</p><h4>Verifying access through the CLI.</h4><p>Each user needs a profile entry in ~/.aws/configthat points to their assigned account and Permission-Set. The sso-session block is shared. All profiles that belong to the same Identity Center instance reuse it:</p><pre>[sso-session your-sso]<br>sso_start_url = https://&lt;your-instance&gt;.awsapps.com/start<br>sso_region    = us-east-1<br>sso_registration_scopes = sso:account:access<br><br>[profile infra-eng]<br>sso_session    = your-sso<br>sso_account_id = &lt;dev-account-id&gt;<br>sso_role_name  = &lt;developer-permission-set&gt;<br>region         = us-east-1<br><br>[profile platform-eng]<br>sso_session    = your-sso<br>sso_account_id = &lt;prod-account-id&gt;<br>sso_role_name  = &lt;readonly-permission-set&gt;<br>region         = us-east-1</pre><p>One sso login call refreshes credentials for all profiles sharing the same session:</p><pre>aws sso login --sso-session &lt;your-sso&gt;</pre><p><strong>Note</strong>: you can use the --use-device-code parameter to get the portal SSO and use it in an incognito window in your browser. You must also enter the device code provided by the command.</p><p>The goal is to confirm three things for each role:</p><ol><li><strong>Allowed operations succeed</strong>: the user can perform the actions their Permission-Set grants.</li><li><strong>Denied operations fail with AccessDenied</strong>: not silently ignored, but explicitly blocked.</li><li><strong>Cross-environment access matches the design</strong>: full access in the primary account, read-only in the other.</li></ol><p>Once authenticated, execute the following commands to validate the user profile access:</p><pre># Confirm the profile is pointing to the right account:<br>aws sts get-caller-identity --profile &lt;infra-eng&gt;<br><br># These commands must work for the selected profile:<br>aws ec2 describe-vpcs --profile &lt;infra-eng&gt;<br>aws iam list-users --profile &lt;infra-eng&gt;</pre><p>Log out, then log in as another user to test its access:</p><pre>aws sso logout<br>aws sso login --sso-session &lt;your-sso&gt;</pre><p>Next, execute the following commands to validate the other user profile:</p><pre># Confirm the profile is pointing to the right account:<br>aws sts get-caller-identity --profile &lt;platform-eng&gt;<br><br># This command must work for the selected profile:<br>aws iam list-users --profile &lt;platform-eng&gt;</pre><h4>AccessDenied use cases.</h4><p>Try to sign in as a developer user to test its access:</p><pre>aws sso login --sso-session &lt;your-sso&gt;</pre><p>Execute the following commands to validate its access:</p><pre>aws sts get-caller-identity --profile &lt;dev-eng&gt;<br>aws lambda list-functions --profile &lt;dev-eng&gt;<br>aws dynamodb list-tables --profile &lt;dev-eng&gt;</pre><h3>Cost considerations.</h3><p>IAM Identity Center itself has no direct cost. AWS does not charge for:</p><ul><li>Permission Sets created or assigned.</li><li>Groups and group memberships.</li><li>Account assignments.</li><li>SSO sessions or authentications.</li><li>Identity-enhanced sessions and ABAC configuration</li></ul><p>The costs associated with this domain come from the underlying services that Identity Center depends on or interacts with:</p><p><strong>AWS Organizations</strong>: no additional charge for using Organizations features (SCPs, RCPs, OUs). The accounts themselves may incur costs depending on what runs inside them.</p><p><strong>Microsoft Entra ID</strong>: the SAML 2.0 federation used in this article is available on the free tier of Entra ID (included with Office 365 Business Standard and above). SCIM provisioning, which would automate user and group synchronization, requires Entra ID P1.</p><p><strong>CloudTrail</strong>: Identity Center login events are recorded in CloudTrail. If you have a trail configured (which Control Tower sets up by default), standard CloudTrail pricing applies for management events.</p><p>In practice, for a small team using a single region, the identity layer adds no meaningful cost to the monthly AWS bill.</p><p>All these commands should work because that user profile has access to development services like DynamoDB or Lambda.</p><p>Try to execute the following command using the same developer role:</p><pre>aws iam list-users --profile &lt;dev-eng&gt;</pre><p>When a denied action is attempted, the response looks like this:</p><pre>An error occurred (AccessDeniedException) when calling the CreateBucket <br>operation: User is not authorized to performs3:CreateBucket on resource <br>because no identity-based policy allows the s3:CreateBucket action</pre><p>This confirms the policy is working as designed. The explicit deny or the absence of an allow in the Permission-Set is correctly blocking the operation. The SCP and RCP layers in the Organizations domain add further defense in depth on top of this.</p><h3>Conclusion.</h3><p>IAM Identity Center is one of those services that is easy to underestimate. It is tempting to leave the Control Tower defaults in place and move on. The environment works, users can log in, and everything looks fine. But the defaults are a starting point, not a design.</p><p>The decisions covered in this article (group-based access, scoped Permission-Sets, ABAC enforcement, session attributes from an external IdP) are not complex to implement. What they require is intentionality: thinking through who needs access to what, and why, before writing a single line of CloudFormation.</p><p>That is the value of treating identity as a domain with its own design, not an afterthought.</p><p>And that’s it!!! In our next article, I’ll focus on networking components, preparing the field for our applications. So I’ll see you in the next post.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=758fcc8e5a6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating AWS Identity Center with Entra ID for Enterprise SSO.]]></title>
            <link>https://aosolorzano.medium.com/integrating-aws-identity-center-with-entra-id-for-enterprise-sso-5ef360cd5648?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ef360cd5648</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Sat, 01 Aug 2026 01:31:18 GMT</pubDate>
            <atom:updated>2026-08-01T01:31:18.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5gW1jTpmyInG2f_M3FkEQ.png" /></figure><h3>Introduction.</h3><p>In our <a href="https://medium.com/@aosolorzano/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">previous article</a>, we created a multi-account environment on AWS using <a href="https://aws.amazon.com/controltower/"><strong>Control Tower</strong></a>, which configures an instance in the <a href="https://aws.amazon.com/iam/identity-center/"><strong>Identity Center</strong></a> service internally. Control Tower creates and configures an admin user for each AWS account, but those users were managed only by Identity Center. We can modify this behavior by configuring Identity Center to retrieve users from an external service like <a href="https://docs.azure.cn/en-us/entra/fundamentals/what-is-entra"><strong>Entra ID</strong></a>. This is the way many companies work. So let’s replicate this scenario in the present article.</p><h3>Prerequisites.</h3><ol><li><strong>Identity Center</strong>: Please follow the <a href="https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">previous article</a> to configure a multi-account environment using Control Tower. You can use your manually created instance in Control Tower, but you will lose the remaining recommended configurations.</li><li><strong>Entra ID: </strong>required to integrate this service with the Identity Center instance, retrieving the created users in Entra ID and configuring them with their required access permissions.</li><li><strong>Office 365 Subscription (optional)</strong>: if you have an active subscription, you’re already using Microsoft Entra ID.</li></ol><h3>What is Identity Center?</h3><p>IAM Identity Center is the recommended service for managing workforce access to multiple AWS accounts and applications from a single place. Instead of creating IAM users in each account, Identity Center provides:</p><ul><li><strong>Single Sign-On (SSO)</strong>: Users authenticate once and access all their assigned AWS accounts without re-entering.</li><li><strong>Centralized access management</strong>: Administrators assign permissions across the entire organization from one console.</li><li><strong>Permission Sets</strong>: Reusable permission templates that define what a user can do in an account (e.g., AdministratorAccess, ReadOnly, custom policies).</li><li><strong>Integration with external identity providers</strong>: Federate with corporate directories like Microsoft Entra ID, Okta, or Google Workspace, eliminating the need to manage users directly in AWS.</li></ul><p>When Control Tower creates a Landing Zone, it automatically provisions an Identity Center instance. By default, it uses its own internal directory. However, for enterprise use, it’s recommended to connect it to an external identity provider.</p><h4>Why Microsoft Entra ID?</h4><p>Microsoft Entra ID (formerly Azure Active Directory) is one of the most widely adopted corporate identity providers. Most organizations already use it through Microsoft 365 (Outlook, Teams, Office). Connecting Entra ID to Identity Center provides:</p><ul><li><strong>One identity for everything</strong>: Employees use the same credentials for Microsoft 365, AWS, Jira, Slack, and any other federated application.</li><li><strong>Centralized user lifecycle</strong>: When an employee joins or leaves, their access to AWS is managed from Entra ID. No need to update AWS separately.</li><li><strong>MFA enforcement</strong>: Leverage Entra ID’s multi-factor authentication policies across all AWS account access.</li><li><strong>Zero additional cost</strong>: Entra ID Free tier (included with any Microsoft 365 subscription) supports unlimited users for SAML federation with AWS.</li></ul><p>In the following sections, we will configure Identity Center to use Entra ID as its external identity provider, replacing the default internal directory.</p><h4>SAML vs. OAuth: Understanding the difference.</h4><p>In the context of Identity Center and Entra ID, we use SAML 2.0 (Security Assertion Markup Language) for federation. It is common to confuse SAML with OAuth, so here is a quick clarification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qmB0YTkrsQ-FAp0aHyBqQ.png" /></figure><p>For our use case, where employees access AWS accounts via Identity Center, SAML is the correct protocol. Entra ID acts as the SAML Identity Provider (IdP) and AWS Identity Center acts as the Service Provider (SP). When a user logs in, Entra ID verifies their credentials and sends a SAML assertion to AWS, which grants access without AWS ever seeing the user’s password.</p><h3>Identity Center and Entra ID integration.</h3><p>We must configure both services. It’s like a handshake. The integration is bidirectional, so both services must know each other. But there is a specific order to configure them.</p><h4>Step 1: Get some Identity Center URLs.</h4><p>Go to your Identity Center instance settings in the AWS console, and choose the “Change identity source” option in the Identity source tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjDWpSmoW-xnKDMLLpwK2w.png" /></figure><p>On the next page, select the “External identity provider” option and click Next. Then, copy the “<strong>IAM Identity Center Assertion Consumer Service (ACS) URL</strong>” and the “<strong>IAM Identity Center issuer URL</strong>” into a notes block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IX5fzaa-acfbT-UnwFqvg.png" /></figure><p>We will need these values in the next step.</p><h4>Step 2: Configure the Enterprise Application in Entra ID.</h4><p>Go to the Entra ID website and select the Enterprise Apps option in the left menu. Then, search for the Identity Center application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niu6XdQHhSnPmSwbYmC6XA.png" /></figure><p>Select the required application, then click the Create button. After the application is created, go to the “Single sign-on” option and edit the “Basic SAML Configuration” section, as it is not configured accordingly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*up86b5sqrMJRgiPVAeLjRA.png" /></figure><p>In the “Identifier” field, enter the “<strong>IAM Identity Center issuer URL</strong>” that you copied in the previous step. Then, in the “Reply URL” field, enter the “<strong>IAM Identity Center Assertion Consumer Service (ACS) URL</strong>” value you copied in the previous step. Save your changes.</p><p>Next, in the Attributes &amp; Claims section, verify that the emailaddress and the Unique User Identifier properties have the user.principalname value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wdl1--V8UdL7coyvZbPneg.png" /></figure><p>Finally, download the <strong>Federation Metadata XML</strong> file located in the SAML Certificates section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bq7Yrv975p2EZ_kanCbDA.png" /></figure><p>The SAML metadata file contains the certificate data, so you don’t need to download the certificate in any of the proposed formats.</p><h4>Step 3: Configure Identity Center to use Entra ID.</h4><p>Return to the “Configure external identity provider” page as we did in step 1, but this time we need to upload the SAML metadata file that we downloaded in the previous step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NtbD1Tqcd7X9_6Ir-b8ZzA.png" /></figure><p>Then, click on the Next button. On the next page, you must see that your metadata file was uploaded successfully and the content is correct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyVVd_DMCuIxbre2j7ljWQ.png" /></figure><p>Below, in the “Review and confirm” section, you’ll see a list of the consequences of this change. Read them carefully and ensure that these changes will not affect your current configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oxc6An84741VrXDo_ccGQ.png" /></figure><p>If you are ok with that, enter ACCEPT and click on the “Change identity source” button. After that, you will see that the SAML 2.0 configuration was updated for your Identity Center instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOlo9nk45bbS-gVvsc97ww.png" /></figure><p>Now, let’s analyze the impact of these changes on what we configured in the previous tutorial.</p><h4>What happens after changing the identity source?</h4><p>In our <a href="https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">previous tutorial</a>, we created some OUs and accounts, and Control Tower configured some users in the Identity Center based on the emails we set in the CFN templates for those new accounts. So the following table summarizes the impact of the changes we want to apply:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5AB3fH8dkTWdQIcaiEYEw.png" /></figure><p>There’s no negative impact on what we have. The permission sets and Control Tower assignments are maintained. The only effect is that the Bootstrap user stops working. We’ve replaced it with Entra ID users.</p><h4>Step 4: Create users in Entra ID</h4><p>Let’s start by creating a single user for testing before creating all the users we need. Go to <strong>Entra ID → Users → All users</strong>, and click the New user button. In the Basics tab, enter the required information for your new user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K5U7-ovmYWFaVT3JOwScLA.png" /></figure><p><strong>IMPORTANT</strong>: the User Principal Name (UPN) must exactly match the SSO user email defined in the Account Factory template in the previous tutorial (3-accounts.yaml). For example, if the template defines account@yourdomain.com as the SSO user email, the Entra ID user must be created with the UPN account@yourdomain.com. A mismatch will cause the SSO login to fail with the error “Looks like this code isn’t right”.</p><p>Allow the Entra ID to generate a password for the user. We will need this password for the first user login, so copy it and paste it into your notes app.</p><p>After you create the user, go to Enterprise apps, select the Identity Center application, select the “<strong>Users and groups</strong>” option, and click on the Add user/group button. Since we don’t have any users assigned yet, click the “None Selected” link, which opens a side panel where you can select the user you created earlier. Then click on the Assign button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MFII6N7ZO9E45X436FMpBg.png" /></figure><p>Your new user must now appear in the Users and groups table.</p><h4>Step 5: Verify the SSO connection.</h4><p>It’s time to test our current configuration. Let’s open a new browser tab and navigate to the <strong>AWS access portal sign-in URL</strong> that you copied in Step 1. You can use an incognito tab to test this integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVQQgq4SAzyV0XkphUVU1A.png" /></figure><p>Enter the email address and generated password of your new user and click Sign In. As this is the first access of your user, the IdP will ask you for a new user password:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3_NYw7ERCFPscvY_zxBDQ.png" /></figure><p>Then, you must configure MFA, for which you will need the MS Authenticator App:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KyjQAUUMG1IwwDpYWO9_LQ.png" /></figure><p>After you configure this, your user must be assigned an MFA process to log in to the AWS console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gccVTFZGaw162y9CZSzjmw.png" /></figure><p>If you configure all these steps successfully, you can be redirected to the AWS Access Portal, where you need to choose the role assigned for your user in the Identity Center:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dieJhAAKPXxCCYJhHa9XqA.png" /></figure><p>Notice that <strong>AWSAdministratorAccess</strong> is the Permission Set assigned by default by the Account Factory for every SSO user in each account. You can review this in our <a href="https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">previous tutorial</a>.</p><p>After you select the desired user role, you can access the AWS console as usual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s7KJmlX0TMKmorcsmb7F4Q.png" /></figure><p>Notice that your user must operate according to the access permissions you assigned. In the previous image, the user doesn’t have permission to access the Service Catalog. You can assign another Permission Set to the user accordingly.</p><h4>Step 6: Create the remaining users.</h4><p>Repeat the process described in Step 4 for each SSO user defined in your Account Factory template (3-accounts.yaml). Each user must have a User Principal Name (UPN) in Entra ID that exactly matches the SSO email configured in the template.</p><p>For each user:</p><ol><li>Create the user in Entra ID (no M365 license needed).</li><li>Assign the user to the Enterprise App “AWS IAM Identity Center”.</li></ol><p>Once assigned, each user will be able to access their respective AWS account through the Identity Center portal using their Entra ID credentials.</p><h3>SCIM Provisioning (Optional).</h3><p>SCIM (System for Cross-domain Identity Management) is a protocol that enables automatic user and group synchronization between Entra ID and Identity Center. When enabled:</p><ul><li>Users created in Entra ID are automatically provisioned in Identity Center.</li><li>Users removed from Entra ID are automatically deprovisioned in Identity Center.</li><li>Group memberships are synchronized, enabling group-based permission assignments.</li><li>No manual user creation in Identity Center is required.</li></ul><p>Without SCIM, you must ensure that users exist in both Entra ID and Identity Center with matching usernames. Account Factory creates the initial users in Identity Center, but any future user changes must be managed manually on both sides.</p><p>SCIM provisioning requires Microsoft Entra ID P1 or higher, which is included with:</p><ul><li>Microsoft 365 Business Premium.</li><li>Microsoft 365 E3 / E5.</li><li>Entra ID P1 standalone license.</li></ul><p>For this article, I proceeded without SCIM since my Microsoft 365 Business Standard license does not support it. Account Factory already created users in Identity Center in the <a href="https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221">previous tutorial</a>, and we only need to ensure that the Entra ID usernames (UPN) match those users.</p><h3>Conclusion.</h3><p>In this article, we configured AWS Identity Center to use Microsoft Entra ID as an external identity provider, enabling enterprise-grade SSO access to our AWS Organization. Here are the key takeaways:</p><ul><li>SAML federation connects Entra ID and Identity Center without storing AWS credentials — authentication is delegated entirely to your corporate identity provider.</li><li>No additional cost — Entra ID Free tier (included with any Microsoft 365 subscription) supports unlimited users for SAML-based SSO.</li><li>UPN matching is critical — the User Principal Name in Entra ID must exactly match the SSO user email defined in Account Factory. A mismatch will prevent authentication.</li><li>Users created by Account Factory are preserved — when changing the identity source, existing users, groups, and permission set assignments are retained.</li><li>MFA is now managed from Entra ID — this gives you centralized control over authentication policies across all applications, not just AWS.</li></ul><h4>Limitations.</h4><ul><li><strong>SCIM provisioning</strong>: automatic user synchronization between Entra ID and Identity Center requires Entra ID P1 (not available with M365 Business Standard).</li></ul><h4>What we did not cover.</h4><ul><li><strong>Automation</strong>: unlike the previous article where we automated the entire setup with Bash scripts and CloudFormation, this integration involves manual steps on both sides (Entra ID console and AWS console). The SAML configuration APIs are limited, and Entra ID’s Enterprise Application setup is console-only.</li></ul><h4>What can we do next?</h4><ul><li><strong>Custom Permission Sets: </strong>we used the default AWSAdministratorAccess created by Account Factory. In a real enterprise, we would create granular permission sets (ReadOnly, Developer, NetworkAdmin, etc.) and assign them per account.</li><li><strong>Group-based access</strong>: instead of assigning permissions to individual users, enterprises typically create groups in Entra ID and assign permissions to groups. This simplifies management at scale.</li></ul><p>And that’s it!!! This article doesn’t include any GitHub repository because the tasks you must implement are manual. In the next article, I’ll talk about creating personalized Permission Sets for the users we created in the Identity Center.</p><p>I hope you enjoy this article, and I’ll see you in the next one.</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef360cd5648" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating AWS Control Tower with CloudFormation for your professional projects.]]></title>
            <link>https://aosolorzano.medium.com/automating-aws-control-tower-with-cloudformation-for-your-professional-projects-0d39d21bf221?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d39d21bf221</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 02:22:21 GMT</pubDate>
            <atom:updated>2026-07-28T02:22:21.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPsC3NB-XofOdtelXXBk5Q.png" /><figcaption>The AWS services and organization structure used in this article.</figcaption></figure><h3>Introduction.</h3><p>In my previous articles, I described how to implement and deploy software components in AWS. In some of them, I explained how to configure AWS management services, such as <a href="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html">Organizations</a>, but I didn’t experiment with <a href="https://docs.aws.amazon.com/controltower/latest/userguide/what-is-control-tower.html">Control Tower</a>. In this article, we’re going to integrate Control Tower to provision our accounts with the recommended settings, thereby increasing the professionalism of our projects.</p><h3>Prerequisites.</h3><ol><li><strong>Domain Name</strong>: Try to acquire a domain name for your professional projects. You can use <a href="https://aws.amazon.com/es/blogs/networking-and-content-delivery/benefits-of-domain-registration-with-amazon-route-53/">Route 53</a> for this purpose.</li><li><strong>Business Email</strong>: You must use your Domain Name to create your business emails. After that, you can create different email addresses (or aliases) and associate them with each account you create for your AWS organization. You can use the <a href="https://www.microsoft.com/en-us/microsoft-365/business/microsoft-365-business-standard">Office 365 Business Standard</a> plan.</li><li><strong>AWS Organization</strong>: This is the easiest one. You need to create an organization in your management account where Control Tower can run.</li></ol><h4>IMPORTANT.</h4><p>We will initially work in the AWS console to familiarize us with the concepts and configurations. Later, we’ll work with CloudFormation templates and Bash scripts to automate the steps we did in the console. So you can follow the console flow without creating any resources, since you can use the Bash scripts in the <a href="https://github.com/aosolorzano/iac-control-tower">GitHub</a> repo to deploy this infrastructure to your AWS account.</p><h3>What is AWS Control Tower?</h3><p>Control Tower is not a service for creating accounts. It’s a continuous governance service. Account creation is just a secondary feature.</p><h4>The problem it solves.</h4><p>Without Control Tower, when you create a multi-account organization manually, you have to:</p><ul><li>Create each account → manually configure CloudTrail, Config, logging.</li><li>Ensure nobody turns off security controls.</li><li>Apply SCPs and verify compliance.</li><li>For every new account → repeat everything manually.</li><li>If an employee breaks a security configuration → you won’t know until it’s too late.</li><li>You have no centralized compliance dashboard.</li></ul><p>Creating accounts is easy. Governing them consistently and continuously is hard.</p><h4>With Control Tower.</h4><ul><li>Account Factory creates accounts already configured with CloudTrail, Config, logging, and guardrails applied automatically.</li><li>Guardrails (preventive and detective) enforce and monitor compliance across all accounts.</li><li>Drift detection alerts you if someone modifies what the Control Tower has configured.</li><li>The compliance dashboard gives centralized visibility of your organization’s security posture.</li><li>Region denies guardrail is ready to activate — no custom SCP needed.</li></ul><h4>Guardrails: the core of Control Tower.</h4><p>Control Tower guardrails come in three types:</p><ul><li><strong>Preventive</strong>: SCPs that block actions before they happen (e.g., “Cannot disable CloudTrail”).</li><li><strong>Detective</strong>: Config Rules that detect and report violations (e.g., “Detect S3 buckets without encryption”).</li><li><strong>Proactive</strong>: CloudFormation Hooks that validate before deployment (e.g., “Block security groups with 0.0.0.0/0”).</li></ul><p>Control Tower includes more than 400 pre-built guardrails that you can activate per OU. You don’t need to write SCPs from scratch or invent Config rules. They’re tested and maintained by AWS.</p><h4>Account Factory is not just “create an account”.</h4><p>When you create an account via Account Factory, it automatically:</p><ul><li>Places it in the OU you selected.</li><li>Applies all guardrails for that OU.</li><li>Enables CloudTrail (sending logs to Log Archive account).</li><li>Enables Config (sending data to Audit account).</li><li>Configures access via Identity Center.</li><li>Applies the complete security baseline.</li></ul><p>If you create an account manually, AWS::Organizations::Account, you only get an empty account. Enrollment in Control Tower is what makes it secure and governable.</p><h4>Simple analogy.</h4><ul><li><strong>Organizations: </strong>creating the structure (OUs, accounts). Like creating folders.</li><li><strong>Control Tower: </strong>governing that structure. Like having a watchdog that ensures nobody breaks the rules in any folder, and that every new folder is created with the rules already applied.</li></ul><h3>Landing Zone: Concept vs. Component.</h3><h4>Architectural concept.</h4><p>A Landing Zone is an architectural concept. It refers to a well-configured, multi-account environment where you deploy your workloads. It includes:</p><ul><li>Organizational Units (OUs) and account structure.</li><li>Base networking (VPCs, connectivity).</li><li>Identity and access management configured.</li><li>Centralized logging and auditing.</li><li>Security guardrails applied</li></ul><p>Any organization that follows multi-account best practices has a Landing Zone, whether it was built with Control Tower or manually.</p><h4>Within the Control Tower.</h4><p>Control Tower has a resource called Landing Zone (AWS::ControlTower::LandingZone). It is the base configuration that Control Tower deploys when you enable it:</p><ul><li>Security OU with two accounts (Audit and Log Archive).</li><li>Organizational CloudTrail.</li><li>AWS Config is enabled across accounts.</li><li>Mandatory guardrails applied.</li><li>Identity Center instance created</li></ul><p>In other words, when you enable Control Tower, what you’re creating is its Landing Zone. It’s an internal component, not a separate tool.</p><h4>When to go beyond the Control Tower.</h4><p>For large enterprises with strict regulatory requirements (government, financial services, healthcare), AWS offers the “Landing Zone Accelerator” (LZA). This open-source solution deploys an entire Landing Zone with advanced configurations: centralized networking, firewalls, complex logging pipelines, and compliance frameworks.</p><p>However, for small to medium-sized organizations or projects that need a solid multi-account foundation without the overhead of managing dozens of automated resources, Control Tower alone is sufficient. It provides governance, compliance, and security baselines out of the box, and you can extend it incrementally with <strong>CloudFormation</strong> as your organization grows.</p><h3>Organization Structure.</h3><p>For this article, we will set up the foundational accounts that every organization needs as a starting point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQk9JemiPlw0l4HbuK3plQ.png" /></figure><h4>Security OU (provisioned by Control Tower).</h4><ul><li><strong>Audit</strong>: Centralized AWS Config aggregation and security notifications across all accounts in the organization.</li><li><strong>Log Archive</strong>: Centralized storage for CloudTrail logs and Config history from all accounts.</li></ul><h4>Infrastructure OU.</h4><ul><li><strong>Network</strong>: Manages shared networking resources such as VPN connections, Transit Gateway, and DNS.</li><li><strong>Shared Services</strong>: Hosts CI/CD pipelines, container registries, artifact storage, and shared tooling used across all environments.</li></ul><h4>Workloads OU.</h4><ul><li><strong>Dev</strong>: Development environment where teams build and test new features.</li><li><strong>Test</strong>: Quality assurance environment for functional and integration testing before promotion.</li><li><strong>Staging</strong>: Pre-production environment that mirrors production for final validation and demos.</li><li><strong>Prod</strong>: Production environment serving end users.</li></ul><h4>Sandbox OU.</h4><ul><li><strong>Sandbox</strong>: Isolated environment for experimentation and learning without impacting governed accounts.</li></ul><p>This gives us a minimal yet solid multi-account foundation aligned with AWS best practices.</p><p>In a real-world enterprise scenario, you would extend this structure with additional accounts as your organization grows:</p><ul><li>A <strong>Shared Services</strong> account in the Infrastructure OU for CI/CD pipelines, artifact storage, and container registries.</li><li>Additional environment accounts in the <strong>Workloads OU</strong>, such as Dev or Staging, to support a full software delivery lifecycle.</li><li>An optional <strong>Sandbox OU</strong> for experimentation without impacting governed accounts.</li></ul><p>The key takeaway is to start small with a governed foundation and scale incrementally. Control Tower makes adding new accounts easy and secure through Account Factory, ensuring every new account inherits the same security baselines and guardrails from day one.</p><h3>Service Costs.</h3><p>When you enable Control Tower, the following AWS services are activated across all governed accounts and will incur charges:</p><ul><li><strong>Config</strong>: enabled across all governed accounts to monitor compliance. This is the primary cost driver.</li><li><strong>S3</strong>: stores CloudTrail logs and Config history in the Log Archive account.</li><li><strong>CloudTrail</strong>: organization-level trail that records management events across all accounts.</li><li><strong>KMS (optional)</strong>: if encryption is enabled for CloudTrail or S3 buckets.</li></ul><p>Regarding guardrails:</p><ul><li><strong>Preventive guardrails</strong> (SCPs) are free. They are policies that block actions, not resources.</li><li><strong>Detective guardrails</strong> (Config Rules) add cost. Each rule is billed per account per region.</li><li><strong>Proactive guardrails</strong> (CloudFormation Hooks) are free. They only evaluate during deployments.</li></ul><p>The main cost driver for Control Tower is AWS Config, which is enabled across all governed accounts. To minimize costs in a lab environment, govern only one region and avoid enabling detective guardrails unless needed.</p><h3>Control Tower Configuration.</h3><p>We need to enable the Control Tower first. If you don’t have it enabled, please enable it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vbWpTDje_b8dGljZ_Kq3g.png" /></figure><p>On the next page, select “I want to set up a full environment”. You can review the difference between the options below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eu_7QxnF-qs_8uJ58T2l0w.png" /></figure><p>In the next panel, choose the region where the Landing Zone will reside. I will choose the “US East (N. Virginia)”. You can choose additional governed regions, but keep in mind that you might be charged for some inter-region integrations. You can also add regions where you don’t want to have access to AWS services and operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmh1swfUAmYW9us0NB2_7A.png" /></figure><p>In the next step, accept the suggested OUs, which are called foundational OUs, and click Next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JE9dTk093C4kvabED1iQg.png" /></figure><p>In the next step, the Security OU was selected as the “Default OU for service integrations”. Keep that selection unless you want something different. In the next panel, keep the “Enable AWS Config” checked, as we want this enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0I4gNZsSZj_YWyVXHxYRNg.png" /></figure><p>For this to work, you must click the “Create new” button and enter the values you want for this new account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K6306swqEuUp5rTz5la6w.png" /></figure><p>In my case, I entered the email associated with the Audit account I defined in the previous section. For the name, you can enter the appropriate one.</p><p>In the “Amazon S3 bucket preferences for logs” section, you can modify the selected values or keep the defined ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep1KjVWP6XEkB6F3C4q6KA.png" /></figure><p>In the next section, also keep the default settings, as we want to enable the “Centralized CloudTrail Logging” configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2keAD7fnfLBlH2TcQPTdrQ.png" /></figure><p>Again, you must click the “Create new” button to enter the details for the new account for this service integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtNP_VA45e7zqMLXGHY2UA.png" /></figure><p>As I mentioned at the beginning, I created an AWS Organization for my previous articles and had enabled the IAM Identity Center. I deleted all OUs in my original organization configuration and all configurations inside the Identity Center. So in the next section, I have activated that service. You may have this integration disabled, so allow that integration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3iAQjfVZTr6nKQGiGOvJA.png" /></figure><p>In the “AWS Backup” section, keep the selected option unless you decide differently and click “Next” to continue to the next step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viyxgo-FGAYoEkOsorvjBg.png" /></figure><p>In the final step, you need to review all selected values and click on the “Enable AWS Control Tower” button if you agree with that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEWezJ_vqsyduc7ERxdy8A.png" /></figure><p>After that, we’ll need to wait until all configurations are created in our management account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCpkKZkbrUrhFQXgWKzajg.png" /></figure><p>After the time is completed, the Control Tower home page will show you the created configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-AMMjadtflqxqr8pub4jg.png" /></figure><p>In the “Organization” option in the left menu, you will see the following configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcfDlqctH2U7NlclsMDrLw.png" /></figure><p>The “Suspended” OU was created manually by me and will contain all closed or removed accounts. The last one is the management account.</p><p>In the “Landing zone settings” option in the left menu, you can see the selected settings when the Control Tower was enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZKeLDKIRXA8m6N50leBvQ.png" /></figure><p>Now, let’s talk about the initial user that Control Tower created in Identity Center as an admin user.</p><h3>Users created in Identity Center.</h3><p>You must also have received an email instructing you to join your new Identity Center instance as an Administrator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3NGwzwHVFFFnKfgsY69wg.png" /></figure><p><strong>Note</strong>: This is not your Organization’s management account user. Control Tower creates an initial user in Identity Center to bootstrap administrative access. This user will be replaced when we integrate with an external Identity Provider.</p><p>When you click the button, you must be redirected to a page where you can enter the user’s new password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8CRCzolGJbYjiY77ToYFw.png" /></figure><p>After doing that, you can see the user with an active status in the Identity Center service console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SadrsLJPNuqFTDULSav34w.png" /></figure><p>The last verification email you must have received is for an SNS topic subscription to receive Control Tower security notifications:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVve3N0FqIhnw8QiTqFhNQ.png" /></figure><p>After completing these 2 email verification steps, you can configure the CLI for this user to log in to AWS.</p><h4>Configuring the CLI for SSO.</h4><p>First, we need to execute the following command:</p><pre>aws configure sso</pre><p>That command will ask you for the following information:</p><pre>- SSO session name (Recommended): &lt;your-session-name&gt;<br>- SSO start URL: (you find it in Identity Center → Settings → Portal URL)<br>- SSO region: &lt;your-region&gt;<br>- SSO registration scopes [sso:account:access]: press enter (default).</pre><p>That will open a new browser tab where you need to enter the admin user credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w87rFPe-9kJ65NvHE7M6bg.png" /></figure><p>You also might be asked to configure MFA, as this was configured by default with Control Tower:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7hFB1pJtDeUOGrktA7SGxQ.png" /></figure><p>After that, you’ll be prompted to accept the CLI application to access applications and accounts in AWS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTntOpmLHEwV9nVhg9-bRA.png" /></figure><p>If you allow access, the CLI will ask you for the final values before ending the configuration:</p><pre>- Account: (select the Management Account)<br>- Role: (select the AWSAdministratorAccess)<br>- Profile name: &lt;desired-profile-name&gt;<br>- Default client Region [None]: &lt;your-client-region&gt;<br>- CLI default output format (json if not specified) [None]: json<br>- Profile name [AWSAdministratorAccess-xxxxxxxx]: &lt;preferred-profile-name&gt;</pre><p>If you open your ~/.aws/config file, you will see the following config at the end of it:</p><pre>[profile &lt;preferred-profile-name&gt;]<br>sso_session = &lt;your-session-name&gt;<br>sso_account_id = 123456789012<br>sso_role_name = AWSAdministratorAccess<br>region = us-east-1<br>output = json<br><br>[sso-session &lt;your-session-name&gt;]<br>sso_start_url = https://&lt;your-identity-center-instance&gt;.awsapps.com/start<br>sso_region = us-east-1<br>sso_registration_scopes = sso:account:access</pre><p>Now you can log in to your Identity Center using the configured profile:</p><pre>aws sso login --profile &lt;preferred-profile-name&gt;</pre><p>The command will open a new tab in your default browser window where you must enter the admin credentials. Note that this is the login for your configured Identity Center in your AWS Organization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ArA1lYDVdMrPD1rbDCQsQ.png" /></figure><p>After your credentials are validated, your CLI is ready to accept AWS commands to administer your organization and its accounts.</p><h3>Adding more OUs and Accounts.</h3><p>In the Organizations option in the Control Tower console, you can add an OU or an account. If you need to add an OU first, you can select that option:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80kmTEwtRr21OFXg5_9eGw.png" /></figure><p>Then, you must enter the following fields to specify the parameters for the new OU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yeqHUnyCzEzuMCPuV5uIqA.png" /></figure><p>Finally, your new OU must appear in your organization’s structure, and the Control Tower’s controls must be enabled for that OU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71pCkn3fmLworPSWRvvYoA.png" /></figure><p>Now let’s move on to the next section, which covers how to use CFN. As I said at the beginning of the article, the process I did in the console was only to familiarize us with the concepts. So let’s try to deploy these resources using Infrastructure as Code.</p><h3>Service Quota limit in Organizations.</h3><p>In the next section, when you use the bash scripts to deploy all this infra, you might encounter the following error if you try to create all the suggested accounts in the first try:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6LIP5S1B-dSV0MBAzpFRw.png" /></figure><p>If you go to the CFN console, you’ll see the following message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l9IAqjh-My2bAziX_pdtg.png" /></figure><p>The error is about a service limit. If you receive this type of error, you must go to the Service Quota console, find the Organizations service, and choose the “Maximum number of accounts” quota name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVzn7Wy_zMnMc1-ZNJlQsQ.png" /></figure><p><strong>IMPORTANT:</strong> If you try to find the Organizations service in the Service Quota console, but you don’t have an organization created, you won’t find the quota name. So first create an organization, and request a quota increase for that service.</p><p>You will be asked to enter the limit you want. I requested an increase of 10 accounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vO4Ju1ABcLSK5351JwO-A.png" /></figure><p>After that, your request will be added to the “Quota request history” and will be in “Pending” status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2nhZNgaFoZFRTtum7oO5w.png" /></figure><p>With a basic support plan, I received an email 4 days after my request, with the following content asking 2 basic things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhBXO1mW15bpuGZ-sUntjQ.png" /></figure><p>You must answer those questions in the console. When I send an email in response, it gets rejected. But the next email indicates that I should follow the opened case in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQn09VRobE9_hci4VZ_jOQ.png" /></figure><p>If you go to the Service Quota console, you will see a link in the “AWS Support Center Case” column that indicates a case number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HL3PZuoxFVd6BMoPDzwf0g.png" /></figure><p>If you click the link, you’ll navigate to another page where you can follow the case and submit any response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oknA7ot7MoFMAJx2vgx4cQ.png" /></figure><p>When you receive an email confirming the quota increase, you can create the accounts you want, respecting the new limit.</p><h3>Using CloudFormation.</h3><p>I will start with an empty account. I don’t have any AWS Organization or Control Tower created. So the first step is to create our organization using the CLI or the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Elfw9Vi2L3HBJfEtyvM1GQ.png" /></figure><p>Then, create the access keys for your root user to deploy all our required infra from the CLI.</p><p><strong>Important</strong>: don’t use your access keys beyond this step. You must remove the root user’s access keys after that, since administrator accounts will be created in your Identity Center instance.</p><p>After creating the access keys for your root user, go to the CLI and configure it:</p><pre>aws configure --profile &lt;your-mgmt-profile&gt;</pre><p>That command will ask you for the following information:</p><pre>AWS Access Key ID [None]: &lt;your-access-key&gt;<br>AWS Secret Access Key [None]: &lt;your-secret-key&gt;<br>Default region name [None]: us-east-1<br>Default output format [None]: json</pre><p>After that, you can initiate the deployment of our infrastructure. For this, go to the project’s root directory and execute the following command:</p><pre>./start.sh</pre><p><strong>Important</strong>: When you close accounts, you must wait 90 days before they are permanently closed. Until that time, you cannot delete your organization. That’s why the script doesn’t create the organization, and it must be created before running the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nxaZ4snqg4oYDKcqdCzNbg.png" /></figure><p>When I wrote these lines, there was no support in CFN for Landing Zones, so CLI must create it. We can define the following using CFN templates: IAM roles, OUs, security accounts, Account Factory, and Guardrails. The following are some code snippets for some of these files. You can see the full content in the project repository:</p><pre>Resources:<br>  SecurityOU:<br>    Type: AWS::Organizations::OrganizationalUnit<br>    Properties:<br>      Name: Security<br>      ParentId: !Ref RootId<br><br>  InfrastructureOU:<br>    Type: AWS::Organizations::OrganizationalUnit<br>    Properties:<br>      Name: Infrastructure<br>      ParentId: !Ref RootId<br><br>  WorkloadsOU:<br>    Type: AWS::Organizations::OrganizationalUnit<br>    Properties:<br>      Name: Workloads<br>      ParentId: !Ref RootId</pre><pre>Parameters:<br>  NetworkAccountEmail:<br>    Type: String<br>    Default: your-email@test.com<br>  NetworkUserEmail:<br>    Type: String<br>    Default: your-email@test.com<br><br>Resources:<br>  NetworkAccount:<br>    Type: AWS::ServiceCatalog::CloudFormationProvisionedProduct<br>    Properties:<br>      ProductId: !Ref AccountFactoryProductId<br>      ProvisioningArtifactId: !Ref AccountFactoryArtifactId<br>      ProvisionedProductName: Network<br>      ProvisioningParameters:<br>        - Key: AccountName<br>          Value: Network<br>        - Key: AccountEmail<br>          Value: !Ref NetworkAccountEmail<br>        - Key: ManagedOrganizationalUnit<br>          Value: Infrastructure<br>        - Key: SSOUserEmail<br>          Value: !Ref NetworkUserEmail<br>        - Key: SSOUserFirstName<br>          Value: !Ref UserFirstName<br>        - Key: SSOUserLastName<br>          Value: !Ref UserLastName</pre><p>Creating the Landing Zone takes some time, as it provisions resources and configurations on your behalf.</p><p>After creating the Landing Zone, the script must enroll the other defined OUs inside Control Tower. Remember that the Security OU is the only required OU when creating the Landing Zone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYqkwuqERQ3a6R5V4-apgw.png" /></figure><p>Finally, the script will create the accounts defined in the CFN template using Account Factory. With this option, the accounts will be created with the required configurations needed by Control Tower:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQrkQ-B5o9unHN7aZ86ITg.png" /></figure><p>If you go to the organizations section in the Control Tower console, you will see the following table with your configured OUs and accounts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wx67h0oNLqP6JUabfjwr7Q.png" /></figure><p>You can also validate your created OUs and accounts in the Organizations console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zSQHAUgi5VY2R2MRgTvS4Q.png" /></figure><p>Now let’s say we need a new account, this time the Sandbox account. So after you modify the CFN “ct-accounts” template, you must execute our start.sh script, but this time select option 2 to deploy the update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1KNnun4pS7fOMjT70MGHQ.png" /></figure><p>After the script finishes, go to the Control Tower console and verify if the Sandbox account was created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2EFdwbIpKjgljkepe3Nzxg.png" /></figure><p>Finally, you can remove all created infra, using the same start.sh script, but choosing option 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIxLzBccyV7DocQfKrah3w.png" /></figure><p>This will decommission the Landing Zone, close all member accounts, clean up Identity Center, and delete CloudFormation stacks.</p><p><strong>IMPORTANT</strong>: Closed accounts remain in the organization for 90 days before permanent deletion.</p><h3>Conclusion.</h3><p>Setting up a multi-account AWS organization with Control Tower is not a trivial task, but automating it with bash scripts and CloudFormation makes this process repeatable and reliable. In this article, we covered:</p><ul><li>How Control Tower provides governance, compliance, and security baselines out of the box.</li><li>How to automate the entire setup using CloudFormation, including the Landing Zone, OUs, accounts (via Account Factory), and guardrails.</li><li>Key lessons learned: hidden account quotas, the importance of Service Catalog portfolio access, and the difference between creating accounts with Organizations API versus the Account Factory.</li></ul><p>The scripts and templates are available on GitHub as a starting point for your own organization. You can start with the base accounts and expand them as your project grows, adding accounts and guardrails.</p><p>And that’s it!!! In the next article, we will configure AWS Identity Center with Microsoft Entra ID to enable SSO access for team members across all accounts in the organization.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d39d21bf221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DynamoDB Async Client in Spring Cloud Functions using WebFlux to create reactive Lambda functions…]]></title>
            <link>https://aosolorzano.medium.com/dynamodb-async-client-in-spring-cloud-functions-using-webflux-to-create-reactive-lambda-functions-dbda7e57e9aa?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbda7e57e9aa</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 00:24:24 GMT</pubDate>
            <atom:updated>2024-08-21T00:24:24.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>DynamoDB Async Client in Spring Cloud Functions using WebFlux to create reactive Lambda functions on AWS.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9qC7TxfT8oNs5xH_Mue1Q.png" /></figure><h3>Introduction.</h3><p>In my <a href="https://aosolorzano.medium.com/using-spring-webflux-in-aws-lambda-functions-with-spring-native-and-sam-cli-2592e7bdf04f">previous tutorial</a>, I wrote about using Spring WebFlux in a Lambda function. I used a project that contained 2 Lambda functions, one that read data from a DynamoDB table and the other that updates data in the same table. In that article, I migrated only the updating function to use WebFlux, but I maintained the DynamoDB sync client to interact with the table. On this occasion, let’s try to migrate the sync client to an async DynamoDB client to exploit the benefits of the reactive programming, and let’s do it for the 2 Lambda functions. Let’s get started.</p><h3>Tooling.</h3><p>To complete this guide, you’ll need the following tools:</p><ul><li><a href="https://git-scm.com/downloads">Git</a>.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> (version 2.17.+)</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a> (version 1.97.+)</li><li><a href="https://openjdk.org/">OpenJDK</a> (version 21.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://maven.apache.org/download.cgi">Apache Maven</a> (version 3.9.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://www.docker.com/">Docker</a> engine. You can use <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> or <a href="https://github.com/abiosoft/colima">Colima</a>.</li><li>Java IDE. You can use <a href="https://www.jetbrains.com/idea/download/"><em>IntelliJ</em></a>.</li></ul><p><strong>Note</strong>: You can download the project’s source code from my <strong>GitHub</strong> <a href="https://github.com/aosolorzano/spring-aws-lambda-with-webflux-and-dynamodb-async-client">repository</a>, which contains all the configurations I made in this tutorial.</p><h3>DynamoDB Async Client.</h3><p>One of the problems I faced was using the async client without a configuration class. As we were using the sync client without a class configuration, I wanted to do the same for the async client. Wrong. So, for the async client, we must implement custom client configuration:</p><pre>@Configuration(proxyBeanMethods = false)<br>public class DynamoDbClientConfig {<br><br>    private final Environment environment;<br><br>    public DynamoDbClientConfig(Environment environment) {<br>        this.environment = environment;<br>    }<br><br>    @Bean<br>    public DynamoDbAsyncClient dynamoDbAsyncClient() {<br>        var builder = DynamoDbAsyncClient.builder()<br>            .region(DefaultAwsRegionProviderChain.builder().build().getRegion())<br>            .credentialsProvider(DefaultCredentialsProvider.builder().build());<br>        String endpointOverrideURL = this.environment.getProperty(&quot;spring.cloud.aws.endpoint&quot;);<br>        if (Objects.nonNull(endpointOverrideURL) &amp;&amp; !endpointOverrideURL.isBlank()) {<br>            builder.endpointOverride(URI.create(endpointOverrideURL));<br>        }<br>        return builder.build();<br>    }<br>}</pre><p>I still use the “<strong>spring.cloud.aws.endpoint</strong>” property to maintain the same Spring Cloud AWS module naming standard. So now, we can use our new async client to interact reactively with the DynamoDB service.</p><h3>Repository Classes.</h3><p>We now have a DynamoDB async client configured. So we can update our repository class for the read function to have the following structure:</p><pre>private final DynamoDbAsyncClient dynamoDbAsyncClient;<br><br>public CompletableFuture&lt;Map&lt;String, AttributeValue&gt;&gt; findByIdAsync(DeviceReadRequest deviceReadRequest) {<br>    HashMap&lt;String, AttributeValue&gt; keyMap = new HashMap&lt;&gt;();<br>    keyMap.put(&quot;deviceId&quot;, AttributeValue.builder().s(deviceReadRequest.deviceId()).build());<br>    keyMap.put(&quot;cityId&quot;, AttributeValue.builder().s(deviceReadRequest.cityId()).build());<br>    <br>    GetItemRequest itemRequest = GetItemRequest.builder()<br>        .key(keyMap)<br>        .tableName(&quot;Devices&quot;)<br>        .build();<br>  <br>    return this.dynamoDbAsyncClient.getItem(itemRequest)<br>        .thenApply(GetItemResponse::item)<br>        .exceptionally(exception -&gt; {<br>            throw new CityException(&quot;Error when trying to find a Device by ID.&quot;);<br>        });<br>}</pre><p>For the update function, the update is as follows:</p><pre>private final DynamoDbAsyncClient dynamoDbAsyncClient;<br><br>public CompletableFuture&lt;Void&gt; updateDeviceStatusAsync(final Device device, final DeviceOperation deviceOperation) {<br>    HashMap&lt;String, AttributeValue&gt; keyMap = new HashMap&lt;&gt;();<br>    keyMap.put(&quot;deviceId&quot;, AttributeValue.builder().s(device.id()).build());<br>    keyMap.put(&quot;cityId&quot;, AttributeValue.builder().s(device.cityId()).build());<br>    <br>    DeviceStatus newDeviceStatus = deviceOperation.equals(DeviceOperation.ACTIVATE) ?<br>        DeviceStatus.ON : DeviceStatus.OFF;<br>    <br>    UpdateItemRequest itemRequest = UpdateItemRequest.builder()<br>        .tableName(&quot;Devices&quot;)<br>        .key(keyMap)<br>        .updateExpression(&quot;SET #deviceStatus = :new_status&quot;)<br>        .expressionAttributeNames(Map.of(&quot;#deviceStatus&quot;, &quot;status&quot;))<br>        .expressionAttributeValues(Map.of(<br>            &quot;:new_status&quot;, AttributeValue.builder().s(newDeviceStatus.name()).build()))<br>        .build();<br>    <br>    return this.dynamoDbAsyncClient.updateItem(itemRequest)<br>        .thenRun(() -&gt; LOGGER.info(&quot;Successfully updated device status for Device ID: &quot; + device.id()))<br>        .exceptionally(exception -&gt; {<br>            throw new CityException(&quot;Couldn&#39;t update device status.&quot;);<br>        });<br>}</pre><p>So now, our repository classes have implemented the DynamoDB async client. Let’s implement other improvements to our functions.</p><h3>Service Classes.</h3><p>As we added a new layer of complexity, it is a good practice to create a service class to control the async responses from the repository classes. Furthermore, I will add some business validations in the following articles, so taking these service classes will help me greatly with this goal. So, for the read function, the service class is as follows:</p><pre>private final DevicesRepository devicesRepository;<br><br>public Mono&lt;Device&gt; findById(final DeviceReadRequest deviceReadRequest) {<br>    return Mono.fromCompletionStage(() -&gt; this.devicesRepository.findByIdAsync(deviceReadRequest))<br>        .handle((returnedItem, sink) -&gt; {<br>            if (Objects.isNull(returnedItem) || returnedItem.isEmpty()) {<br>                sink.error(new ResourceNotFoundException(&quot;No device found with the provided ID.&quot;));<br>                return;<br>            }<br>            sink.next(this.deviceMapper.mapToDevice(returnedItem));<br>        });<br>}</pre><p>For the update function, the update is as follows:</p><pre>private final DevicesRepository devicesRepository;<br><br>public Mono&lt;Void&gt; updateDeviceStatus(final EventBridgeRequest eventBridgeRequest) {<br>    return Mono.fromCompletionStage(() -&gt; this.devicesRepository.findByIdAsync(eventBridgeRequest.detail()))<br>        .flatMap(returnedItem -&gt; {<br>            if (Objects.isNull(returnedItem) || returnedItem.isEmpty()) {<br>                return Mono.error(new ResourceNotFoundException(&quot;No device found with the provided ID.&quot;));<br>            }<br>            Device device = this.deviceMapper.mapToDevice(returnedItem);<br>            return Mono.just(device);<br>        })<br>        .flatMap(device -&gt; Mono.fromCompletionStage(<br>            () -&gt; this.devicesRepository.updateDeviceStatusAsync(device, eventBridgeRequest.detail().deviceOperation())<br>        ));<br>}</pre><p>We have configured our repository and service classes for our 2 Lambda functions with these changes.</p><p>The function classes don’t need to be updated with significant changes, so we can continue with our tutorial.</p><h3>Running GraalVM Tracing Agent.</h3><p>As we updated our Lambda functions dependencies and logic, it is a good idea to update the native image files generated in our previous tutorial for the Trancing Agent to avoid errors at runtime concerning dynamic references. So, let’s execute the following command from the project’s root folder, one function at a time, to deploy the function with the agent:</p><p><strong>NOTE</strong>: Please review my <a href="https://aosolorzano.medium.com/executing-graalvm-tracing-agent-with-spring-boots-docker-compose-plugin-in-a-lambda-function-649d84b8eb52">previous tutorial</a> for the latest updates concerning this topic from the “Tracing Agent in POM files” section onwards.</p><pre>mvn clean process-classes                           \<br>    -f functions/device-read-function/pom.xml       \<br>    -P tracing-agent<br><br>mvn clean process-classes                           \<br>    -f functions/device-update-function/pom.xml     \<br>    -P tracing-agent</pre><p>Navigate to the “<strong>functions/city-read-function/src/test/http/local.http”</strong> file for the read Lambda function, and execute all requests as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fasY6wY64ynD2IrznExBQA.png" /></figure><p>Copy the generated files from the Tracing Agent to the function’s resources folder with the following command:</p><pre>cp -rf functions/device-read-function/target/native-image/*                         \<br>       functions/device-read-function/src/main/resources/META-INF/native-image</pre><p>Next, go to the “<strong>functions/city-update-function/src/test/http/local.http”</strong> file for the read Lambda function, and execute all requests as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7Hu9wN3pwulpCeeygx-qg.png" /></figure><p>As we did with the read function, copy the generated files from the Tracing Agent to the update function’s resources folder:</p><pre>cp -rf functions/device-update-function/target/native-image/*                       \<br>       functions/device-update-function/src/main/resources/META-INF/native-image</pre><p>We have generated and copied the Tracing Agent files into each function’s source code to build our native images safely.</p><h3>Deploying to AWS using SAM CLI.</h3><p>As we did in our previous tutorial, you must execute the following commands inside the &lt;<strong>functions</strong>&gt; directory, where is the SAM config files:</p><pre>sam build<br><br>sam deploy                                       \<br>    --parameter-overrides SpringProfile=&#39;dev&#39;    \<br>    --no-confirm-changeset                       \<br>    --disable-rollback                           \<br>    --profile &#39;your-aws-profile&#39;</pre><p>After a successful deployment, you can run the following command to invoke the read function on AWS from the project’s root directory:</p><pre>aws lambda invoke                           \<br>  --function-name &#39;city-data-function&#39;      \<br>  --payload file://functions/city-data-function/src/test/resources/requests/valid/lambda-valid-id-request.json \<br>  --cli-binary-format raw-in-base64-out     \<br>  --profile &#39;your-aws-profile&#39;              \<br>  ~/Downloads/response.json</pre><p>You can open the ~/Downloads/response.json to see the response.</p><p>Then, execute the following command to invoke the update function on AWS from the project’s root directory:</p><pre>aws lambda invoke                               \<br>  --function-name &#39;device-update-function&#39;      \<br>  --payload file://functions/device-update-function/src/test/resources/requests/valid/lambda-valid-id-request.json \<br>  --cli-binary-format raw-in-base64-out         \<br>  --profile &#39;your-aws-profile&#39;                  \<br>  ~/Downloads/response.json</pre><p>Also, you can open the ~/Downloads/response.json to see the response.</p><p>Finally, go to the CloudWatch console to see the logs in action. You can see 2 different CWL groups, one for each Lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUw2siLpXU38oxJ-7TRscg.png" /></figure><p>The first CWL group is for the City Read function we deployed in our <a href="https://aosolorzano.medium.com/executing-graalvm-tracing-agent-with-spring-boots-docker-compose-plugin-in-a-lambda-function-649d84b8eb52">previous tutorial</a>.</p><p>For the read function, you must see something:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2xwkhTl_HAi-kcalMMJWw.png" /></figure><p>You can see the same output for the update function. We called the update function directly, but in a real scenario, this function must be called from the EventBridge service. So, to invoke our service bus, we must execute the following command:</p><pre>aws events put-events \<br>  --cli-input-json file://functions/device-update-function/src/test/resources/requests/valid/eventbridge-valid-event-request.json \<br>  --profile &#39;your-aws-profile&#39;</pre><p>With this new invocation, you must see the following output in the CWL console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4wvxZ_FOI7ACoz63NfARQ.png" /></figure><p>Notice that this time, the payload message has a JSON structure owned by the EventBridge standard. So, our update function is called correctly.</p><p>Excellent!! You have deployed 2 Lambda functions in AWS that use Spring WebFlux with the async DynamoDB client. We can also create a native Linux executable with the help of GraalVM and the Tracing Agent, so our Lambda functions are also native.</p><p>I hope this article has been helpful to you, and I’ll see you in the next one.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbda7e57e9aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executing GraalVM Tracing Agent with Spring Boot’s Docker Compose plugin in a Lambda function.]]></title>
            <link>https://aosolorzano.medium.com/executing-graalvm-tracing-agent-with-spring-boots-docker-compose-plugin-in-a-lambda-function-649d84b8eb52?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/649d84b8eb52</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 01:46:56 GMT</pubDate>
            <atom:updated>2024-08-13T01:46:56.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3pnu3lRuVm1ND0e83Nvyw.png" /></figure><h3>Introduction.</h3><p>In our <a href="https://aosolorzano.medium.com/using-spring-webflux-in-aws-lambda-functions-with-spring-native-and-sam-cli-2592e7bdf04f">previous tutorial</a>, we built a Lambda function using Spring WebFlux. That Lambda function also used Spring Native to build a native Linux executable with the help of GraalVM. I showed you an additional configuration we must implement in the Native Maven plugin only for Lambda functions. I also told you that all our City’s Lambda projects have a parent POM file that extends from Spring Boot’s parent POM. So, let’s focus on this tutorial in our parent POM file, which configures the GraalVM tracing agent for all our projects.</p><p>In another previous tutorial, I wrote about <a href="https://aosolorzano.medium.com/publishing-pom-files-in-maven-central-leveraging-on-amazon-route53-4eaa84aaef72">Publishing POM files in Maven Central</a>. Our parent POM is published there, and we start from this point. We will also use the new Spring Boot’s Docker Compose plugin to execute our <a href="https://github.com/aosolorzano/pom-to-maven-central-and-route53">City Data Lambda</a> function in conjunction with the Tracing Agent to capture all function’s interactions, the same one that we’re migrating to Spring Webflux in this tutorial.</p><p>As usual in these tutorials, we will use <a href="https://docs.spring.io/spring-boot/reference/packaging/native-image/index.html"><strong>Spring Native</strong></a> with <a href="https://www.graalvm.org/"><strong>GraalVM</strong></a> (to build a native Linux executable), <a href="https://awspring.io/"><strong>Spring Cloud AWS</strong></a>, and <a href="https://www.localstack.cloud/"><strong>LocalStack</strong></a> with <a href="https://testcontainers.com/"><strong>Testcontainers</strong></a> for integration tests.</p><h3>Tooling.</h3><p>To complete this guide, you’ll need the following tools:</p><ul><li><a href="https://git-scm.com/downloads">Git</a>.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> (version 2.17.+)</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a> (version 1.97.+)</li><li><a href="https://openjdk.org/">OpenJDK</a> (version 21.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://maven.apache.org/download.cgi">Apache Maven</a> (version 3.9.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://www.docker.com/">Docker</a> engine. You can use <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> or <a href="https://github.com/abiosoft/colima">Colima</a>.</li><li>Java IDE. You can use <a href="https://www.jetbrains.com/idea/download/"><em>IntelliJ</em></a>.</li></ul><p><strong>Note</strong>: You can download the project’s source code from my <strong>GitHub</strong> <a href="https://github.com/aosolorzano/spring-cloud-aws-with-graalvm-tracing-agent">repository</a>, which contains all the configurations I made in this tutorial.</p><h3>GraalVM Tracing Agent.</h3><p>Let’s write some Oracle official documentation about the <a href="https://docs.oracle.com/cd/F44923_01/enterprise/19/guide/reference/native-image/tracing-agent.html#tracing-agent">Tracing Agent</a> to put some context about it:</p><blockquote>The tracing agent helps to deal with features as <a href="https://github.com/oracle/graal/blob/master/substratevm/REFLECTION.md">Reflection</a>, <a href="https://github.com/oracle/graal/blob/master/substratevm/JNI.md">Java Native Interface</a>, <a href="https://github.com/oracle/graal/blob/master/substratevm/RESOURCES.md">Class Path Resources</a>, and <a href="https://github.com/oracle/graal/blob/master/substratevm/DYNAMIC_PROXY.md">Dynamic Proxy</a> in the GraalVM environment. It is applicable when the static analysis cannot automatically determine what to put into a native image and undetected usages of these dynamic features need to be provided to the generation process in the form of configuration files. The tracing agent observes the application behaviour and builds configuration files when running on the Java HotSpot VM, thus it can be enabled on the command line with the java command…</blockquote><blockquote>During execution, the agent interfaces with the JVM to intercept all calls that look up classes, methods, fields, resources or request proxy accesses. The agent then generates the <em>jni-config.json</em>, <em>reflect-config.json</em>, <em>proxy-config.json</em> and <em>resource-config.json</em> in the specified output directory. The generated files are stand-alone configuration files in JSON format which contain all intercepted dynamic accesses.</blockquote><p>Oracle defines the goal of the tracing agent very well. However, as you saw in my tutorial “<a href="https://aosolorzano.medium.com/storing-eda-events-in-dynamodb-using-a-native-lambda-function-with-graalvm-spring-cloud-functions-c32cee4775fc">Storing EDA events in DynamoDB from a Native Lambda Function</a>” from section 4, not all libraries are supported to be included in a native executable due to the exhaustive usage of Java dynamic operations, like in the case of Log4J. That’s why I have used Logback in our last tutorials for logging procedures.</p><p>Next, we will examine the other building blocks for native image generation in Spring Boot’s context.</p><h3>Spring Boot’s parent POM.</h3><p>If you visit the content of the Spring Boot parent POM (version 3.3.2), you will see a profile called &lt;<strong>native</strong>&gt; with the following content :</p><pre>&lt;profile&gt;<br>  &lt;id&gt;native&lt;/id&gt;<br>  &lt;build&gt;<br>    &lt;pluginManagement&gt;<br>      &lt;plugins&gt;<br>        ...<br>        &lt;plugin&gt;<br>          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>          &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>          &lt;configuration&gt;<br>            &lt;image&gt;<br>              &lt;builder&gt;paketobuildpacks/builder-jammy-tiny:latest&lt;/builder&gt;<br>              &lt;env&gt;<br>                &lt;BP_NATIVE_IMAGE&gt;true&lt;/BP_NATIVE_IMAGE&gt;<br>              &lt;/env&gt;<br>            &lt;/image&gt;<br>          &lt;/configuration&gt;<br>          &lt;executions&gt;<br>            &lt;execution&gt;<br>              &lt;id&gt;process-aot&lt;/id&gt;<br>              &lt;goals&gt;<br>                &lt;goal&gt;process-aot&lt;/goal&gt;<br>              &lt;/goals&gt;<br>            &lt;/execution&gt;<br>          &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>        &lt;plugin&gt;<br>          &lt;groupId&gt;org.graalvm.buildtools&lt;/groupId&gt;<br>          &lt;artifactId&gt;native-maven-plugin&lt;/artifactId&gt;<br>          &lt;configuration&gt;<br>            &lt;classesDirectory&gt;${project.build.outputDirectory}&lt;/classesDirectory&gt;<br>            &lt;requiredVersion&gt;22.3&lt;/requiredVersion&gt;<br>          &lt;/configuration&gt;<br>          &lt;executions&gt;<br>            &lt;execution&gt;<br>              &lt;id&gt;add-reachability-metadata&lt;/id&gt;<br>              &lt;goals&gt;<br>                &lt;goal&gt;add-reachability-metadata&lt;/goal&gt;<br>              &lt;/goals&gt;<br>            &lt;/execution&gt;<br>          &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>      &lt;/plugins&gt;<br>    &lt;/pluginManagement&gt;<br>  &lt;/build&gt;<br>&lt;/profile&gt;</pre><p>This profile configuration has defined some plugins that help us build the native image. If you go to the <a href="https://start.spring.io/">Spring Initializr</a> site and generate a project using the “<strong>GraalVM Native Support</strong>” dependency, the pom file will include the following build configuration:</p><pre>&lt;build&gt;<br>  &lt;plugins&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.graalvm.buildtools&lt;/groupId&gt;<br>      &lt;artifactId&gt;native-maven-plugin&lt;/artifactId&gt;<br>    &lt;/plugin&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>So, your new Spring Boot project will use the &lt;<strong>native-maven-plugin</strong>&gt; plugin, also defined in the parent POM with some custom configuration, to build the native image.</p><p>To generate the native Linux executable, you must execute the following Maven command, indicating also the use of the &lt;<strong>native</strong>&gt; profile:</p><pre>mvn native:compile -Pnative</pre><p>Internally, Spring Boot performs an <a href="https://docs.spring.io/spring-boot/reference/packaging/native-image/introducing-graalvm-native-images.html#packaging.native-image.introducing-graalvm-native-images.understanding-aot-processing"><strong>Ahead-of-Time (AOT) Processing</strong></a> when building the native image. This approach is seen in the &lt;<strong>spring-boot-maven-plugin</strong>&gt; plugin declared in the Spring Boot parent POM file.</p><p>With these configurations in place, let’s prepare our application to be built as a native image.</p><h3>Using WebFlux in Lambda function.</h3><p>In our <a href="https://aosolorzano.medium.com/using-spring-webflux-in-aws-lambda-functions-with-spring-native-and-sam-cli-2592e7bdf04f">previous tutorial</a>, I demonstrated how to implement WebFlux in a Lambda function that updates data in a DynamoDB table. In this opportunity, let’s implement WebFlux in a Lambda function that reads data from a DynamoDB table.</p><p><strong>NOTE:</strong> I will not explain all the details in this tutorial because it has another goal. You can visit my <a href="https://aosolorzano.medium.com/using-spring-webflux-in-aws-lambda-functions-with-spring-native-and-sam-cli-2592e7bdf04f">previous tutorial</a> to learn more about this topic.</p><p>The initial function implementation has the following structure:</p><pre>@Override<br>public CityDataResponse apply(Message&lt;CityDataRequest&gt; cityIdRequestMessage) {<br>    CityDataRequest cityDataRequest = cityIdRequestMessage.getPayload();<br>    BeanValidations.validateBean(cityDataRequest);<br>    <br>    HashMap&lt;String, AttributeValue&gt; keyToGet = new HashMap&lt;&gt;();<br>    keyToGet.put(&#39;id&#39;, AttributeValue.builder().s(cityDataRequest.cityId()).build());<br>    GetItemRequest request = GetItemRequest.builder()<br>        .key(keyToGet)<br>        .tableName(&#39;Cities&#39;)<br>        .build();<br>    <br>    CityDataResponse response;<br>    Map&lt;String, AttributeValue&gt; returnedItem = this.dynamoDbClient.getItem(request).item();<br>    try {<br>        response = this.cityMapper.toCityResponse(city, HttpStatus.OK.value(), null);<br>    } catch (DynamoDbException exception) {<br>        response = new CityDataResponse(null, null, null, HttpStatus.INTERNAL_SERVER_ERROR.value(), &quot;Internal server error when trying to find City data.&quot;);<br>    }<br>    return response;<br>}</pre><p>After applying all the steps shown in the previous tutorial to use WebFlux, the method implementation is as follows:</p><pre>@Override<br>public Mono&lt;CityDataResponse&gt; apply(Message&lt;byte[]&gt; cityIdRequestMessage) {<br>    CityDataRequest cityDataRequest = OBJECT_MAPPER.readValue(cityIdRequestMessage.getPayload(), CityDataRequest.class);<br>    <br>    return Mono.just(cityDataRequest)<br>        .doOnNext(BeanValidations::validateBean)<br>        .map(this.citiesRepository::findCityById)<br>        .doOnNext(this::validateCityStatus)<br>        .map(city -&gt; this.cityMapper.toCityResponse(city, HttpStatus.OK.value(), null))<br>        .onErrorResume(CityDataFunction::handleException);<br>}</pre><p>After updating the integration tests following the new function’s method signature, the results are the follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbq-4GV6ZMBLdZlez8SDrg.png" /></figure><p>Our changes are working as expected. So, let’s build the native image locally using Docker Compose and perform some tests before deploying our Lambda function to AWS.</p><h3>Native Testing using Docker Compose.</h3><p>Let’s deploy our native Lambda function locally using Docker Compose and perform some requests to see the results:</p><pre>docker compose up --build</pre><p>Docker will build our native image and deploy it in a container using the &lt;<strong>public.ecr.aws/lambda/provided:al2023-arm64</strong>&gt; image. So we can invoke our Lambda function as it was in AWS. On the other hand, the Docker cluster will deploy a <strong>LocalStack</strong> container with the required DynamoDB table for the Lambda function interaction.</p><p>The compilation and build process will take some time. However, you can see the build process in your terminal window as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_VTIUVyIa5cXgt1oZEqM5w.png" /></figure><p>After that, you must see the following output indicating that our cluster is ready:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpYi-XEKt6U2GCGdlm3kIA.png" /></figure><p><strong>NOTE</strong>: I’m also deploying the native image in the Lambda service inside the Localstack container. So, you can perform some additional validations against the deployed function.</p><p>In another terminal window/tab, execute the following command to invoke our Lambda function, which has enabled the HTTP port to interact with the function directly, but this is for local testing only:</p><pre>curl -XPOST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; \<br>  -d @functions/city-data-function/src/test/resources/requests/valid/lambda-valid-id-request.json</pre><p>You won’t see a result because of an error in the Lambda function. If you return to the Docker Compose terminal window/tab, you will see an error like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hNZWyiOb4t8fPpNmPSBpA.png" /></figure><p>Spring couldn’t instantiate a bean required by the DynamoDB client. You can also see a named configuration file that cannot be found.</p><p>The definition of dynamic features we saw in the first section of this article could generate these kinds of errors. So, it could be a good idea to implement the GraalVM Tracing Agent to help us identify these kinds of dynamic operations before safely generating the native image.</p><h3>Tracing Agent in POM files.</h3><p>Let’s create a new Maven profile in our POM file to run our Spring Boot applications with the tracing agent enabled:</p><pre>&lt;profile&gt;<br>    &lt;id&gt;tracing-agent&lt;/id&gt;<br>    &lt;build&gt;<br>        &lt;plugins&gt;<br>            &lt;plugin&gt;<br>                &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;<br>                &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt;<br>                &lt;executions&gt;<br>                    &lt;execution&gt;<br>                        &lt;phase&gt;process-classes&lt;/phase&gt;<br>                        &lt;goals&gt;<br>                            &lt;goal&gt;exec&lt;/goal&gt;<br>                        &lt;/goals&gt;<br>                    &lt;/execution&gt;<br>                &lt;/executions&gt;<br>                &lt;configuration&gt;<br>                    &lt;executable&gt;java&lt;/executable&gt;<br>                    &lt;arguments&gt;<br>                        &lt;argument&gt;<br>                            -agentlib:native-image-agent=config-output-dir=${project.build.directory}/native-image<br>                        &lt;/argument&gt;<br>                        &lt;argument&gt;-cp&lt;/argument&gt;<br>                        &lt;classpath/&gt;<br>                        &lt;argument&gt;${start-class}&lt;/argument&gt;<br>                    &lt;/arguments&gt;<br>                    &lt;environmentVariables&gt;<br>                        &lt;SPRING_PROFILES_ACTIVE&gt;local&lt;/SPRING_PROFILES_ACTIVE&gt;<br>                    &lt;/environmentVariables&gt;<br>                &lt;/configuration&gt;<br>            &lt;/plugin&gt;<br>        &lt;/plugins&gt;<br>    &lt;/build&gt;<br>&lt;/profile&gt;</pre><p>You must have installed GraalVM in your local environment for this to work. Notice that in the &lt;configuration&gt; block, I’m defining the use of the &lt;<strong>java</strong>&gt; executable to run our Spring Boot main class defined in the &lt;<strong>start-class</strong>&gt; variable taken from the parent POM file. Also, I’m passing some arguments to the JVM to enable the Tracing Agent to capture all application operations when running the main class.</p><p>The &lt;<strong>process-class</strong>&gt; phase is because, at this point, Maven has compiled all Java classes, so our Tracing Agent could navigate and identify the dynamics behaviors at runtime. You can use the &lt;<strong>package</strong>&gt; phase, but this is recommended when you have a JAR file already generated and want to create a native image from it.</p><p>So, we can execute the following command to run our Spring Boot application in conjunction with the Tracing Agent:</p><pre>mvn clean process-classes                  \<br>  -f functions/city-data-function/pom.xml  \<br>  -P tracing-agent</pre><p>You must see the following in your terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObFKVRJGdTb07zlZrabDFQ.png" /></figure><p>As you can see, the Spring Boot application has started, so you can begin sending requests to our Lambda function.</p><p>But wait a minute! You must have deployed the LocalStack container with the DynamoDB service enabled to allow the function to interact with the &lt;Cities&gt; table, correct? However, I would like to improve this process by starting the Tracing Agent and the LocalStack container in the same process. Let’s do that in the following section.</p><h3>Spring Boot’s Docker Compose plugin.</h3><p>From Spring Boot version 3.1.0, you can deploy your application with a definition of a Docker Compose together. So I created a &lt;<strong>compose.yaml</strong>&gt; file inside the &lt;<strong>functions/city-data-function/tools/spring&gt;</strong> directory with the following content:</p><pre>services:<br>  localstack:<br>    image: &quot;localstack/localstack:latest&quot;<br>    ports:<br>      - &quot;4566:4566&quot;<br>    env_file:<br>      - spring.env<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>      - ../../src/test/resources/localstack/table-data.json:/var/lib/localstack/table-data.json<br>      - ../../src/test/resources/localstack/table-setup.sh:/etc/localstack/init/ready.d/table-setup.sh</pre><p>Notice I’m defining the <strong>LocalStack</strong> service only. I don’t need another container definition to execute my Lambda function. Notice that I’m also adding inside the LocalStack container’s volume the same files I’m using in the &lt;compose.yaml&gt; file located in the project’s root directory. So, we can reuse our configurations here, too.</p><p>For this to work, you must add the following Spring Boot dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-docker-compose&lt;/artifactId&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>    &lt;optional&gt;true&lt;/optional&gt;<br>&lt;/dependency&gt;</pre><p>As I’m using a &lt;<strong>local</strong>&gt; Spring profile to configure my application for local deployment, I need to update the &lt;<strong>local-application.properties</strong>&gt; file with the following configurations:</p><pre>logging.level.web=debug<br><br>spring.main.web-application-type=reactive<br>spring.cloud.function.web.export.enabled=true<br><br>spring.cloud.aws.region.static=us-west-2<br>spring.cloud.aws.credentials.accessKey=test<br>spring.cloud.aws.credentials.secretKey=test<br>spring.cloud.aws.endpoint=http://localhost:4566<br><br>spring.docker.compose.enabled=true<br>spring.docker.compose.lifecycle-management=start_and_stop<br>spring.docker.compose.file=functions/city-data-function/tools/spring/compose.yaml </pre><p>The &lt;spring.cloud.aws&gt; properties are used for the Spring Cloud AWS dependency. The &lt;<strong>spring.cloud.aws.endpoint</strong>&gt; property has the value of &lt;<strong>http://localhost:4566</strong>&gt;, which is the endpoint of the LocalStack container.</p><p>The &lt;spring.docker.compose&gt; properties are used for the Spring Docker Compose dependency. The &lt;<strong>spring.docker.compose.file</strong>&gt; has the path to our previous &lt;<strong>compose.yaml</strong>&gt; file.</p><p>To start the Spring Boot application, you can execute our Maven command again with the &lt;<strong>tracing-agent</strong>&gt; profile. But this time, you will see some log messages related to the Docker Compose plugin:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*neV8v1lgDbo36SVDmmv_xQ.png" /></figure><p>Now, you can invoke the Lambda function directly using the following commands:</p><pre>curl -H &quot;Content-Type: application/json&quot; &quot;http://localhost:8080/findByIdFunction&quot; \<br>  -d @functions/city-data-function/src/test/resources/requests/valid/lambda-valid-id-request.json<br>  <br>curl -H &quot;Content-Type: application/json&quot; &quot;http://localhost:8080/findByIdFunction&quot; \<br>  -d @functions/city-data-function/src/test/resources/requests/non-valid/lambda-wrong-uuid-request.json</pre><p>I chose these 2 requests for the Tracing Agent to capture both the successful case and the one that produces responses with an error code.</p><p>In the other terminal window/tab, you will see log messages concerning the request process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDFqFtsAp_4bHvviinQo3A.png" /></figure><p>After that, you must execute the following command to copy the generated files from the Tracing Agent with the findings of the function’s operation:</p><pre>cp -rf functions/city-data-function/target/native-image/* \<br>  functions/city-data-function/src/main/resources/META-INF/native-image</pre><p>Notice that the generated files by the Tracing Agent are located in the Maven &lt;target&gt; folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltcdzp9ihxmV0MInIbB6MA.png" /></figure><p>These files must now be situated inside the &lt;<strong>META-INF/native-image</strong>&gt; as follows so the GraalVM build process can take these findings to generate the native image with more contextual information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWwxHATea8VzSYEDxp_Jqw.png" /></figure><p>Finally, you can execute the main project’s Docker Compose file again:</p><pre>docker compose --build</pre><p>Now, you can invoke the Lambda function deployed in Docker Compose to see the results:</p><pre>curl -XPOST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; \<br>  -d @functions/city-data-function/src/test/resources/requests/valid/lambda-valid-id-request.json</pre><p>You must see that this time, the <strong>curl</strong> command will return a valid response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZ6iMzGZz6bee309ok5WCg.png" /></figure><p>Verify that in the Docker Compose terminal, there are no errors in the log messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXZ0z26gAFUo6sWghfKygQ.png" /></figure><p>As you can see, there are no errors in the terminal window/tab, and you also have a valid JSON response from the curl command. So, we can conclude that the Tracing Agent helps a lot when generating a native image file with more context about the application execution.</p><h3>Deploying to AWS using SAM-CLI.</h3><p>As we did in our previous tutorial, you must execute the following commands inside the &lt;<strong>functions</strong>&gt; directory, where is the SAM config files:</p><pre>sam build<br><br>sam deploy                                       \<br>    --parameter-overrides SpringProfile=&#39;dev&#39;    \<br>    --no-confirm-changeset                       \<br>    --disable-rollback                           \<br>    --profile &#39;your-aws-profile&#39;</pre><p>After a successful deployment, you can run the following command to invoke the Lambda function in AWS from the project’s root directory:</p><pre>aws lambda invoke                           \<br>  --function-name &#39;city-data-function&#39;      \<br>  --payload file://functions/city-data-function/src/test/resources/requests/valid/lambda-valid-id-request.json \<br>  --cli-binary-format raw-in-base64-out     \<br>  --profile &#39;your-aws-profile&#39;              \<br>  ~/Downloads/response.json</pre><p>You can open the content of the &lt;response.json&gt; file to see the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiTL8cC9_NTNLTIEaHdLCA.png" /></figure><p>Finally, you can open the CloudWatch console to see the log messages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4xroadZKEOboiQHmDBQyw.png" /></figure><p>Excellent!! You deployed a Lambda function in AWS that uses Spring Cloud Function and Spring WebFlux, so you build a reactive Lambda function. But if that is not enough, we can also create a native Linux executable with the help of GraalVM and the Tracing Agent, so our Lambda function is also a native image.</p><p>I hope this article has been helpful to you, and I’ll see you in the next one.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649d84b8eb52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Spring WebFlux in AWS Lambda functions with Spring Native and SAM CLI.]]></title>
            <link>https://aosolorzano.medium.com/using-spring-webflux-in-aws-lambda-functions-with-spring-native-and-sam-cli-2592e7bdf04f?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/2592e7bdf04f</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 01:26:54 GMT</pubDate>
            <atom:updated>2024-08-11T01:26:54.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q0GdPkqBP0kCbr9owlgZXA.png" /></figure><h3>Introduction.</h3><p>Our <a href="https://medium.com/@aosolorzano/publishing-pom-files-in-maven-central-leveraging-on-amazon-route53-4eaa84aaef72">last tutorial</a> deployed a POM file into the Maven Central Repository to build our Lambda functions without providing parent POM files. Build tools like <a href="https://aws.amazon.com/serverless/aws-sam/"><strong>AWS</strong> <strong>SAM</strong></a><strong> </strong>to<strong> </strong>download the dependency from Maven Central. Furthermore, other projects can reuse those parent POM files to bootstrap the implementation. And talking about different projects, remember that our <a href="https://github.com/aosolorzano/city-tasks-aws-fullstack">Task Service</a> project invokes a Lambda function to update a device’s status in a <a href="https://aws.amazon.com/dynamodb/"><strong>DynamoDB</strong></a> table. For this reason, that project deployed a device table to read data and perform device updates based on task operations.</p><p>On this occasion, we’ll create a new project based on the previous article. The idea is to decouple device artifacts from the task project, making the device domain independent from task one. We’ll also add <a href="https://spring.io/reactive"><strong>Spring Reactive</strong></a> to one of the new Lambda functions to update the device status in DynamoDB.</p><p>As we worked on in previous tutorials, we will use <a href="https://docs.spring.io/spring-boot/reference/packaging/native-image/index.html"><strong>Spring Native</strong></a> with <a href="https://www.graalvm.org/"><strong>GraalVM</strong></a> (to build a native Linux executable), <a href="https://awspring.io/"><strong>Spring Cloud AWS</strong></a>, and <a href="https://www.localstack.cloud/"><strong>LocalStack</strong></a> with <a href="https://testcontainers.com/"><strong>Testcontainers</strong></a> for integration tests. So, let’s get started.</p><h3>Tooling.</h3><p>To complete this guide, you’ll need the following tools:</p><ul><li><a href="https://git-scm.com/downloads">Git</a>.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> (version 2.17.+)</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a> (version 1.97.+)</li><li><a href="https://openjdk.org/">OpenJDK</a> (version 21.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://maven.apache.org/download.cgi">Apache Maven</a> (version 3.9.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://www.docker.com/">Docker</a> engine. You can use <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> or <a href="https://github.com/abiosoft/colima">Colima</a>.</li><li>Java IDE. You can use <a href="https://www.jetbrains.com/idea/download/"><em>IntelliJ</em></a>.</li></ul><p><strong>Note</strong>: You can download the project’s source code from my <strong>GitHub</strong> <a href="https://github.com/aosolorzano/spring-aws-lambda-with-webflux-and-sam">repository</a>, which contains all the configurations I made in this tutorial.</p><h3>Lambda function for Reading Operations.</h3><p>This is the simplest one because it uses the same codebase of the Lambda function we built in a <a href="https://aosolorzano.medium.com/using-spring-cloud-aws-in-lambda-functions-to-automate-sdk-client-configurations-0e27c4beb588">previous tutorial</a>. As our last Lambda uses the synchronous <strong>DynamoDbClient</strong> class to interact with DynamoDB, we’ll use the same approach for this new Lambda function. So, it will seem like this:</p><pre>@Override<br>public DeviceDataResponse apply(Message&lt;DeviceDataRequest&gt; deviceIdRequestMessage) {<br>    DeviceDataRequest deviceDataRequest = deviceIdRequestMessage.getPayload();<br>    BeanValidations.validateBean(deviceDataRequest);<br><br>    HashMap&lt;String, AttributeValue&gt; keyMap = new HashMap&lt;&gt;();<br>    keyMap.put(Device.ID_COLUMN_NAME, AttributeValue.builder().s(deviceDataRequest.deviceId()).build());<br>    keyMap.put(Device.CITY_ID_COLUMN_NAME, AttributeValue.builder().s(deviceDataRequest.cityId()).build());<br>    GetItemRequest request = GetItemRequest.builder()<br>        .key(keyMap)<br>        .tableName(Device.TABLE_NAME)<br>        .build();<br><br>    DeviceDataResponse response;<br>    Map&lt;String, AttributeValue&gt; returnedItem = this.dynamoDbClient.getItem(request).item();<br>    if (Objects.isNull(returnedItem) || returnedItem.isEmpty()) {<br>        response = new DeviceDataResponse.Builder()<br>            .httpStatus(HttpStatus.NOT_FOUND.value())<br>            .errorMessage(&quot;Device not found.&quot;)<br>            .build();<br>    } else {<br>        Device device = this.deviceMapper.mapDevice(returnedItem);<br>        response = this.deviceMapper.mapDeviceResponse(device, HttpStatus.OK.value(), null);<br>    }<br>    return response;<br>}</pre><p>Nothing new, right? So, let’s continue with the next section, which will use the <a href="https://projectreactor.io/">Project Reactor</a> for the other Lambda function.</p><h3>Spring WebFux in Lambda functions.</h3><p>We need to use another Spring Cloud Function (SCF) dependency for this:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-starter-function-webflux&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Then, the Lamba function must be seen like this:</p><pre>@Override<br>public Mono&lt;LambdaResponse&gt; apply(Message&lt;byte[]&gt; message) {<br>    try {<br>        EventBridgeEvent event = OBJECT_MAPPER.readValue(message.getPayload(), EventBridgeEvent.class);<br>        return Mono.just(event)<br>            .doOnNext(BeanValidations::validateBean)<br>            .doOnNext(this::validateCityStatus)<br>            .doOnNext(this.deviceRepository::updateDeviceStatus)<br>            .then(Mono.just(new LambdaResponse.Builder().statusCode(HttpStatus.NO_CONTENT.value()).build()))<br>            .onErrorResume(UpdateStatusFunction::handleException);<br>    } catch (IOException exception) {<br>        return Mono.error(new RuntimeException(&quot;Error deserializing the request&quot;, exception));<br>    }<br>}</pre><p>You must notice two differences in the previous code regarding the previous section’s code:</p><ul><li>I used “<strong>byte[]</strong>” to receive the request payload.</li><li>I used “<strong>Mono</strong>” to return the resultant value to the caller.</li></ul><p>For the first point, I think the AWS adapter we use in SCF passes the entire request to the function’s handler method in a bytes array as is. So, we must know the structure of the requesting payload beforehand to deserialize it accordingly. As the function must be called from an EventBridge event, the Java records must be as follows:</p><pre>public record EventBridgeEvent(<br>    String id,<br>    String version,<br>    String source,<br>    String account,<br>    String time,<br>    String region,<br>    List&lt;String&gt; resources,<br><br>    @JsonProperty(&quot;detail-type&quot;)<br>    String detailType,<br><br>    @Valid<br>    @NotNull<br>    EventBridgeEventDetail detail) {<br>}</pre><pre>public record EventBridgeEventDetail(<br><br>    @NotBlank<br>    @ValidUUID<br>    String deviceId,<br><br>    @NotBlank<br>    @ValidUUID<br>    String cityId,<br><br>    @NotNull<br>    DeviceOperation deviceOperation) {<br>}</pre><p>The last record is personalized because it must have the parameters we expect from the caller. In this case, we must know the device ID, the City ID where the device belongs, and the operation we must execute against that device.</p><p>With this in mind, we can deserialize the <strong>byte[] </strong>array without error:</p><pre>EventBridgeEvent event = OBJECT_MAPPER.readValue(message.getPayload(), EventBridgeEvent.class);</pre><p>This is the first step in our functions’ handler method before continuing to create the reactive flow, as we see previously.</p><p>The second point is easy to understand because our Lambda function is returning a Mono object containing a Java object with the results of the operation:</p><pre>public record LambdaResponse(<br>    int statusCode,<br>    Map&lt;String, String&gt; headers,<br>    String body) {<br>}</pre><p>But how can we know if these changes are correct before deploying our function to AWS? Well, let’s write about it.</p><h3>Integration Testing with LocalStack.</h3><p>As we said before, our Lambda function must be called from the EventBridge service, so the event message must have the following structure in JSON format:</p><pre>{<br>  &quot;version&quot;: &quot;0&quot;,<br>  &quot;id&quot;: &quot;7bf73129-1428-4cd3-a780-95db273d1602&quot;,<br>  &quot;account&quot;: &quot;123456789012&quot;,<br>  &quot;source&quot;: &quot;hiperium.city.tasks.api&quot;,<br>  &quot;time&quot;: &quot;2024-05-08T15:00:00Z-05:00&quot;,<br>  &quot;region&quot;: &quot;us-east-1&quot;,<br>  &quot;resources&quot;: [],<br>  &quot;detail-type&quot;: &quot;ExecutedTaskEvent&quot;,<br>  &quot;detail&quot;: {<br>    &quot;deviceId&quot;: &quot;37f44ed4-b672-4f81-a579-47679c0d6f31&quot;,<br>    &quot;cityId&quot;: &quot;a0ecb466-7ef5-47bf-a1ca-12f9f9328528&quot;,<br>    &quot;deviceOperation&quot;: &quot;ACTIVATE&quot;<br>  }<br>}</pre><p>So, create a couple of files with this structure to validate your function’s behavior. Then, invoke your function, sending those files from your integration test method based on your required test cases:</p><pre>@ParameterizedTest<br>@DisplayName(&quot;Non-valid requests&quot;)<br>@ValueSource(strings = {<br>    &quot;requests/non-valid/empty-device-id.json&quot;,<br>    &quot;requests/non-valid/wrong-device-uuid.json&quot;,<br>    &quot;requests/non-valid/non-existing-city.json&quot;,<br>    &quot;requests/non-valid/non-existing-device.json&quot;,<br>    &quot;requests/non-valid/existing-device-disabled-city.json&quot;<br>})<br>void givenInvalidEvents_whenInvokeLambdaFunction_thenThrowsException(String jsonFilePath) throws IOException {<br>    Function&lt;Message&lt;EventBridgeEvent&gt;, Mono&lt;LambdaResponse&gt;&gt; createEventFunction = this.getFunctionUnderTest();<br>    try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(jsonFilePath)) {<br>        assert inputStream != null;<br>        EventBridgeEvent event = TestsUtils.unmarshal(inputStream.readAllBytes(), EventBridgeEvent.class);<br>        Message&lt;EventBridgeEvent&gt; requestMessage = TestsUtils.createMessage(event);<br>        StepVerifier.create(createEventFunction.apply(requestMessage))<br>            .assertNext(response -&gt; {<br>                assertThat(response).isNotNull();<br>                // The status code should be an error code.<br>                int statusCode = response.statusCode();<br>                assertThat(statusCode &gt;= HttpStatus.OK.value() &amp;&amp; statusCode &lt;= HttpStatus.IM_USED.value()).isFalse();<br>            })<br>            .verifyComplete();<br>    }<br>}</pre><p>Notice I’m using the “@ParameterizedTest” annotation in our test method to use the JSON file’s path as test method input to call the Lambda function. Also, I’m parsing the JSON file as an “EventBridgeEvent” class before calling the Lambda function, but you can send the “byte[]” array if you prefer.</p><p>As usual in my articles, my integration test classes extend the “<strong>TestContainersBase</strong>” class, which starts the LocalStack container with the DynamoDB service to create the required table for the Lambda function:</p><pre>public abstract class TestContainersBase {<br><br>    private static final HiperiumLogger LOGGER = new HiperiumLogger(TestContainersBase.class);<br>    private static final LocalStackContainer LOCALSTACK_CONTAINER;<br><br>    static {<br>        LOCALSTACK_CONTAINER = new LocalStackContainer(DockerImageName.parse(&quot;localstack/localstack:latest&quot;))<br>            .withServices(LocalStackContainer.Service.DYNAMODB)<br>            .withCopyToContainer(MountableFile.forClasspathResource(&quot;localstack/table-setup.sh&quot;),<br>                &quot;/etc/localstack/init/ready.d/table-setup.sh&quot;)<br>            .withCopyToContainer(MountableFile.forClasspathResource(&quot;localstack/table-data.json&quot;),<br>                &quot;/var/lib/localstack/table-data.json&quot;)<br>            .withLogConsumer(outputFrame -&gt; LOGGER.info(outputFrame.getUtf8String()))<br>            .withEnv(&quot;DEBUG&quot;, &quot;0&quot;)<br>            .withEnv(&quot;LS_LOG&quot;, &quot;info&quot;)<br>            .withEnv(&quot;EAGER_SERVICE_LOADING&quot;, &quot;1&quot;);<br>        LOCALSTACK_CONTAINER.start();<br>    }<br><br>    @DynamicPropertySource<br>    public static void dynamicPropertySource(DynamicPropertyRegistry registry) {<br>        registry.add(&quot;aws.region&quot;, LOCALSTACK_CONTAINER::getRegion);<br>        registry.add(&quot;aws.accessKeyId&quot;, LOCALSTACK_CONTAINER::getAccessKey);<br>        registry.add(&quot;aws.secretAccessKey&quot;, LOCALSTACK_CONTAINER::getSecretKey);<br>        registry.add(&quot;spring.cloud.aws.endpoint&quot;, () -&gt; LOCALSTACK_CONTAINER.getEndpoint().toString());<br>    }<br>}</pre><p>When the container starts, I configure the LocalStack container to print the container’s logs using my logger object. I also passed a bash script file to create the DynamoDB table and load testing data:</p><pre> #!/bin/bash<br><br>echo &quot;&quot;<br>echo &quot;CREATING DEVICES TABLE...&quot;<br>awslocal dynamodb create-table              \<br>  --table-name &#39;Devices&#39;                    \<br>  --attribute-definitions                   \<br>    AttributeName=id,AttributeType=S        \<br>    AttributeName=cityId,AttributeType=S    \<br>  --key-schema                              \<br>    AttributeName=id,KeyType=HASH           \<br>    AttributeName=cityId,KeyType=RANGE      \<br>  --billing-mode PAY_PER_REQUEST<br><br>echo &quot;&quot;<br>echo &quot;WRITING DEVICE ITEMS...&quot;<br>awslocal dynamodb batch-write-item          \<br>  --request-items file:///var/lib/localstack/table-data.json</pre><p>With this configuration, you must see related logs printed in your terminal when executing the test methods so you can validate the correct creation of the required infra before running test methods.</p><p>If you’re using IntelliJ, you can execute all test methods directly from a test class. In our case, you must see a result like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbGtnIigZGon0NnVH7JAXQ.png" /></figure><p>You can scroll down in the test class execution to see the logs I mentioned before to validate the correct creation of your required infra in LocalStack.</p><h3>Spring Native and GraalVM.</h3><p>The configuration is straightforward, as I did in tutorials before. The main thing to do (as in many Spring Boot projects) is to extend your POM file from the Spring Boot’s parent POM file:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>    xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;<br>    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br>    &lt;parent&gt;<br>        &lt;groupId&gt;city.hiperium&lt;/groupId&gt;<br>        &lt;artifactId&gt;cities-parent-pom&lt;/artifactId&gt;<br>        &lt;version&gt;1.0.7&lt;/version&gt;<br>        &lt;relativePath/&gt;<br>    &lt;/parent&gt;<br>...<br>&lt;/project&gt;</pre><p>The only different configuration regarding Lambda functions with the traditional Spring Boot’s microservices we’re accustomed to building is in the way to enable HTTP protocols at build time and in the packaging form used for the native Linux executable:</p><pre>&lt;profiles&gt;<br>    &lt;profile&gt;<br>        &lt;id&gt;native&lt;/id&gt;<br>        &lt;build&gt;<br>            &lt;plugins&gt;<br>                &lt;plugin&gt;<br>                    &lt;groupId&gt;org.graalvm.buildtools&lt;/groupId&gt;<br>                    &lt;artifactId&gt;native-maven-plugin&lt;/artifactId&gt;<br>                    &lt;executions&gt;<br>                        &lt;execution&gt;<br>                            &lt;goals&gt;<br>                                &lt;goal&gt;build&lt;/goal&gt;<br>                            &lt;/goals&gt;<br>                            &lt;phase&gt;package&lt;/phase&gt;<br>                        &lt;/execution&gt;<br>                    &lt;/executions&gt;<br>                    &lt;configuration&gt;<br>                        &lt;imageName&gt;native&lt;/imageName&gt;<br>                        &lt;buildArgs&gt;<br>                            &lt;buildArg&gt;--enable-url-protocols=http,https&lt;/buildArg&gt;<br>                        &lt;/buildArgs&gt;<br>                    &lt;/configuration&gt;<br>                &lt;/plugin&gt;<br>                &lt;plugin&gt;<br>                    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>                    &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;<br>                    &lt;configuration&gt;<br>                        &lt;descriptors&gt;<br>                            &lt;descriptor&gt;tools/assembly/native.xml&lt;/descriptor&gt;<br>                        &lt;/descriptors&gt;<br>                        &lt;appendAssemblyId&gt;false&lt;/appendAssemblyId&gt;<br>                        &lt;finalName&gt;native-assembly&lt;/finalName&gt;<br>                    &lt;/configuration&gt;<br>                    &lt;executions&gt;<br>                        &lt;execution&gt;<br>                            &lt;id&gt;native-zip&lt;/id&gt;<br>                            &lt;goals&gt;<br>                                &lt;goal&gt;single&lt;/goal&gt;<br>                            &lt;/goals&gt;<br>                            &lt;phase&gt;package&lt;/phase&gt;<br>                            &lt;inherited&gt;false&lt;/inherited&gt;<br>                        &lt;/execution&gt;<br>                    &lt;/executions&gt;<br>                &lt;/plugin&gt;<br>            &lt;/plugins&gt;<br>        &lt;/build&gt;<br>    &lt;/profile&gt;<br>&lt;/profiles&gt;</pre><p>As the Spring Native plugin uses the “native” Maven profile to build the native executable, we’re overriding the traditional process by adding additional steps for Lambda functions, as seen in the previous configuration.</p><p>The &lt;<strong>native.xml</strong>&gt; file defined in the assembly plugin is in charge of Zip the native Linux executable with a required script file called &lt;<strong>bootstrap</strong>&gt;:</p><pre>&lt;assembly xmlns=&quot;http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2&quot;<br>          xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>          xsi:schemaLocation=&quot;http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 https://maven.apache.org/xsd/assembly-1.1.2.xsd&quot;&gt;<br>    &lt;id&gt;native-assembly&lt;/id&gt;<br>    &lt;formats&gt;<br>        &lt;format&gt;zip&lt;/format&gt;<br>    &lt;/formats&gt;<br>    &lt;baseDirectory&gt;&lt;/baseDirectory&gt;<br>    &lt;fileSets&gt;<br>        &lt;fileSet&gt;<br>            &lt;directory&gt;target&lt;/directory&gt;<br>            &lt;outputDirectory&gt;/&lt;/outputDirectory&gt;<br>            &lt;useDefaultExcludes&gt;true&lt;/useDefaultExcludes&gt;<br>            &lt;fileMode&gt;0775&lt;/fileMode&gt;<br>            &lt;includes&gt;<br>                &lt;include&gt;native&lt;/include&gt;<br>            &lt;/includes&gt;<br>        &lt;/fileSet&gt;<br>        &lt;fileSet&gt;<br>            &lt;directory&gt;tools/shell&lt;/directory&gt;<br>            &lt;outputDirectory&gt;/&lt;/outputDirectory&gt;<br>            &lt;useDefaultExcludes&gt;true&lt;/useDefaultExcludes&gt;<br>            &lt;fileMode&gt;0775&lt;/fileMode&gt;<br>            &lt;includes&gt;<br>                &lt;include&gt;bootstrap&lt;/include&gt;<br>            &lt;/includes&gt;<br>        &lt;/fileSet&gt;<br>    &lt;/fileSets&gt;<br>&lt;/assembly&gt;</pre><p>The bootstrap file is the entry point to execute the Linux executable, which internally invokes our Lambda function handler class:</p><pre>#!/bin/sh<br>set -e<br><br>cd &quot;${LAMBDA_TASK_ROOT:-.}&quot;<br><br>./native &quot;$_HANDLER&quot;</pre><p>Notice that the &lt;<strong>native</strong>&gt; script file, defined inside the previous script, has the same name as the one configured in the &lt;<strong>native-maven-plugin</strong>&gt; Maven plugin. If you decide to change the name of the native executable in the Maven plugin, don’t forget to update the bootstrap script to use the same executable filename.</p><p>We must make these minimal configurations to build our Lambda function as a native Linux executable with Spring Native and GraalVM.</p><h3>Deploying to AWS using SAM-CLI.</h3><p>As we’re using an EventBridge event bus for all our services, we must create the event bus independently:</p><pre>aws events create-event-bus                                    \<br>    --name &#39;cities-event-bus&#39;                                  \<br>    --description &quot;Event-Bus for the Hiperium City project&quot;    \<br>    --profile &#39;your-aws-profile&#39;</pre><p>Then, you must update your Lambda function definition inside your &lt;<strong>template.yaml</strong>&gt; file to refer to the previous event bus:</p><pre>DeviceUpdateFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    CodeUri: ./device-update-function<br>    FunctionName: &#39;device-update-function&#39;<br>    Handler: org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest<br>    Events:<br>      EventBridgeEvent:<br>        Type: EventBridgeRule<br>        Properties:<br>          EventBusName: &#39;cities-event-bus&#39;<br>          Pattern:<br>            source:<br>              - &#39;hiperium.city.tasks.api&#39;<br>            detail-type:<br>              - &#39;ExecutedTaskEvent&#39;<br>    Policies:<br>      - DynamoDBReadPolicy:<br>          TableName: &#39;Devices&#39;<br>      - DynamoDBWritePolicy:<br>          TableName: &#39;Devices&#39;<br>    Environment:<br>      Variables:<br>        SPRING_PROFILES_ACTIVE: &#39;dev&#39;<br>  Metadata:<br>    BuildMethod: makefile</pre><p>Notice that inside the “<strong>Events</strong>” block, we must define the event bus name and pattern. So, the event bus must dispatch events to a Lambda function based on the event pattern. So, be careful when defining the properties and values to be matched to invoke your corresponding function.</p><p>It’s crucial to add the <strong>DynamoDBReadPolicy</strong> and <strong>DynamoDBWritePolicy</strong> policies in the &lt;Policies&gt; section because before writing to a DynamoDB table, you must read the values in the table first.</p><p>The other significant roadblock is to define an event rule inside the existing event bus so EventBridge can dispatch the event message to the corresponding Lambda function:</p><pre>DeviceUpdateEventRule:<br>  Type: AWS::Events::Rule<br>  Properties:<br>    Name: &#39;device-update-event-rule&#39;<br>    EventBusName: &#39;cities-event-bus&#39;<br>    State: ENABLED<br>    EventPattern:<br>      source:<br>        - &#39;hiperium.city.tasks.api&#39;<br>      detail-type:<br>        - &#39;ExecutedTaskEvent&#39;<br>    Targets:<br>      - Arn: !GetAtt DeviceUpdateFunction.Arn<br>        Id: &#39;DeviceUpdateFunctionTarget&#39;<br>        RetryPolicy:<br>          MaximumRetryAttempts: 3<br>          MaximumEventAgeInSeconds: 300</pre><p>Then, you must execute the following commands from the &lt;functions&gt; directory to deploy the Lambda function in AWS:</p><pre>sam build<br><br>sam deploy                                       \<br>    --parameter-overrides SpringProfile=&quot;dev&quot;    \<br>    --no-confirm-changeset                       \<br>    --disable-rollback                           \<br>    --profile &#39;your-aws-profile&#39;</pre><p>After a successful deployment, execute the following command to receive all logs for the Lmanda functions deployed with your SAM template:</p><pre>sam logs --tail                     \<br>  --stack-name &#39;devices-sam-cli&#39;    \<br>  --profile &#39;your-aws-profile&#39;</pre><p>In another terminal, execute the following command from the project’s root directory to invoke the reactive Lambda function directly:</p><pre>aws lambda invoke                               \<br>  --function-name &quot;device-update-function&quot;      \<br>  --payload file://functions/device-data-function/src/test/resources/requests/valid/lambda-valid-id-request.json \<br>  --cli-binary-format raw-in-base64-out         \<br>  --profile &quot;your-aws-profile&quot;                  \<br>  ~/Downloads/response.json</pre><p>I’m using the same JSON file I used for integration tests in the previous section, but this time, I am using it to invoke the lambda function deployed in AWS. Also, notice that the response is stored in a JSON file in my downloads directory. You can execute the following command to see the content of the file:</p><pre>cat ~/Downloads/response.json | jq</pre><p>You must see the following content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUiRZnTdxwwhGKl065GTpQ.png" /></figure><p>I programmed the function to return an HTTP response code when the device update was performed successfully.</p><p>In your other terminal, you must see the following logs when executing the Lambda invoke command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvFTJS0jtJqu1TXxdMtEJA.png" /></figure><p>Finally, execute the following command to send an event to the event bus so EventBridge can dispatch the event message to our Lambda function:</p><pre>aws events put-events \<br>  --cli-input-json file://functions/device-update-function/src/test/resources/requests/valid/eventbridge-valid-event-request.json \<br>  --profile &#39;your-aws-profile&#39;</pre><p>The command will show you the event ID indicating the event message was received successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6toCZq2qgaolLAKBVEXn-A.png" /></figure><p>In your logger terminal, you must see a new group of log messages indicating that the Lambda function was called successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzKac0y604enlH1Uol16eA.png" /></figure><p>For this to work, the message events you send to your event bus must have the following JSON structure:</p><pre>{<br>  &quot;Entries&quot;: [<br>    {<br>      &quot;Source&quot;: &quot;hiperium.city.tasks.api&quot;,<br>      &quot;DetailType&quot;: &quot;ExecutedTaskEvent&quot;,<br>      &quot;Detail&quot;: &quot;{\&quot;deviceId\&quot;:\&quot;37f44ed4-b672-4f81-a579-47679c0d6f31\&quot;,\&quot;cityId\&quot;:\&quot;a0ecb466-7ef5-47bf-a1ca-12f9f9328528\&quot;,\&quot;deviceOperation\&quot;:\&quot;INACTIVATE\&quot;}&quot;,<br>      &quot;Resources&quot;: [],<br>      &quot;EventBusName&quot;: &quot;cities-event-bus&quot;<br>    }<br>  ]<br>}</pre><p>It’s important to note that the “<strong>Source</strong>” and “<strong>DetailType</strong>” values are used as event patterns I configured in the SAM template to be used as a rule to EventBridge to dispatch this message to our Lambda function.</p><h3>Automation Script Files.</h3><p>As usual, you can execute the following command from the project’s root directory to execute your required operations:</p><pre>./setup.sh</pre><p>This script will show you a little menu with a few options according to the current project status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DE-9vQdu9wNEfbE1PsNyiQ.png" /></figure><p>Enter the menu option according to your requirements. These script files will internally execute all commands you saw in this article, so you don’t need to type every command to deploy or delete the SAM project in AWS.</p><p>And that is!!! Now, you have deployed 2 Lambda functions using a SAM template file. One function reads data from a DynamoDB table, and the other writes data into the same table. However, the latter is called asynchronously and uses reactive programming to perform its objective.</p><p>I hope this article has been helpful to you, and I’ll see you in the next one.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2592e7bdf04f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Publishing POM files in  Maven Central leveraging on Amazon Route53.]]></title>
            <link>https://aosolorzano.medium.com/publishing-pom-files-in-maven-central-leveraging-on-amazon-route53-4eaa84aaef72?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eaa84aaef72</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 03:10:52 GMT</pubDate>
            <atom:updated>2024-07-20T03:10:52.806Z</atom:updated>
            <content:encoded><![CDATA[<h3>Publishing POM files in Maven Central leveraging on Amazon Route53.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJ4nOLwrrbpLrZtndjrSHg.png" /></figure><h3>Introduction.</h3><p>One of the problems I faced when working on Monorepos was the errors produced when building internal Maven projects isolatedly. For example, in our <a href="https://aosolorzano.medium.com/using-spring-cloud-aws-in-lambda-functions-to-automate-sdk-client-configurations-0e27c4beb588">previous tutorial</a>, I needed to provide the entire project using the SAM CLI because the internal Lambda function needs the parent POM file to compile and generate the native Linux executable. On the other hand, I need the parent POM because I want to control common properties in all Maven projects, like Java versions and libraries. I wouldn’t say I like the idea that Maven projects within Monorepo use different frameworks or versions of them.</p><p>In this tutorial, I’ll show you how to publish a parent POM file in the Maven Central repository so your Open Source dependencies will be accessible when compiling a Maven child project without needing the parent POM file.</p><h3>Tooling.</h3><p>To complete this guide, you’ll need the following tools:</p><ul><li><a href="https://git-scm.com/downloads">Git</a>.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> (version 2.11.+)</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a> (version 1.97.+)</li><li><a href="https://openjdk.org/">OpenJDK</a> (version 21.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://maven.apache.org/download.cgi">Apache Maven</a> (version 3.9.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://www.docker.com/">Docker</a> engine. You can use <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> or <a href="https://github.com/abiosoft/colima">Colima</a>.</li><li>Java IDE. You can use <a href="https://www.jetbrains.com/idea/download/"><em>IntelliJ</em></a>.</li></ul><p><strong>Note</strong>: You can download the project’s source code from my <strong>GitHub</strong> <a href="https://github.com/aosolorzano/pom-to-maven-central-and-route53">repository</a>, which contains all the configurations made in this tutorial.</p><h3>Maven Central Repository.</h3><p>The first thing you must do is to create your account in the <a href="https://central.sonatype.com/">Maven Central Repository</a> before deploying artifacts to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWEVnTrVbipkhNP0jy-73Q.png" /></figure><p>Then, go to your Namespaces and create a new one for your OSS project. It’s recommended to use a reverse DNS. Our project is called Hiperium City, and I own the &lt;<strong>hiperium.city</strong>&gt; domain name, I used it to create the namespace:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8c24BohEYJ4I2Yz6JTc3g.png" /></figure><p>Copy the verification key value and follow the next instructions.</p><h3>Amazon Route53.</h3><p>Go to your Hosted Zones and select your domain name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9Ka_AyiHgKWSihDjrsNhw.png" /></figure><p>Add a new record. Select TXT in the record type list, and paste the Verification Key in the value field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaC6L5AQR30opwIGDYWLsg.png" /></figure><p>You can change the Time-to-Live (TTL) value to fit your needs. As you can see, this value is evaluated in seconds.</p><p>After creating this record, you must see the following message on your main Hosted Zone page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeoSZIfcdS5gGJvuH6murg.png" /></figure><p>The message indicates that I must wait 60 seconds for Route53 to propagate this value in the authoritative DNS servers. But I chose 300 seconds in my record’s TTL, so I must wait at least 5 minutes before continuing.</p><p>You can use the following command to validate if your domain name contains your TXT register:</p><pre>dig TXT hiperium.city</pre><p>If so, continue to the following section.</p><h3>Maven Central Validation.</h3><p>Back to your Namespaces tab option in your Maven Central Repository account and click the &lt;<strong>Verify Namespace</strong>&gt; button. Accept the popup message, and you must see a yellow message indicating the verification is pending:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XY3b9sdObs7RWhql6keypg.png" /></figure><p>After another few minutes, reload the page to see if the domain name was verified. You must see a green message with the text “<strong>Verified</strong>” like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3EGxvWDMoK_6S4IVYxkTg.png" /></figure><p>It’s time to deploy our POM files into the Maven Central Repository.</p><h3>Required POM definitions.</h3><p>I don’t have an entire package to deploy into Maven Central. I only need to publish the parent POM files for Cities and Tasks projects. You can go to my Git <a href="https://github.com/hiperium/city-commons"><strong>repository</strong></a> to find a folder called &lt;java&gt;, which contains the parent POMs I will publish.</p><p>Before deploying your POM file, verify you have the required tags: coordinates (GAV), name, description, URL, license, SCM, and developer information. Your POM must look like this:</p><pre>&lt;parent&gt;<br>    &lt;groupId&gt;city.hiperium&lt;/groupId&gt;<br>    &lt;artifactId&gt;parent-pom&lt;/artifactId&gt;<br>    &lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;/parent&gt;<br>&lt;artifactId&gt;city-functions-parent&lt;/artifactId&gt;<br>&lt;version&gt;1.0.0&lt;/version&gt;<br>&lt;packaging&gt;pom&lt;/packaging&gt;<br><br>&lt;name&gt;${project.groupId}:${project.artifactId}&lt;/name&gt;<br>&lt;description&gt;Parent POM for Lambda functions in the City Admin project.&lt;/description&gt;<br>&lt;url&gt;https://github.com/hiperium/city-commons&lt;/url&gt;<br><br>&lt;licenses&gt;<br>    &lt;license&gt;<br>        &lt;name&gt;GNU Affero General Public License v3.0&lt;/name&gt;<br>        &lt;url&gt;https://www.gnu.org/licenses/agpl-3.0.html&lt;/url&gt;<br>        &lt;distribution&gt;repo&lt;/distribution&gt;<br>    &lt;/license&gt;<br>&lt;/licenses&gt;<br>&lt;developers&gt;<br>    &lt;developer&gt;<br>        &lt;name&gt;Andres Solorzano&lt;/name&gt;<br>        &lt;email&gt;contact@hiperium.com&lt;/email&gt;<br>        &lt;organization&gt;Hiperium Inc.&lt;/organization&gt;<br>        &lt;organizationUrl&gt;https://hiperium.com&lt;/organizationUrl&gt;<br>    &lt;/developer&gt;<br>&lt;/developers&gt;<br>&lt;scm&gt;<br>    &lt;url&gt;https://github.com/hiperium/city-commons&lt;/url&gt;<br>    &lt;connection&gt;scm:git:git://github.com/hiperium/city-commons.git&lt;/connection&gt;<br>    &lt;developerConnection&gt;scm:git:ssh://git@github.com/hiperium/city-commons.git&lt;/developerConnection&gt;<br>&lt;/scm&gt;</pre><p>In the &lt;build&gt; section, you must add the Sonatype and GPG plugins before deploying artifacts to the Maven Central Repository:</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;maven-gpg-plugin&lt;/artifactId&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;id&gt;sign-artifacts&lt;/id&gt;<br>                    &lt;phase&gt;verify&lt;/phase&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;sign&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.sonatype.central&lt;/groupId&gt;<br>            &lt;artifactId&gt;central-publishing-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;0.5.0&lt;/version&gt;<br>            &lt;extensions&gt;true&lt;/extensions&gt;<br>            &lt;configuration&gt;<br>                &lt;publishingServerId&gt;central&lt;/publishingServerId&gt;<br>            &lt;/configuration&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt; </pre><p>Then, go to your account settings in the Maven Central Repository and generate a <strong>User Token</strong> to validate your credentials when deploying:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTUjx83GFYXSqTMcSEI0Jw.png" /></figure><p>Copy your credentials in the &lt;servers&gt; section inside your Maven &lt;<strong>settings.xml</strong>&gt; file:</p><pre>&lt;server&gt;<br>    &lt;id&gt;central&lt;/id&gt;<br>    &lt;username&gt;&lt;!-- your token username --&gt;&lt;/username&gt;<br>    &lt;password&gt;&lt;!-- your token password --&gt;&lt;/password&gt;<br>&lt;/server&gt;</pre><p>Finally, execute the following Maven command to deploy the POM file:</p><pre>./mvnw deploy -f city-data-function/pom.xml</pre><p>I got the following error concerning a GPG key to sign the artifact:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFu7tAOJG1akll0oZ_jEVg.png" /></figure><p>If you get the same error as I do, you must create a GPG key and perform additional configurations to the previous ones.</p><h3>GnuPG.</h3><p>I run the GPG command as follows to know the version I’m using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NGybJ9fqr4y-SUSwxtyOQ.png" /></figure><p>Then, execute the following command to create a new GPG key.</p><pre>gpg --gen-key</pre><p>The command will ask for your name and email to generate a new key. It also asks for a passphrase to complete the procedure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zg39FAy-NU00i8_W3uldw.png" /></figure><p>Verify your GPG key was effectively created with the following command:</p><pre>gpg --list-keys</pre><p>The value of your key ID is the last 8 digits in the text shown in the &lt;<strong>pub</strong>&gt; row. You can also verify this by executing the following command that lists the keys in a hexadecimal format:</p><pre>gpg --list-signatures --keyid-format 0xshort</pre><p>Add the key value shown in the &lt;<strong>sig 3</strong>&gt; row in your &lt;<strong>settings.xml</strong>&gt; file using a new profile:</p><pre>&lt;profile&gt;<br>    &lt;id&gt;cental&lt;/id&gt;<br>    &lt;activation&gt;<br>        &lt;activeByDefault&gt;true&lt;/activeByDefault&gt;<br>    &lt;/activation&gt;<br>    &lt;properties&gt;<br>        &lt;gpg.keyname&gt;&lt;!-- your GPG key--&gt;&lt;/gpg.keyname&gt;<br>    &lt;/properties&gt;<br>&lt;/profile&gt;</pre><p>Note the definition of the &lt;<strong>gpg.keyname</strong>&gt; property variable. This must be used when updating your POM file concerning the GPG plugin as follows:</p><pre>&lt;plugin&gt;<br>    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>    &lt;artifactId&gt;maven-gpg-plugin&lt;/artifactId&gt;<br>    &lt;executions&gt;<br>        &lt;execution&gt;<br>            &lt;id&gt;sign-artifacts&lt;/id&gt;<br>            &lt;phase&gt;verify&lt;/phase&gt;<br>            &lt;goals&gt;<br>                &lt;goal&gt;sign&lt;/goal&gt;<br>            &lt;/goals&gt;<br>            &lt;configuration&gt;<br>                &lt;keyname&gt;${gpg.keyname}&lt;/keyname&gt;<br>                &lt;gpgArguments&gt;<br>                    &lt;arg&gt;--pinentry-mode&lt;/arg&gt;<br>                    &lt;arg&gt;loopback&lt;/arg&gt;<br>                &lt;/gpgArguments&gt;<br>            &lt;/configuration&gt;<br>        &lt;/execution&gt;<br>    &lt;/executions&gt;<br>&lt;/plugin&gt;</pre><p>The &lt;<strong>gpgArguments</strong>&gt; block lets you enter the key’s passphrase from the terminal. This is useful if you don’t have an interactive one.</p><p>If you don’t want to enter your passphrase every time you wish to perform a Maven deployment, add a server configuration in your &lt;<strong>settings.xml</strong>&gt; file:</p><p><strong>IMPORTANT</strong>: Maven will warn you when using this method because you expose sensitive information in a known file.</p><pre>&lt;server&gt;<br>    &lt;id&gt;gpg.passphrase&lt;/id&gt;<br>    &lt;passphrase&gt;&lt;!-- your GPG passphrase --&gt;&lt;/passphrase&gt;<br>&lt;/server&gt;</pre><p>Then, modify your &lt;<strong>maven-gpg-plugin</strong>&gt; configuration as follows:</p><pre>&lt;configuration&gt;<br>    &lt;keyname&gt;${gpg.keyname}&lt;/keyname&gt;<br>    &lt;passphrase&gt;${gpg.passphrase}&lt;/passphrase&gt;<br>&lt;/configuration&gt;</pre><p>With this alternative, you don’t need to enter the passphrase every time you execute a Maven deployment command.</p><p>It’s essential to publish your GPG public key to a <strong>GPG keyserver</strong> so the Maven Central Repository can verify the signature of the files you’re trying to publish. Execute the following command to perform this requirement:</p><pre>gpg --keyserver keyserver.ubuntu.com  \<br>    --send-keys &lt;your-public-key&gt;</pre><p>If you get an error like this: “<strong><em>gpg: keyserver send failed: No keyserver available</em></strong><em>,” </em>try to execute the following commands to use a standard server resolver in the &lt;<strong>dirmngr</strong>&gt; process, which is part of the GPG command:</p><pre>gpgconf --kill dirmngr<br>dirmngr --daemon --standard-resolver</pre><p>Then, try to execute the GPG command to export your public key. You can verify if your key was sent to the GPG server executing the following:</p><pre>gpg --keyserver keyserver.ubuntu.com  \<br>    --recv-keys &lt;your-public-key&gt;</pre><p>You must see something like the following message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIkIMbXwf8d5I-nv2KdEZw.png" /></figure><p>You have configured and published a new GPG key, which Maven Central must use to validate your signed files before publishing.</p><h3>Maven Central deployment.</h3><p>Try to execute the Maven deploy command again to see the results. The command will deploy your artifact(s) to the Maven Central Repository and wait for its validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xzszmg2Efo1292JKgc68ag.png" /></figure><p>After a few seconds, you must see the following output if everything is ok:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KB9vhjwK2ynzEujgPANrzQ.png" /></figure><p>Then, go to your <strong>Deployments</strong> option in your Sonatype account and verify if a deployment needs validation before proceeding with the publishing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puKhNBqNGs8kzswT7bnJkg.png" /></figure><p>If you agree, click the &lt;<strong>Publish</strong>&gt; button to accept the procedure. Then, you must see that your deployment is publishing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS5sF70B96OAJjBmyRLc5A.png" /></figure><p>You can click the &lt;<strong>Refresh</strong>&gt; button to verify your successful publishing. After some minutes, you will see the following status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YY0YwrDdDU4IHDiXPpzkag.png" /></figure><p>This means your Java files were published successfully in the Maven Central Repository. Therefore, you can easily reference these POM files from your internal projects.</p><h3><strong>New Code Structure.</strong></h3><p>As I said in the introduction, the idea is to modify the project we used in my <a href="https://aosolorzano.medium.com/using-spring-cloud-aws-in-lambda-functions-to-automate-sdk-client-configurations-0e27c4beb588">previous tutorial</a>. So, let’s start deleting the parent POMs because they are currently deployed in Maven Central, so we don’t need them locally. The structure of the Lambda project must be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbmQQYbVsu7xDnnMpgCPFQ.png" /></figure><p>I moved the SAM config files from the root directory to the &lt;<strong>city-data-function</strong>&gt; directory. There is no patent POM file in the root directory, so I also moved the <strong>Maven Wrapper</strong> artifacts into the &lt;functions&gt; directory because we have Java projects in that directory.</p><p>Now, we can build our Lambda function using SAM as usual, and Maven can resolve POM files from Maven Central from the builder container. So first, delete the &lt;<strong>city</strong>&gt; directory from your Maven local directory:</p><pre>rm -rf ~/.m2/repository/city/</pre><p>Then, build the Lamba function using the following Maven command from inside the &lt;<strong>functions</strong>&gt; directory:</p><pre>./mvnw clean compile -f functions/pom.xml</pre><p>Notice that Maven tries to download the required dependencies from the Central Repository:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGCxSvuGa0BcoZNwQMbjVw.png" /></figure><p>It’s working!! Now, let’s try to build our Lambda function using AWS SAM, as we did in the previous tutorial.</p><h3>SAM Build &amp; Deployment.</h3><p>Let’s execute the following command from the project’s root directory to use the automated deployment:</p><pre>./start.sh</pre><p>Select option 2, which executes the SAM build and then the SAM deployment commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bfvwgw39j9TlxyILEJB4Q.png" /></figure><p>The build process will be performed inside a Docker container managed by SAM. It doesn’t matter if you have the Hiperium dependencies in your Maven local repository because the builder container will try to download the required Maven dependencies from scratch. As we have our parent POMs in the Central Repository, this won’t be a problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbKtDHrp37Q_Aah-28zdmA.png" /></figure><p>As you can see, the builds succeed, meaning that all dependencies were downloaded in the first place.</p><p>Our automated script then deploys the native Linux executable to AWS and loads test data to our DynamoDB table on AWS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7jGyt18g1uLF6O9gSS0MA.png" /></figure><p>Open a new terminal tab/window and execute the following command project’s root directory to retrieve the Lambda function’s logs in real time:</p><pre>sam logs -n &quot;CityDataFunction&quot;            \<br>  --stack-name &quot;city-data-function-dev&quot;   \<br>  --tail                                  \<br>  --profile &quot;your-aws-profile&quot;</pre><p>Return to your original terminal tab/window and invoke your Lambda function deployed in AWS using the following command:</p><pre>aws lambda invoke                       \<br>  --function-name &quot;city-data-function&quot;  \<br>  --payload file://functions/city-data-function/src/test/resources/requests/lambda-valid-id-request.json \<br>  --cli-binary-format raw-in-base64-out \<br>  --profile &quot;your-aws-profile&quot; response.json</pre><p>Then, go to your Lamba’s logs terminal tab/window, and you must see an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfA9m1ltc96KF2YQcEd1PA.png" /></figure><p>Finally, print the content of the &lt;response.json&gt; to validate the response. You must see a content like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ro5nYVUMv36s5cw8qs8X8Q.png" /></figure><p>And that’s it!! Now, we have deployed our Lambda function to AWS using SAM. More importantly, our parent POMs are deployed in the Maven Central Repository, so we don’t need to specify them to the build tools to avoid compilation errors.</p><p>I hope this article has been helpful to you, and I’ll see you in the next one.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eaa84aaef72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Spring Cloud AWS in Lambda functions to automate SDK client configurations.]]></title>
            <link>https://aosolorzano.medium.com/using-spring-cloud-aws-in-lambda-functions-to-automate-sdk-client-configurations-0e27c4beb588?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e27c4beb588</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 23:11:16 GMT</pubDate>
            <atom:updated>2024-07-12T23:11:16.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eWBiXaYPomUOOx0AC9K7QQ.png" /></figure><h3>Introduction.</h3><p>In our <a href="https://medium.com/@aosolorzano/fullstack-app-on-aws-using-ionic-angular-frameworks-inside-an-nx-monorepo-with-pnpn-and-amplify-588e124452e4">previous tutorial</a>, I used a fullstack project to talk about the configuration of a Monorepo to store a Spring Boot project for the backend and Angular for the front-end. In the case of the backend, I also used a Lambda function to store the event’s data from an ECS service in a DynamoDB table. I used Spring Cloud Function to configure and deploy the function artifact into AWS Lambda for this case. We did this using a Native Linux Executable built using Spring Native with GraalVM and Java 17.</p><p>So, let’s create a new Lambda function using the same technologies, upgrading the Java version to 21 and using a new dependency called <a href="https://spring.io/projects/spring-cloud-aws"><strong>Spring Cloud AWS</strong></a>, which helps us automate the creation of AWS SDK clients, like the DynamoDB client.</p><h4>Tooling.</h4><p>To complete this guide, you’ll need the following tools:</p><ul><li><a href="https://git-scm.com/downloads">Git</a>.</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> (version 2.11.+)</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a> (version 1.97.+)</li><li><a href="https://openjdk.org/">OpenJDK</a> (version 21.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://maven.apache.org/download.cgi">Apache Maven</a> (version 3.9.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://www.docker.com/">Docker</a> engine. You can use <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> or <a href="https://github.com/abiosoft/colima">Colima</a>.</li><li>Java IDE. You can use <a href="https://www.jetbrains.com/idea/download/"><em>IntelliJ</em></a>.</li></ul><p><strong>Note 1</strong>: You can download the project’s source code from my <strong>GitHub</strong> <a href="https://github.com/aosolorzano/spring-aws-lambda-with-graalvm-and-sam">repository</a>, which contains all the configurations made in this tutorial.</p><p><strong>Note 2:</strong> This is an initial project configuration. The structure of this project may be unfamiliar to you because it is intended to belong to a Monorepo. I’ll be adding more building blocks in the future, such as an Angular project or another Lambda function. In this case, the Monorepo will make more sense to you.</p><h3>Dependencies.</h3><p>As I said before, I’ll use the Lambda function created in my previous tutorial as a baseline for the project structure for this tutorial. I’ll remove the &lt;<strong>software.amazon.awssdk</strong>&gt; dependency in favor of the &lt;<strong>spring-cloud-aws-dependencies</strong>&gt; dependency in the parent POM file:</p><pre>&lt;dependencyManagement&gt;<br>    &lt;dependencies&gt;<br>        ...<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;io.awspring.cloud&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-cloud-aws-dependencies&lt;/artifactId&gt;<br>            &lt;version&gt;3.0.0&lt;/version&gt;<br>            &lt;type&gt;pom&lt;/type&gt;<br>            &lt;scope&gt;import&lt;/scope&gt;<br>        &lt;/dependency&gt;<br>    &lt;/dependencies&gt;<br>&lt;/dependencyManagement&gt;</pre><p>Then, add the following dependencies to configure the DynamoDB client in our project automatically:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.awspring.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-aws-starter&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.awspring.cloud&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-cloud-aws-starter-dynamodb&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>In the case of <a href="https://testcontainers.com/"><strong>Testcontainers</strong></a>, I removed the &lt;testcontainers-bom&gt; dependency in favor of the &lt;spring-boot-testcontainers&gt; dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-testcontainers&lt;/artifactId&gt;<br>    &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>A new feature in Spring Boot 3.2 was the <a href="https://docs.docker.com/compose/"><strong>Docker Compose</strong></a> support. This feature will be helpful for testing as we will execute integration tests with Testcontainers:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-docker-compose&lt;/artifactId&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>    &lt;optional&gt;true&lt;/optional&gt;<br>&lt;/dependency&gt;</pre><p>I’ll discuss the configuration and use of this dependency later in the tutorial.</p><p>Finally, I removed the use of Lombok from our project. I’m using Spring Native with GraalVM, and this library frequently uses reflection. So, I don’t want to depend much on this kind of library because of the risk of errors in generating the native Linux executable in the future. Furthermore, let’s use Java records instead ;)</p><h3>Testcontainers with LocalStack.</h3><p>As usual, I’ll use Testcontainers to validate the integration between the Lambda function code and DynamoDB. So, I’ll preserve the same strategy as in our previous tutorial, using a parent class to configure the <a href="https://www.localstack.cloud/"><strong>LocalStack</strong></a> service with DynamoDB for integration tests:</p><pre>LOCALSTACK_CONTAINER = new LocalStackContainer(DockerImageName.parse(&quot;localstack/localstack:3.5&quot;))<br>    .withServices(LocalStackContainer.Service.DYNAMODB)<br>    .withCopyToContainer(MountableFile.forClasspathResource(&quot;localstack/table-setup.sh&quot;),<br>        &quot;/etc/localstack/init/ready.d/table-setup.sh&quot;)<br>    .withCopyToContainer(MountableFile.forClasspathResource(&quot;localstack/table-data.json&quot;),<br>        &quot;/var/lib/localstack/table-data.json&quot;);<br><br>LOCALSTACK_CONTAINER.start();</pre><p>As you see, I’m only using the DynamoDB service for the integration tests. Likewise, I’m mounting 2 files. The first one is to create the DynamoDB table when the LocalStack container is starting:</p><pre>#!/bin/bash<br><br>echo &quot;&quot;<br>echo &quot;CREATING DYNAMODB TABLE...&quot;<br>awslocal dynamodb create-table                \<br>  --table-name &#39;Cities&#39;                       \<br>  --attribute-definitions                     \<br>    AttributeName=id,AttributeType=S          \<br>  --key-schema                                \<br>    AttributeName=id,KeyType=HASH             \<br>  --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5<br><br>echo &quot;&quot;<br>echo &quot;WRITING ITEMS INTO DYNAMODB...&quot;<br>awslocal dynamodb batch-write-item  \<br>  --request-items file:///var/lib/localstack/table-data.json</pre><p>Notice that I’m loading some testing data into the “Cities” table at the end of the bash file. That’s the objective of the second file I’m loading into the LocalStack container:</p><pre>{<br>  &quot;Cities&quot;: [<br>    {<br>      &quot;PutRequest&quot;: {<br>        &quot;Item&quot;: {<br>          &quot;id&quot;: {<br>            &quot;S&quot;: &quot;a0ecb466-7ef5-47bf-a1ca-12f9f9328528&quot;<br>          },<br>          &quot;name&quot;: {<br>            &quot;S&quot;: &quot;Hiperium City&quot;<br>          },<br>          &quot;status&quot;: {<br>            &quot;S&quot;: &quot;ACT&quot;<br>          },<br>          ...<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>Then, we must specify the same parent class, the AWS properties to be used by the DynamoDB client to interact with the LocalStack container:</p><pre>@DynamicPropertySource<br>public static void dynamicPropertySource(DynamicPropertyRegistry registry) {<br>    registry.add(&quot;aws.region&quot;, LOCALSTACK_CONTAINER::getRegion);<br>    registry.add(&quot;aws.accessKeyId&quot;, LOCALSTACK_CONTAINER::getAccessKey);<br>    registry.add(&quot;aws.secretAccessKey&quot;, LOCALSTACK_CONTAINER::getSecretKey);<br>    registry.add(&quot;spring.cloud.aws.endpoint&quot;, () -&gt; LOCALSTACK_CONTAINER.getEndpoint().toString());<br>}</pre><p>I’m using the LOCALSTACK_CONTAINER static variable to obtain the running container information, such as the region, credentials, and, more importantly, the AWS endpoint with which to interact.</p><p>The test classes must extend our parent class, which initializes the LocalStack container before executing the test methods:</p><pre>@ActiveProfiles(&quot;test&quot;)<br>@FunctionalSpringBootTest(classes = FunctionalApplication.class)<br>class FunctionalApplicationTest extends TestContainersBase {<br>    <br>    // The rest of the test class.<br>}</pre><p>Recall I’m using the same project structure as in our previous tutorials, so the content of the test methods has the same goal: find the function bean and invoke it. You can also execute the entire test class directly in the IDE if you’re using IntelliJ:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nu-pQOyTbQhBnN7LK9AkFQ.png" /></figure><p>In this case, I’m only validating the happy and unhappy paths for test cases. If you prefer, you can add more test cases.</p><h3>Configuring DynamoDB Client.</h3><p>From now on, we don’t have to create a configuration class for AWS SDK clients as we did in our previous tutorials with the following class:</p><pre>@Configuration<br>public class DynamoDBClientConfig {<br><br>    private final Environment environment;<br><br>    public DynamoDBClientConfig(Environment environment) {<br>        this.environment = environment;<br>    }<br><br>    @Bean<br>    public DynamoDbClient dynamoDbClient() {<br>        var builder = DynamoDbClient.builder()<br>                .region(DefaultAwsRegionProviderChain.builder().build().getRegion())<br>                .credentialsProvider(DefaultCredentialsProvider.builder().build());<br>        String endpointOverrideURL = this.environment.getProperty(PropertiesUtil.AWS_ENDPOINT_OVERRIDE_PROPERTY);<br>        if (Objects.nonNull(endpointOverrideURL) &amp;&amp; !endpointOverrideURL.isBlank()) {<br>            builder.endpointOverride(URI.create(endpointOverrideURL));<br>        }<br>        return builder.build();<br>    }<br>}</pre><p>The Spring Cloud AWS libraries now automate this configuration for us. So we have one less thing to think about.</p><p>If you’re testing the application directly from the IDE, you must specify the following system properties in your configuration file for your default Spring profile:</p><pre>spring.cloud.aws.region.static=us-west-2<br>spring.cloud.aws.credentials.accessKey=test<br>spring.cloud.aws.credentials.secretKey=test<br>spring.cloud.aws.endpoint=http://localhost:4566</pre><p>If you plan to deploy the application inside a Docker container or a cluster using Docker Compose, you can use the standard AWS environment variables instead. The following section will discuss this further.</p><p>So now, without any configuration class to create the DynamoDB client, we use it in any Spring Bean as usual:</p><pre>@Configuration(proxyBeanMethods=false)<br>public class FunctionsConfig {<br><br>    private final DynamoDbClient dynamoDbClient;<br><br>    public FunctionsConfig(DynamoDbClient dynamoDbClient) {<br>        this.dynamoDbClient = dynamoDbClient;<br>    }<br> <br>    ...<br>}</pre><p>After that, we can invoke any CRUD operation using the DynamoDB client. In our case, we only used it to retrieve information about a City:</p><pre>@Override<br>public CityResponse apply(Message&lt;CityIdRequest&gt; cityIdRequestMessage) {<br>    ...<br>    try {<br>        Map&lt;String, AttributeValue&gt; returnedItem = this.dynamoDbClient.getItem(request).item();<br>        if (Objects.nonNull(returnedItem) &amp;&amp; !returnedItem.isEmpty()) {<br>            return this.cityMapper.toCityResponse(returnedItem);<br>        }<br>    } catch (DynamoDbException e) {<br>    }<br>}</pre><p>Notice I’m using Mapstruct to transform the returned data from DynamoDB into a Java object.</p><h4>Problems with DynamoDB Enhanced Client.</h4><p>If you plan to build a native Linux executable like me, don’t use the enhanced client because this dependency constantly uses Java reflection, and this feature is not GraalVM friendly. You can review about this topic in a <a href="https://aosolorzano.medium.com/storing-eda-events-in-dynamodb-using-a-native-lambda-function-with-graalvm-spring-cloud-functions-c32cee4775fc">previous tutorial</a> I wrote, reading section 8:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t8OqUC6zHlSc1zmo.png" /></figure><p>However, this is not always true because I haven’t had problems with Lombok, but it is evident that there is a limitation in the case of the DynamoDB Enhanced Client.</p><h3>Docker Compose support for Spring Boot.</h3><p>Using Spring Boot 3.2 or later, the framework added support for Docker Compose natively. So, if you’re using IntelliJ, you can start the application from the main class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZZeXX7egsvIFrzcR-XGVA.png" /></figure><p>This applies to regular Spring Boot web application projects and Lambda functions, as in our case.</p><p>You need to add the following properties to your default Spring profile as follows:</p><pre>spring.docker.compose.enabled=true<br>spring.docker.compose.lifecycle-management=start_and_stop<br>spring.docker.compose.file=functions/city-data-function/tools/docker/compose.yaml</pre><p>Notice that you must specify the path of your Docker Compose file inside the project directory. This is a regular compose file that configures LocalStack with the DynamoDB service to test the integration:</p><pre>services:<br>  localstack:<br>    image: &quot;localstack/localstack:3.5&quot;<br>    ports:<br>      - &quot;4566:4566&quot;<br>    env_file:<br>      - local.env<br>    volumes:<br>      - /var/run/docker.sock:/var/run/docker.sock<br>      - ../../src/test/resources/localstack/table-data.json:/var/lib/localstack/table-data.json<br>      - ../../src/test/resources/localstack/table-setup.sh:/etc/localstack/init/ready.d/table-setup.sh</pre><p>I’m importing the last 2 files to the LocalStack container, just as we did when running the integration tests using Testcontainers. So, we’re applying the same procedure for local testing with Docker Compose.</p><p>So, Spring Boot will use the previous Docker Compose file to start the docker cluster with the specified image configurations. But we must add another configuration because we’re not deploying our Lambda function as a web application. We must allow our function to be called as it was a web application:</p><pre>spring.main.web-application-type=reactive<br>spring.cloud.function.web.export.enabled=true</pre><p>It’s important to note that this configuration must be applied only for local testing. Setting this property when you deploy the function to production environments is not a good idea.</p><p>After these settings are applied, you can use the <strong>cURL</strong> command to call the Lambda function, as it has a REST endpoint:</p><pre>curl -H &quot;Content-Type: application/json&quot; &quot;http://localhost:8080/findById&quot; \<br>     -d @functions/city-data-function/src/test/resources/requests/lambda-valid-id-request.json</pre><p>After executing this command in your terminal, you must get a response like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StGm0tk8o30sXXY0W1pL0w.png" /></figure><p>Note the JSON response in the IntelliJ terminal window. This indicates that the function is interacting with the deployed LocalStack service to retrieve data from DynamoDB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4duuqCQO7ENwghH1ugGrA.png" /></figure><p>So here you have another option to test your Spring Boot projects directly from the IDE, where the framework automatically deploys a docker cluster for you before your Spring Boot application goes live.</p><h3>Deploying to AWS.</h3><p>I’ll use AWS SAM to deploy to AWS as I did in previous tutorials. So basically, we must execute the following commands:</p><p><strong>IMPORTANT</strong>: If you want to create a function from scratch, you can check out my <a href="https://aosolorzano.medium.com/eda-with-eventbridge-and-lambda-using-sam-cli-with-spring-boot-ms-on-fargate-ecs-as-event-source-9abee237be08">article</a> about using SAM CLI to create a Lambda function that receives event messages from <a href="https://aws.amazon.com/eventbridge/">Amazon EventBridge</a>.</p><pre>sam build --config-env &quot;your-config-env&quot;<br><br>sam deploy                                    \<br>  --config-env &quot;your-config-env&quot;              \<br>  --parameter-overrides SpringProfile=dev     \<br>  --disable-rollback                          \<br>  --profile &quot;your-aws-profile&quot;</pre><p>One important thing in our SAM configuration is the &lt;<strong>Metadata</strong>&gt; definition of the Lambda function in the &lt;<strong>template.yaml</strong>&gt; file:</p><pre>CityDataFunction:<br>  Type: AWS::Serverless::Function<br>  Properties:<br>    FunctionName: &quot;city-data-function&quot;<br>    Handler: &quot;org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest&quot;<br>    CodeUri: .<br>    Policies:<br>      - DynamoDBReadPolicy:<br>          TableName: !Ref CitiesTable<br>    Environment:<br>      Variables:<br>        SPRING_PROFILES_ACTIVE: !Ref SpringProfile<br>  Metadata:<br>    BuildMethod: &quot;makefile&quot;</pre><p>SAM should use a <strong>Makefile</strong> in the same project directory to generate the corresponding artifact before deploying it to AWS. In our case, we’re deploying a native Linux executable, so the content of this file must be as follows:</p><pre>build-CityDataFunction:<br>  ./mvnw -T 4C clean native:compile -Pnative -f ./functions/city-data-function -DskipTests -Ddependency-check.skip=true<br>  cp ./functions/city-data-function/target/native $(ARTIFACTS_DIR)<br>  cp ./functions/city-data-function/tools/shell/bootstrap $(ARTIFACTS_DIR)<br>  chmod 755 $(ARTIFACTS_DIR)/bootstrap</pre><p>So, our first SAM command will execute the previous Makefile, which uses Maven to build the native Linux executable. You must see the following output at the end of the SAM execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFvzfZ4j6kpq-6_XheibeA.png" /></figure><p>At the end of the command execution, SAM performs the CP commands defined in the Makefile. This directory is located inside the container where the build was executed, but in our project, SAM created a hidden folder called &lt;aws-sam&gt; with the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NW7MoI0oTJ-rIOopr70VzQ.png" /></figure><p>So when we try to deploy our function to AWS Lambda, SAM will package and deploy these artifacts for us. The following must be the result of our SAM second command execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASEQA2nA-gfq2394vYRlaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkrbLFec5fAVDuvZfNBXXg.png" /></figure><p>As our resources are deployed to AWS, let’s insert some test data into the DynamoDB table as we did previously for integration tests, this time using the CLI:</p><pre>aws dynamodb batch-write-item \<br>  --request-items file://functions/city-data-function/src/test/resources/localstack/table-data.json \<br>  --profile &quot;your-aws-profile&quot;</pre><p>You must receive the same message when executing the integration tests or when deploying the Docker Compose cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*738q9u-ARo8Xw_uh9LWfGg.png" /></figure><p>Let’s validate this by executing the following command to retrieve the existing items in our DynamoDB table on AWS:</p><pre>aws dynamodb scan               \<br>  --table-name &quot;Cities&quot;         \<br>  --profile &quot;your-aws-profile&quot;</pre><p>You must receive the following output, this time from AWS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pwDtb80JVMtOpFGJAz0qg.png" /></figure><p>Now we have data in DynamoDB, so let’s call our Lambda function. First, open a new terminal window/tab and execute the following command to get the logs in real time of our Lambda function:</p><pre>sam logs -n &#39;CityDataFunction&#39;            \<br>  --stack-name &quot;city-data-function-dev&quot;   \<br>  --tail                                  \<br>  --profile &quot;your-aws-profile&quot;</pre><p>Then, return to your original terminal window/tab and execute the following command to invoke the Lambda function in AWS:</p><pre>aws lambda invoke --function-name &quot;city-data-function&quot; \<br>  --payload file://functions/city-data-function/src/test/resources/requests/lambda-valid-id-request.json \<br>  --cli-binary-format raw-in-base64-out \<br>  --profile &quot;city-dev&quot; response.json</pre><p>You must receive an HTTP 200 response code in the terminal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUaH5Qwx-FZUFCpn-y42hw.png" /></figure><p>Open the other terminal window/tab to see the Lambda function logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyDAut5to7xsGw0f8wt4jg.png" /></figure><p>Finally, print the content of the &lt;<strong>response.json</strong>&gt; file with the &lt;<strong>cat</strong>&gt; command to see the returned data from the Lambda function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khR2-PGg5zsYytw99dOwJw.png" /></figure><p>Excellent!!. Now you can delete all created resources in AWS using the SAM command:</p><pre>sam delete                               \<br>  --stack-name &quot;city-data-function-dev&quot;  \<br>  --profile &quot;city-dev&quot;</pre><p>You must see a successful message at the end of the command execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVsXjiZro6kP5kt_8dEilA.png" /></figure><p>Perfect. Now you know how to deploy a Lambda function into AWS using SAM CLI ;)</p><h3>Automation Scripts.</h3><p>As usual, I created some bash scripts in the &lt;<strong>utils/scripts</strong>&gt; directory to automate the deployment in AWS using the same SAM commands you saw previously. You need to execute the following command from the project’s root directory:</p><pre>./start.sh</pre><p>Choose the correct option according to your needs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1rA5bd8NFkcQWEBR7YaRw.png" /></figure><p>This may not be necessary, but when you have a lot of components to deploy, as with the previous tutorial, this could be time-saving. The following is an improvement of the last project’s tutorial automation file, which I’m working on for a future article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hs9M14B-gk2x_cirNPRPJA.png" /></figure><p>This option includes AWS commands like SAM, Copilot, and Amplify. The project contains a fullstack application, but the actual one has only one component. We’re creating the front-end project and maybe an ECS cluster later.</p><p>And that’s it!! You now know a new project dependency called <strong>Spring Cloud AWS</strong> that you can use in your Spring Cloud Functions projects to decrease the number of configuration classes, which you need to create different kinds of AWS SDK clients required to interact with your AWS resources.</p><p>I hope this article has been helpful to you, and I’ll see you in the next one.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e27c4beb588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FullStack App on AWS using Ionic/Angular Frameworks inside an Nx Monorepo with PNPN and Amplify.]]></title>
            <link>https://aosolorzano.medium.com/fullstack-app-on-aws-using-ionic-angular-frameworks-inside-an-nx-monorepo-with-pnpn-and-amplify-588e124452e4?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/588e124452e4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 19:06:53 GMT</pubDate>
            <atom:updated>2023-11-29T15:16:10.873Z</atom:updated>
            <content:encoded><![CDATA[<h3>FullStack application on AWS using Ionic/Angular Frameworks inside an Nx Monorepo with PNPM and Amplify.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcWmlkJDg4zt1dq64aQ6gQ.png" /></figure><h3><strong>Introduction.</strong></h3><p>It has been some time since my last tutorial about the front-end side. My <a href="https://medium.com/@aosolorzano/storing-eda-events-in-dynamodb-using-a-native-lambda-function-with-graalvm-spring-cloud-functions-c32cee4775fc">previous tutorial</a> discussed the implementation of a Java-native Lambda function in AWS. The function was built using Spring Cloud Functions (SCF) and GraalVM. Furthermore, the project has a Java native API built with Spring Boot 3 and GraalVM. The idea is that our API service emits an event to the EventBridge service, which routes the event messages to the Lambda function. These architectures are known as Event-Driven Architecture (EDA), but in practice, they are called Event-Driven Applications (also EDA) when implemented.</p><p>Talking about EDA, it’s well-known that all <strong>Serverless</strong> architectures are EDA, but not the other way around. Concerning our project, we can ensure it is also serverless and uses some serverless services like Fargate, ELB, Lambda, EventBridge, and SQS.</p><p>But the missing piece in this puzzle is the UI component, and continuing with the Serverless way, it’s the turn of the <strong>Amplify</strong> service to participate in this solution architecture. So let’s get started.</p><h3>Tooling.</h3><p>To complete this guide, you’ll need the following tools:</p><ul><li><a href="https://git-scm.com/downloads">Git</a>.</li><li><a href="https://nodejs.org/en">Node.js</a> (version 18.+)</li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">AWS CLI</a> (version 2.11.+)</li><li><a href="https://aws.github.io/copilot-cli/docs/getting-started/install/">AWS Copilot CLI</a> (version 1.29.+)</li><li><a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html">AWS SAM CLI</a> (version 1.97.+)</li><li><a href="https://openjdk.org/">OpenJDK</a> (version 17.0.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://maven.apache.org/download.cgi">Apache Maven</a> (version 3.9.+). You can use <a href="https://sdkman.io/install">SDKMAN</a> to install it.</li><li><a href="https://www.docker.com/">Docker</a> engine. You can use <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a> or <a href="https://github.com/abiosoft/colima">Colima</a>.</li><li>Java IDE. You can use <a href="https://www.jetbrains.com/idea/download/"><em>IntelliJ</em></a>.</li></ul><p><strong>NOTE</strong>: You can download the project’s source code from my <strong>GitHub</strong> <a href="https://github.com/aosolorzano/city-tasks-aws-fullstack">repository</a>, which contains all the configurations made in this tutorial.</p><h3>Depuring Node.js installation (Optional)</h3><p>If you’re in a situation like mine, where you installed some UI libraries or tools months ago, it’s time to depurate our system. So, I’ll start removing the entire Node.js installation from my system. Also, I want to solve issues related to the lack of access permission when installing NPM packages globally. I hope to have a cleaner installation of Node.js in my system.</p><p>The idea is to have a version manager like SDKMAN where you can install the required versions of OpenJDK, Maven, or GraalVM. This tool is called NVM (Node Package Manager).</p><p>First, let’s depurate our Nodejs installation:</p><pre>$ brew uninstall npm<br>$ brew uninstall node</pre><p>If you used a GUI installer from the Nodejs site, then execute:</p><pre>$ sudo rm /usr/local/bin/node<br>$ sudo rm /usr/local/bin/npm</pre><p>Remove the “<strong>node_modules</strong>” from your system:</p><pre>$ sudo rm -rf /usr/local/lib/node_modules</pre><p>Remove the “<strong>~/.npm</strong>” and “<strong>~/.node-gyp</strong>” folders from your home directory, as they contain npm-related data:</p><pre>$ rm -rf ~/.npm ~/.node-gyp</pre><p>Verify that Node and NPM have been removed successfully:</p><pre>$ which npm<br>$ which node</pre><p>Now, let’s install the NVM tool in our systems.</p><p><strong>NOTE:</strong> When we write these lines, the latest version is <a href="https://github.com/nvm-sh/nvm/releases/tag/v0.39.5">0.39.5</a>:</p><pre>$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash</pre><p>Open a new terminal window and execute the following command to install the latest LTS version:</p><pre>$ nvm install --lts</pre><p>You must see an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKwb9GDvspt8fXjGaG5M1g.png" /></figure><p>As you can see, the latest LTS version is <strong>18.18.0</strong> of NodeJS and <strong>9.8.1</strong> of NPM. So now, we can install the required libraries for our project.</p><h3>Package management with PNPM.</h3><p>The JavaScript ecosystem boasts various package manager tools that aid developers in managing and maintaining their project dependencies. Among these, <strong>npm</strong> and <strong>yarn</strong> have been the dominant players for a long time. However, a tool that has gained attention and adoption in recent years is <strong>pnpm</strong>.</p><p>PNPM is a fast, efficient, and deterministic package manager for JavaScript. While it uses the same package.json file, its approach to package management is unique.</p><p>The principal advantage I like most is that <strong>pnpm</strong> does not duplicate packages. Instead of downloading packages repeatedly for each project, PNPM maintains a single copy of each package in a global cache and then links to these packages in <strong>node_modules</strong>. This results in considerable disk space savings and faster installations.</p><p>PNPM is an excellent alternative to traditional package managers. For large projects like monorepos, PNPM is undoubtedly a tool to consider. So, let’s install and configure it:</p><pre>$ npm install -g pnpm<br>$ pnpm setup</pre><p>So, next, let’s try to use it with the Nx tool.</p><h3>Using Nx 17 for Ionic/Angular Monorepo.</h3><p>Nx is a set of extensible dev tools for monorepos. Monorepos provides a single repository to house multiple projects (like apps and libraries), making sharing and managing code across different applications easier. While monorepos have been around for a while and are used by big tech companies like Google and Facebook, Nx brings this capability to every organization, optimizing the process and offering best practices.</p><p>Teams can easily share configurations, components, utilities, and more by organizing multiple applications and libraries within a single repository. This eliminates the redundancy of code and ensures consistency across applications. When a core component is updated, the change can seamlessly propagate across all projects that use it, providing uniformity and reducing potential errors.</p><p>That’s why I created a parent Maven POM for the back-end projects. So, I found good references when I searched for dependency management tools for web projects, maintaining a <a href="https://nx.dev/concepts/more-concepts/dependency-management#single-version-policy"><strong>single version policy</strong></a>, as we did using Maven for our back-end projects.</p><p>The idea in this section is to start an Nx project from scratch and then incrementally add the Ionic/Angular components from our previous project.</p><p>So, let’s begin installing the required tools globally:</p><pre>$ pnpm install -g nx@latest</pre><p>Then, create an empty monorepo using Nx with PNPM as a package manager:</p><pre>$ npx create-nx-workspace@latest  \<br>    --name city-tasks             \<br>    --preset=empty                \<br>    --packageManager=pnpm         \<br>    --skipGit=true                \<br>    --nxCloud=false</pre><p>After the monorepo is completed, move to the new project directory and install an <strong>Nx extension</strong> to generate Ionic/Angular projects:</p><pre>$ cd city-tasks<br>$ pnpm add --save-dev --save-exact @nxext/ionic-angular</pre><p>Now we can create a <strong>new Ionic/Angular</strong> project using the “sidemenu” template:</p><pre>$ nx generate @nxext/ionic-angular:app  \<br>    --name=city-tasks-app               \<br>    --template=sidemenu                 \<br>    --unitTestRunner=jest               \<br>    --e2eTestRunner=cypress             \<br>    --linter=eslint                     \<br>    --capacitor=true</pre><p>When using the “— directory=apps” flag, I got the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*IZ7TNw1kwDYqv07R5Tgl6w.png" /></figure><p>For this reason, I didn’t use that flag in the previous command, so we need to configure this manually.</p><p>Now, open the project using your favorite IDE to see the created files so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9LahEXi__-6tMN63Xoc1Q.png" /></figure><p>So, create the apps directory manually and move the app projects inside that directory.</p><p>You must edit the “<strong>/apps/city-tasks-app/project.json</strong>” file, updating directory paths to the new route:</p><pre>{<br>  &quot;name&quot;: &quot;city-tasks-app&quot;,<br>  &quot;sourceRoot&quot;: &quot;apps/city-tasks-app/src&quot;,<br>  &quot;targets&quot;: {<br>    &quot;build&quot;: {<br>      &quot;options&quot;: {<br>        ...<br>        &quot;index&quot;: &quot;apps/city-tasks-app/src/index.html&quot;,<br>        &quot;main&quot;: &quot;apps/city-tasks-app/src/main.ts&quot;,<br>        &quot;tsConfig&quot;: &quot;apps/city-tasks-app/tsconfig.app.json&quot;,<br>        &quot;assets&quot;: [<br>          &quot;apps/city-tasks-app/src/assets&quot;<br>        ],<br>        &quot;styles&quot;: [<br>          &quot;apps/city-tasks-app/src/styles.scss&quot;,<br>          {<br>            &quot;input&quot;: &quot;./apps/city-tasks-app/src/theme/variables.scss&quot;<br>          }<br>        ],<br>        &quot;scripts&quot;: []<br>      },<br>      ...<br>      &quot;defaultConfiguration&quot;: &quot;production&quot;<br>    },<br>    ...<br>    &quot;lint&quot;: {<br>      &quot;executor&quot;: &quot;@nx/linter:eslint&quot;,<br>      &quot;outputs&quot;: [&quot;{options.outputFile}&quot;],<br>      &quot;options&quot;: {<br>        &quot;lintFilePatterns&quot;: [<br>          &quot;apps/city-tasks-app/**/*.ts&quot;,<br>          &quot;apps/city-tasks-app/**/*.html&quot;<br>        ]<br>      }<br>    }<br>    ...<br>  }<br>}</pre><p>Accomplish the same for the “<strong>end-2-end</strong>” project. Also, look at the rest of the TS configuration files, like the “<strong>tsconfig.json</strong>” file and others.</p><p>Let’s try to build and deploy our new app locally, executing the following commands from the project’s root directory:</p><pre>$ nx build city-tasks-app<br>$ nx serve city-tasks-app</pre><p>You must see a message like the following after running the last command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2ZFYGOxAMy5gTPpIQT4LA.png" /></figure><p>So, open a new browser tab with the indicated URL to see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbxlcGOX41SRuSJXBya9-g.png" /></figure><p>So our Ionic/Angular <strong>sidemenu</strong> <strong>template</strong> is working. But before migrating the last City Task application’s components into the new repository, let’s compare the migration tasks we must perform.</p><h3>City Tasks Front-end dependencies.</h3><p>Examining the City Tasks App project documentation, I saw that we must install the following dependencies:</p><pre>$ pnpm add aws-amplify<br>$ pnpm add angular-oauth2-oidc<br>$ pnpm add animate.css<br>$ pnpm add date-fns<br>$ pnpm add date-fns-tz</pre><p>Also, we must install the <a href="https://ngrx.io/"><strong>NgRx</strong></a> framework, and as we’re using Nx in our new project, we must execute the following commands:</p><pre>$ pnpm add @ngrx/store@latest          &amp;&amp; pnpm exec nx g @ngrx/store:ng-add<br>$ pnpm add @ngrx/store-devtools@latest &amp;&amp; pnpm exec nx g @ngrx/store-devtools:ng-add<br>$ pnpm add @ngrx/effects@latest        &amp;&amp; pnpm exec nx g @ngrx/effects:ng-add<br>$ pnpm add @ngrx/router-store@latest   &amp;&amp; pnpm exec nx g @ngrx/router-store:ng-add<br>$ pnpm add @ngrx/data@latest           &amp;&amp; pnpm exec nx g @ngrx/data:ng-add</pre><p><strong>NOTE</strong>: You can review my <a href="https://aosolorzano.medium.com/using-angular-ngrx-for-a-reactive-programming-cef032ad1e7d">previous tutorial</a> when I wrote about NgRx and implemented it in the City Tasks App. That tutorial was written last year when we hadn’t implemented the IdP yet. So please review the topics related to the NgRx concepts only.</p><p>Now, install the Amplify CLI tool in our system:</p><pre>$ pnpm add -g @aws-amplify/cli</pre><p>All previous commands install the required dependencies and update the <strong>package.json</strong> file in the project’s root folder.</p><p>When I executed these commands, I got a warning message indicating that some dependencies were outdated. To fix this issue, you must run the following Nx commands:</p><pre>$ npx nx migrate latest<br>$ npx nx migrate @angular/core@latest<br>$ npx nx migrate @ngrx/store@latest</pre><p>Finally, run the following command to execute the migrations:</p><pre>$ pnpm exec nx migrate --run-migrations </pre><p>You can also execute the following command to list the outdated packages:</p><pre>$ pnpm outdated</pre><p>You can update the required packages using the PNPM command:</p><pre>$ pnpm update eslint@latest prettier@latest </pre><p>We have installed all project dependencies to migrate the existing City Task App components to the new Nx project monorepo. But before, let’s analyze the instructed steps before the migration.</p><h3>Angular 17 — New Features.</h3><p>Before migrating the existing City Tasks components into the new project monorepo with Nx, let’s examine the following Angular <a href="https://update.angular.io/?l=3&amp;v=14.0-15.0"><strong>guide</strong></a>, which provides some considerations to take into account during the migration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJZR5L-jkxEkl8_7wPf97Q.png" /></figure><p>We need to analyze all the implications of the migrations from Angular version 14 to 15 before going directly to Angular 17. We must repeat this process from 15 to 16 and 16 to 17.</p><p>Let’s describe some essential features of Angular 17:</p><ul><li>Signals.</li><li>Standalone Components.</li><li>New Template Syntax.</li><li>End-to-End testing.</li><li>Ahead-of-Time (AOT) Compilation.</li><li>EsModules (ViteJS).</li></ul><p>I don’t cover all these features here because this can become an hour-long tutorial. I promise to work on all these features in another tutorial, writing specifically on Angular 17. Our objective in this tutorial is to build a full-stack monorepo and use the tools we have been working on to deploy our applications and services into AWS.</p><p>So, let’s continue with the next steps of the tutorial.</p><h3>Amazon Cognito as Identity Provider (IdP).</h3><p>I’ve created a Git repo called “<a href="https://github.com/hiperium/hiperium-city-idp"><strong>hiperium-city-idp</strong></a>,<strong>” </strong>where you can find the Amplify commands to configure the IdP service. Remember that I’m not sharing my “.<em>amplify</em>” directory, so you must execute the following commands.</p><p><strong>NOTE</strong>: Following my previous tutorials, you might have configured and deployed the IdP service in AWS. You can skip this section or continue reading if you want to validate your configurations.</p><p>First, log in to the SSO using the helper shell script. Use your AWS profile for your <strong>Identity Provider</strong> account:</p><pre>$ hiperium-login</pre><p>Then, navigate to the cloned “hiperium-city-idp” repository and create a new branch for the pre-production environment:</p><pre>$ git checkout -b pre</pre><p>Initialize the Amplify project for this new environment:</p><pre>$ amplify init</pre><p>These are the initial config values that I’m using. Feel free to use the same or your own:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-K7M8a5HPuZhyuc_.png" /></figure><p><strong>NOTICE</strong>: idp-pre is the AWS profile I used for this configuration, and pre is the Amplify environment name.</p><p>So now, it’s time to configure our Amplify Authentication module.</p><pre>$ amplify add auth</pre><p>These are the initial config values that I’m using:</p><p><strong>NOTE</strong>: I enabled Multi-Factor Authentication (MFA) for our IdP. This is not mandatory for this tutorial, but if you want details about this configuration, please review my <a href="https://aosolorzano.medium.com/adding-amplify-auth-to-your-ionic-angular-projects-4c8b6337e4e6">previous article</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QUU6Ku2WJQsLBnCp5H6lw.png" /></figure><p>It’s important to mention the following settings regarding the previous configuration:</p><ul><li>I used &lt;<strong>localhost&gt;</strong> for OAuth redirections. In the following sections, we will update this property by adding the Amplify URL to redirect the user after a successful login when our app is deployed on AWS.</li><li>I also used &lt;<strong>https://oauth.pstmn.io/v1/browser-callback/</strong>&gt; for sign-in redirection to allow Postman to access our API endpoints using a valid JWT access token.</li></ul><p>Finally, go to the <strong>cli-inputs.json</strong> file in the “<em>amplify/backend/auth/CityIdP</em><strong>”</strong> directory and update the “<strong>userpoolClientGenerateSecret”</strong> property to true to generate a client secret to be used in the Postman tool:</p><pre>&quot;aliasAttributes&quot;: [],<br>&quot;userpoolClientGenerateSecret&quot;: true,<br>&quot;userpoolClientRefreshTokenValidity&quot;: 30,</pre><p>Finally, push these changes into your AWS account using the Amplify CLI:</p><pre>$ amplify push</pre><p>You must see the following message, which indicates a successful deployment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Llany-OmisUPDNebS9Dzjw.png" /></figure><p>So, we have deployed our <strong>IdP </strong>service into AWS. The next step is updating the City Tasks components for local deployment.</p><h3>Running Back-end as a Standalone service.</h3><p>Before running the Ionic/Angular app, we must update the &lt;<strong>envoy.yaml</strong>&gt; file to allow connections from our Ionic/Angular application. So, clone the &lt;<a href="https://github.com/aosolorzano/city-tasks-lambda-native-with-dynamodb">city-tasks-lambda-native-with-dynamodb</a>&gt; project, which has the latest version of our back-end services.</p><p>Execute the hiperium-login command again using your &lt;idp-pre&gt; profile to get a valid AWS session before obtaining the IdP endpoint by the automation scripts.</p><p><strong>IMPORTANT</strong>: editing our “/etc/hosts” file is unnecessary to redirect all HTTPS communication to the local API microservice. We are now configuring our front-end application to make accurate functional tests.</p><p>Deploy the back-end services by executing the following shell script:</p><pre>$ ./run-scripts</pre><p>Select <strong>option 1</strong> to deploy the back-end using <strong>Docker Compose</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WyxhvsaiT7c1izkyb5sfA.png" /></figure><p>Review the Docker Compose logs for the Task API service and validate that it’s running on port 8080 without errors among the other services:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4guXxInTbzLc4PgMSnkhIw.png" /></figure><p>Open a new terminal and navigate to the back-end project directory to test if the <strong>function</strong> deployed on the <strong>Docker</strong> container is working:</p><pre>$ curl -XPOST &quot;http://localhost:9000/2015-03-31/functions/function/invocations&quot; \<br>  -d @apis/city-events-function/src/test/resources/events/lambda-event-valid-detail.json</pre><p>You must see the following output in the Docker Compose terminal tap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rl4e0-Y2a1TTGFMO-T0YQQ.png" /></figure><p>Open Postman and execute the following API call to get all created tasks. Recall to configure the Authorization properties to get a valid JWT token from the IdP service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWkOWOW6TSLGcl80AtLnUw.png" /></figure><p>So, as our Events Lambda function and the Tasks API microservice are working as expected, let’s integrate our Ionic/Angular app to make functional tests.</p><h3>Running Ionic/Angular as a Standalone service.</h3><p>Go to your AWS Cognito service console and copy the <strong>User Pool ID</strong> and <strong>Client Web ID </strong>values<strong>.</strong> Paste them into the &lt;<strong>environment.ts</strong>&gt; file located in the front-end project as follows:</p><pre>export const authConfig: AuthConfig = {<br>  issuer: &#39;https://cognito-idp.&lt;AWS_REGION&gt;.amazonaws.com/&lt;YOUR_COGNITO_USER_POOL_ID&gt;&#39;,<br>  oidc: true,<br>  strictDiscoveryDocumentValidation: false,<br>  clientId: &#39;&lt;YOUR_COGNITO_APP_CLIENT_ID_WEB&gt;&#39;,<br>  redirectUri: &#39;http://localhost:4200/home/&#39;,<br>  responseType: &#39;code&#39;,<br>  scope: &#39;phone email openid profile&#39;,<br>  showDebugInformation: !environment.production<br>};</pre><p>In the same file, paste the following code to create a global variable that configures the NgRx Data to connect to our back-end service:</p><pre>export const defaultDataServiceConfig: DefaultDataServiceConfig = {<br>  root: &#39;https://localhost/api/v1&#39;,<br>  timeout: 3000,<br>  delete404OK: false,<br>  trailingSlashEndpoints: false,<br>};</pre><p>Execute the following command inside the Nx monorepo to build and run our migrated Ionic/Angular app:</p><pre>$ nx build city-tasks-app<br>$ nx serve city-tasks-app</pre><p>The last command prints the address to access our application. Open that URL in a new browser tab, and you must see the following home page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NOYsSY97Y9UriyyyqxxWw.png" /></figure><p>If you click the &lt;<strong>Login</strong>&gt; button, you must be redirected to the Cognito IdP service page to enter your credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Xh3M2YgoXaWHw-2jOrPOA.png" /></figure><p>Enter your credentials if you have created one in your IdP service, or click the &lt;<strong>Sign up</strong>&gt; link to create your account. As we mentioned before, I enabled the MFA feature, so when you create your account, you must follow the process as shown following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EhEJ_9ORaZXfyDEqrU6VUQ.png" /></figure><p>When you create your user and enter the credential, you must have access to the home page of our application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZGzVOOSFMcttAb7uvmZ0A.png" /></figure><p>Click on the &lt;Task&gt; option in the left menu to try to get the created tasks in the database, but you must have the following error in developers tools in your browser window:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umqwNePWo2e44r-_v4pLrg.png" /></figure><p>This is an issue with our self-signed TLS certificate. Accessing the Spring Boot Actuator page in another tab is the easiest way. The browser must ask you to access an insecure site:</p><pre>https://localhost/tasks-actuator/health</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQD83lLh7UcVXq1F0yKOBA.png" /></figure><p>Proceed to the unsecured site, and you must get a status message from the Spring Boot Actuator endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqC19OUsfeKqaI39E-9mQg.png" /></figure><p>Now, your browser will trust this URL, and in the subsequent calls, you won’t have a certification error by the browser. So, return to the Ionic/Angular app browser tab and refresh the page. It would be best if you did not have errors in the browser console because you’re again on the home page. Now refresh the app and click again on the &lt;Task&gt; option to see the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xyo9YWxe0VnNpm_kprzkQ.png" /></figure><p>Now we have a <strong>CORS</strong> problem. To fix this, stop the docker-compose process and update the <strong>Envoy</strong> configuration to use CORS in the filters section as shown next:</p><pre>route_config:<br>  name: local_route<br>  virtual_hosts:<br>    - name: local_api<br>      domains: [ &quot;*&quot; ]<br>      typed_per_filter_config:<br>        envoy.filters.http.cors:<br>          &quot;@type&quot;: type.googleapis.com/envoy.extensions.filters.http.cors.v3.CorsPolicy<br>          allow_origin_string_match:<br>            - prefix: &quot;*&quot;<br>          allow_methods: &quot;GET,PUT,DELETE,POST,OPTIONS&quot;<br>          allow_headers: &quot;keep-alive,user-agent,cache-control,content-type,access-control-request-headers,access-control-request-method,authorization,x-requested-with&quot;<br>          allow_credentials: true<br>          max_age: &quot;1728000&quot;</pre><p>Start one more time the docker-compose cluster and try again to access the Tasks page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pO8LNCo63sfDNPc7Kar1vQ.png" /></figure><p>Excellent. So now, it’s time to unify our repositories into a single one.</p><h3>Unifying Nx Monorepo with Back-end services.</h3><p>Copy both projects in a single one. I called this monorepo &lt;<strong>city-tasks-aws-fullstack&gt;,</strong> which you can find in my GitHub account. The project structure will have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kv1d-q_fjacVZkQjRAAGLA.png" /></figure><p>To follow the new Monorepo conventions, I renamed the old &lt;src&gt; folder to &lt;<strong>apis&gt;,</strong> as seen in the previous image. So, the &lt;apps&gt; folder is dedicated to front-end applications, and the &lt;apis&gt; folder will be focused on back-end services.</p><p>Try to build and deploy the entire solution using this new convention to see if all is working as expected before continuing with the next section. Recall to rename the script files that use the old “src” directory to use the actual one.</p><h3>Docker Compose for local Deployment.</h3><p>The service that needs to be added is the City Tasks Application. So first, create the <strong>Dockerfile</strong> inside the &lt;<strong>city-tasks-app</strong>&gt; directory with the following content:</p><pre>##########################################################################<br>######################## Stage 1 : Builder Image #########################<br>##########################################################################<br>FROM node:18 AS builder<br>WORKDIR /workspace<br><br>RUN npm install -g pnpm<br>COPY pnpm-lock.yaml ./<br>COPY package.json ./<br>RUN pnpm install<br><br>COPY . .<br>RUN pnpm run build<br><br>##########################################################################<br>######################## Stage 2: Application Image ######################<br>##########################################################################<br>FROM nginx:alpine<br>COPY --from=builder /workspace/dist/city-tasks-app /usr/share/nginx/html<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>Next, update the &lt;<strong>compose.yaml</strong>&gt; file adding the City Tasks App service:</p><pre>  city-tasks-app:<br>    image: hiperium/city-tasks-app:1.8.0<br>    container_name: tasks-app<br>    build:<br>      context: .<br>      dockerfile: apps/city-tasks-app/Dockerfile<br>    ports:<br>      - &quot;80:80&quot;<br>    environment:<br>      - NODE_ENV=production<br>    depends_on:<br>      - city-image-builder<br>      - city-tasks-postgres<br>      - city-tasks-api<br>      - city-tasks-api-proxy<br>    networks:<br>      - city-network</pre><p>Then, modify the &lt;<strong>environment.ts</strong>&gt; file, updating the API address with the one specified in the Docker Compose file:</p><pre>export const defaultDataServiceConfig: DefaultDataServiceConfig = {<br>  root: &#39;https://localhost/api/v1&#39;,<br>  ...<br>};</pre><p>We must add a new redirection URI in our Cognito OAuth configuration. For this purpose, update the IdP project using the Amplify command:</p><pre>$ amplify update auth</pre><p>Select the “<strong><em>Add/Edit signin and signout redirect URIs</em></strong>” option, and add the new hostname address like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuMfhVLOCWAulZ__zvdAhA.png" /></figure><p>Push the changes to AWS using the Amplify command:</p><pre>$ amplify push</pre><p>Modify again the &lt;<strong>environment.ts</strong>&gt; file, updating the &lt;redirectUri&gt; property to use the new one:</p><pre>export const authConfig: AuthConfig = {<br>  redirectUri: &#39;http://localhost/&#39;,<br>  ...<br>};</pre><p>Execute the Docker Compose to deploy the entire solution locally:</p><pre>$ docker compose up --build</pre><p>Validate that all services are deployed successfully, and then try to open the City Tasks App in your browser. You must access the app without errors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cspZHgNxpCEC44F0zvK5YQ.png" /></figure><p>Excellent. Our entire solution was deployed using Docker Compose so we could test our changes locally before pushing them to AWS.</p><h3>Deploying Back-end Services on AWS Fargate.</h3><p>For this purpose, use our main script to deploy all back-end services automatically (ECS cluster and Lambda function):</p><pre>$ ./run-scripts</pre><p>Select <strong>option 2 </strong>to deploy the back-end into AWS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jmgkb-Bn7fyS1jno.png" /></figure><p>Enter the required information as the script asks before deploying the required infra and services into AWS.</p><p>If you want to know the entire deployment process, please go to my <a href="https://aosolorzano.medium.com/storing-eda-events-in-dynamodb-using-a-native-lambda-function-with-graalvm-spring-cloud-functions-c32cee4775fc">previous tutorial</a> and find section 13 to see the details that apply to this section.</p><h3>Deploying Front-end Services on AWS Amplify.</h3><p>After the back-end deployment has been finished into AWS, go to the &lt;<strong>city-tasks-app</strong>&gt; directory and execute the following command to init the Amplify project in AWS:</p><pre>$ amplify init</pre><p>Enter the required general information about your project. I used the following information, calling Amplify the project as &lt;<strong>CityTasksApp</strong>&gt;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpyYA0bos_zcRrCiPoZl4g.png" /></figure><p>Verify that the project was created in the Amplify console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LF86wxTQ-KE2CRvJ_KXyKQ.png" /></figure><p>Update the &lt;<strong>environment.ts</strong>&gt; file with the required information. The following is a content template that you must fulfill:</p><pre>export const defaultDataServiceConfig: DefaultDataServiceConfig = {<br>  root: &#39;https://ALB_API_ENDPOINT/api/v1&#39;,<br>  ...<br>};<br><br>export const authConfig: AuthConfig = {<br>  issuer: &#39;https://cognito-idp.IDP_AWS_REGION.amazonaws.com/COGNITO_USER_POOL_ID&#39;,<br>  clientId: &#39;COGNITO_APP_CLIENT_ID_WEB&#39;,<br>  redirectUri: &#39;https://main.AMPLIFY_APP_ID.amplifyapp.com/&#39;,<br>  ...<br>};</pre><p><strong>NOTE</strong>: You can get the ALB endpoint when you deploy the back-end services. Besides, the Amplify ID can be obtained using the following command:</p><pre>$ aws amplify list-apps                         \<br>  --query &quot;apps[?name==&#39;CityTasksApp&#39;].appId&quot;   \<br>  --output text                                 \<br>  --profile tasks-dev</pre><p>Now update the &lt;<strong>main.ts</strong>&gt; file, adding the following configuration following the steps indicated by Amplify in its official <a href="https://docs.amplify.aws/angular/start/getting-started/setup/">documentation</a>:</p><pre>import amplifyConfig from &quot;./amplifyconfiguration.js&quot;;<br><br>Amplify.configure(amplifyConfig);<br><br>if (environment.production) {<br>  ConsoleLogger.LOG_LEVEL = &quot;INFO&quot;;<br>  ...<br>}</pre><p>Push all your pending Ionic/Angular project changes to your Git repository. This is because we will be configuring the Amplify Hosting with the latest version of your app. So make sure you push your changes into your Git repository:</p><pre>$ git add .<br>$ git commit -m &quot;Updating Ionic/Angular config for Amplify&quot;<br>$ git push</pre><p>Then, execute the following command to configure your app in the Amplify Hosting service. This command will ask you for additional information before continuing with the following steps:</p><pre>$ amplify add hosting</pre><p>You must select the following options:</p><ul><li>Hosting with Amplify Console.</li><li>Continuous deployment.</li></ul><p>The last one is necessary to allow Amplify to access our Git repo and download the code before publishing the changes. This is a CI/CD process, but for the moment, we’re using only 1 environment.</p><p>You’ll be directed to the Amplify console when the command opens a browser window or tab. Select the &lt;<strong>Hosting environments&gt;</strong> tab, and select the Git Provider where your code resides:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRvssXtzxuxl50TSls5mzA.png" /></figure><p>In the next screen, you will be asked to allow Amplify to connect to your Git repository, so click on the &lt;<strong>Authorize</strong>&gt; button to continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1GJq0ODlFXLGb0F5DFhZQ.png" /></figure><p>After authorizing Amplify to access your Git repository, you will be directed to a steeper form to complete the hosting configuration.</p><p>In step 1, select your Git repo and the branch where your code resides:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6QJMcliTiiudcDUYUA0SA.png" /></figure><p>In step 2, select the Amplify app name, the registered environment, and the IAM Role used by Amplify to deploy the required infra. I created this role in a previous tutorial, so click on the &lt;<strong>Create new role</strong>&gt; if you don’t have this role created yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXEUz7hB8yDKGp9xElvcDQ.png" /></figure><p>In step 3, review your selected settings before proceeding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dEHol6x9z5Dhi7guetfpA.png" /></figure><p>Finally, after clicking on the &lt;<strong>Save and deploy</strong>&gt; button, a <strong>CI/CD</strong> pipeline will be started by Amplify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQaZDLtwWc8NXgQKbcvlLA.png" /></figure><p>But in the &lt;Build&gt; phase, I got the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hya4pb9KSl6kAKMak3v-sA.png" /></figure><p>Line 4 indicates the missing &lt;<strong>angular.json</strong>&gt; file, which is the main config file when you create an Angular project using the Ng tool. However, we used Nx to create our monorepo and the Ionic/Angular project. It is a bug or some misunderstood configuration by Amplify.</p><p>For this reason, I created the following <strong>basic</strong> &lt;<strong>angular.json</strong>&gt; file in the project’s root directory:</p><pre>{<br>  &quot;version&quot;: 1,<br>  &quot;projects&quot;: {<br>    &quot;city-tasks-app&quot;: {<br>      &quot;root&quot;: &quot;apps/city-tasks-app&quot;,<br>      &quot;projectType&quot;: &quot;application&quot;,<br>      &quot;architect&quot;: {}<br>    }<br>  }<br>}</pre><p>If you push this change into your Git repository, you will see that the &lt; back-end&gt; build runs well, so we solve the problem at that stage, but you will see a new error now in the &lt;<strong> front-end</strong>&gt; phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ic4xtMzVgWFQAasZsNRSLQ.png" /></figure><p>If you try to build the project locally, you will see the same error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b99sjYEgy2aSIi-bAG2ujA.png" /></figure><p>The new &lt;<strong>angular.json</strong>&gt; file is causing this error. So, an alternative to fix this error is to create the &lt;angular.json&gt; file on the fly when the &lt;<strong> back-end</strong>&gt; phase is executing and then delete it in the &lt;<strong> front-end</strong>&gt; phase.</p><p>So, update our &lt;<strong>amplify.yml</strong>&gt; file must contain the following content:</p><pre>applications:<br>  - appRoot: apps/city-tasks-app<br>    backend:<br>      phases:<br>        preBuild:<br>          commands:<br>            - echo &#39;{&quot;version&quot;:1,&quot;projects&quot;:{&quot;city-tasks-app&quot;:{&quot;root&quot;:&quot;apps/city-tasks-app&quot;,&quot;projectType&quot;:&quot;application&quot;,&quot;architect&quot;:{}}}}&#39; &gt; angular.json<br>        build:<br>          commands:<br>            - amplifyPush --simple<br>        postBuild:<br>          commands:<br>            - rm angular.json<br>    ...</pre><p>If you push these changes into your Git repository, you will receive another error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jK9w0gNAp3T6IVUEiMnTUA.png" /></figure><p>Notice the error indicates the missing &lt;<strong>amplifyconfiguration.json</strong>&gt; in &lt;<strong>main.ts</strong>&gt; file. That configuration file was created by the Amplify CLI when we initiated our project, but this command also created the following &lt;<strong>.gitignore</strong>&gt; file:</p><pre>#amplify-do-not-edit-begin<br>...<br>aws-exports.js<br>awsconfiguration.json<br>amplifyconfiguration.json<br>amplifyconfiguration.dart<br>amplify-build-config.json<br>...<br>#amplify-do-not-edit-end</pre><p>So, to solve this new problem, we have 2 options. The easiest way is to update the &lt;.gitignore&gt; file, removing the needed file. The other option is to update the &lt;<strong>amplify.yml</strong>&gt; file again, adding the missing file on the fly:</p><pre>applications:<br>  - appRoot: apps/city-tasks-app<br>    ...<br>    frontend:<br>      buildPath: /<br>      phases:<br>        preBuild:<br>          commands:<br>            - npm install -g pnpm<br>            - pnpm install<br>            - echo &#39;{&quot;aws_project_region&quot;:&quot;us-east-1&quot; }&#39; &gt; apps/city-tasks-app/src/amplifyconfiguration.json<br>      ...</pre><p>I will implement this last solution because the recommendation is to keep sensitive information private in configuration files if you work on a private/company project. So, as our project is public, sharing information about AWS accounts is not recommended.</p><p>So, pushing all these changes finally runs successfully in our pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvbpKPJZWh5PtYt83tnmQQ.png" /></figure><p>Clicking on the generated Amplify URL for our project, you must see the main page of our Ionic/Angular app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTG0r3kkhK0A6Bv8nQG_Pw.png" /></figure><p>Before clicking the &lt;Login&gt; button, go to the &lt;<strong>hiperium-city-idp</strong>&gt; project and update the OAuth settings for redirection URIs. Recall this project is also using Amplify, so you need to execute the following command to update the auth module:</p><pre>$ amplify update auth</pre><p>Then, select the &lt;<strong>Add/Edit signin and signout redirect URIs</strong>&gt; option and enter your generated Amplify Hosting endpoint. Push your changes to the Amplify service for your new configuration to take effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yKm8zMWEdhpEKJvJYf8pw.png" /></figure><p>Notice that the generated URL uses the &lt;<strong>amplify.com</strong>&gt; domain, the branch name of our Git repository, which is &lt;<strong>main</strong>&gt;, and a secure communication with <strong>SSL/TLS</strong>.</p><p>Now, you can click the &lt;<strong>Login</strong>&gt; button to be redirected to the IdP login page and follow the known process we did before to access the City Tasks home page.</p><p>We have finally deployed our app in the Amplify Hosting service. So, the last step of our tutorial is to create the required automation scripts to deploy the entire solution.</p><h3>Automation Scripts.</h3><p>As usual, I created script files to create/delete the required infra on AWS to deploy our fullstack City Task application. So, our new menu is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hc--8L87XiRhW64sTaDtpw.png" /></figure><p>Use option 1 to deploy the fullstack City Tasks solution on your local machine using Docker Compose, as we did initially in this tutorial. Before deploying the entire City Task application in your AWS accounts, I recommend doing this.</p><p>The other new options are to create and delete front-end stacks in or from your AWS workloads account. Those options are the main topics in this tutorial.</p><p>Finally, I added 2 other options to create or delete the back-end and front-end services using a single script instead of creating all those services independently. So you’re free to choose whatever option you like regarding your learning in AWS or development journey ;)</p><p>And that’s it!! It is a great pleasure to write about these kinds of articles. I hope you learn as much as I do and apply this knowledge to your projects.</p><p>In my following tutorial, I’ll write about implementing this fullstack application on AWS but using CI/CD pipelines with the help of the AWS tools. So I will see you then.</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=588e124452e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Colima as a Docker Engine provider with Buildx and Compose plugins installed.]]></title>
            <link>https://aosolorzano.medium.com/installing-colima-as-a-docker-engine-provider-with-buildx-and-compose-plugins-installed-1ce8b3bae158?source=rss-b15bb6bd7ea7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce8b3bae158</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Andres Solorzano]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 21:01:22 GMT</pubDate>
            <atom:updated>2024-04-24T21:01:07.778Z</atom:updated>
            <content:encoded><![CDATA[<h3>Installing Colima as a Docker Engine provider with Buildx and Compose plugins installed to build/run Spring-based projects.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMyr2ErqohPKniq3fqtoGQ.png" /></figure><p>Due to license restrictions for enterprises using the Docker Desktop tool, many enterprise developers must migrate to another solution. As a Linux CLI user, Colima is a better solution for building and running containerized applications. So, in this article, I’ll describe the steps to install and configure Colima with the required tools that most software engineers will use daily.</p><p>To complete this guide, you’ll need the following:</p><ul><li>MacOS with ARM64.</li><li><a href="https://brew.sh/">Homebrew</a> (package manager).</li></ul><h3>Remove the Docker Desktop cache.</h3><p>After you delete Docker Desktop, you must remove some cached files in your system. In a MacOS, I created the following shell script to delete these files:</p><pre>#!/bin/bash<br><br># Files that must be deleted.<br>paths=(<br>    &quot;~/Library/Cookies/com.docker.docker.binarycookies&quot;<br>    &quot;~/Library/Logs/Docker Desktop&quot;<br>    &quot;~/Library/Application Support/Docker Desktop&quot;<br>    &quot;~/Library/Caches/com.docker.docker&quot;<br>    &quot;~/Library/Group Containers/group.com.docker&quot;<br>    &quot;~/Library/Saved Application State/com.electron.docker-frontend.savedState&quot;<br>    &quot;/Library/PrivilegedHelperTools/com.docker.vmnetd&quot;<br>    &quot;/Library/LaunchDaemons/com.docker.vmnetd.plist&quot;<br>    &quot;/usr/local/lib/docker&quot;<br>    &quot;~/.docker&quot;<br>)<br><br># Loop to delete declared files.<br>for path in &quot;${paths[@]}&quot;; do<br>    eval rm -rf $path<br>    echo &quot;Deleted: $path&quot;<br>done<br><br>echo &quot;&quot;<br>echo &quot;DONE.&quot;</pre><p>After you execute this script, you can continue with the next steps.</p><h3>Update/Clean your Homebrew installation.</h3><p>Verifying if your &lt;Homebrew&gt; installation is current is a good idea. So first verify if you have any outdated packages:</p><pre>$ brew outdated</pre><p>If the previous command shows you any package obsolete, you can upgrade them with the following command:</p><pre>$ brew upgrade</pre><p>Finally, clean any cached file used by Homebrew in previous installations:</p><pre>$ brew cleanup</pre><p>Now, we can continue with the next steps.</p><h3>Installing Docker Client.</h3><p>Docker Engine and Client are different products. As the title of this tutorial suggests, Colima will be our Docker Engine provider for macOS systems, but we need a Docker Client to interact with the engine. So you can install only the client with the following command:</p><pre>$ brew install docker</pre><p>Do not install the &lt;docker-compose&gt; plugin using the &lt;brew&gt; command because docker plugins must be installed differently.</p><p>Try to execute the &lt;<strong>docker version</strong>&gt; command to verify the installation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWMX960XRcva77YdrQybww.png" /></figure><p>Notice that only the Docker client info is displayed. This is because we haven’t installed any Docker Engine yet.</p><h3>Installing Colima Core dependencies.</h3><p>If you install Colima directly using the &lt;brew&gt; command, it will download the required dependencies. Still, it’s a good idea to install some core dependencies independently so you can fix any problem beforehand.</p><p>The first dependency is <strong>QEMU</strong>, an open-source software virtualization tool that performs hardware emulation. In the container space, QEMU is essential in running containers on hardware platforms other than the host. This is especially relevant in environments where containers run on multiple processor architectures. So you can install it using brew:</p><pre>$ brew install qemu</pre><p>The other dependency is <strong>Lima</strong>, a tool that allows us to run Linux virtual machines on macOS, acting as a container environment similar to Docker Desktop. It benefits developers working on macOS who need a Linux environment for developing, testing, or running containerized applications. So we can install it with the following &lt;<strong>brew</strong>&gt; command:</p><pre>$ brew install lima</pre><p>If you have problems installing any of these tools, try to solve them before continuing with our next step in this journey.</p><h3>Installing Docker Engine through Colima.</h3><p>Now, execute the following command to install Colima:</p><pre>$ brew install colima</pre><p>If you have successfully installed Colima, then try to run it, configuring the service to start at every system login:</p><pre>$ brew services start colima</pre><p>However, the service began using the default values. So try to stop the service and start it again but using the following param to edit the default values:</p><pre>$ colima stop<br>$ colima start --edit</pre><p>Adjust the CPU, memory, and disk space values according to your needs.</p><p><strong>NOTE</strong>: As I’m using AWS to deploy the services described in my tutorials, it could be a good idea to have in mind the values used by the AWS CodeBuild service so you can dimension your Colima settings accordingly for your testing purposes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOV9FsxKm9c-_aFwkTIqRg.png" /><figcaption>Taken from the AWS CodeBuild <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html">website</a>.</figcaption></figure><p>Before you end with the Colima settings updates, you must change the &lt;<strong>network</strong>&gt; configuration so Colima can assign an IP address to the virtual machine. This will be useful when running our Docker Engine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*0R2H9FxZ0Dn9RYzXowxelQ.png" /></figure><p>If you use VIM as your default system editor, save and exit the file with the &lt;wq!&gt; command, and then the Colima service will start. If everything is ok, your Colima service must be started successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGVwRG2bg48gH7NPruvfvw.png" /></figure><p>Now you can run the &lt;<strong>docker version</strong>&gt; command one more time to see the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OehI8mzy2zmk6L3BKuJkA.png" /></figure><p>Notice that now we have information about the Docker Engine (server).</p><p>Try to execute the &lt;<strong>docker context ls</strong>&gt; command to see which context is using the Docker client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3iHtU-KLzX564u44yWYi7Q.png" /></figure><p>The Docker client uses the Colima context, which uses a Unix socket to interact with the Docker Engine through REST APIs.</p><p>This is half of our journey because I’ve had problems building Docker images, which previously worked when using the Docker Desktop tool. So, let’s continue with the next part of the tutorial.</p><h3>Running Integration Tests with Testcontainers.</h3><p>Let’s use the project from my <a href="https://aosolorzano.medium.com/storing-eda-events-in-dynamodb-using-a-native-lambda-function-with-graalvm-spring-cloud-functions-c32cee4775fc">previous tutorial</a>, which contains Spring Boot and Spring Function projects. Both projects use <a href="https://testcontainers.com/"><strong>Tescontainers</strong></a> technology to execute integration tests with JUnit 5.</p><p>Clone the project from my GitHub <a href="https://github.com/aosolorzano/city-tasks-lambda-native-with-dynamodb"><strong>repository</strong></a>, navigate to the project’s folder, and execute the following Maven command to run the integration tests, initially for the API microservice:</p><pre>$ mvn test -f src/city-tasks-api/pom.xml</pre><p>Then, you will receive the following error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zefrxGJM5qljnelB3AA2Ow.png" /></figure><p>The error message says that the Java Docker Client could not find the Docker Socket in the system. It expects the socket in the default “<strong>/var/run/docker.sock</strong>” path.</p><p>If you search the official Tescontainers documentation, you’ll find an essential page about <a href="https://java.testcontainers.org/supported_docker_environment/">container runtime configurations</a>. As we’re using Colima, we must export the following environment variables:</p><pre>export TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE=/var/run/docker.sock<br>export DOCKER_HOST=&quot;unix://${HOME}/.colima/default/docker.sock&quot;</pre><p>Try to export these variables as system global variables. I’m using ZSH, so I updated my “<strong>.zshenv</strong>” file by adding the previous environment variables. Then, execute the following command to update the changes:</p><pre>$ source .zshenv</pre><p>Return to the project directory and try to execute the Maven test command again:</p><pre>$ mvn test -f src/city-tasks-api/pom.xml</pre><p>You will notice that this time, the Java Docker Client is downloading the required Docker images to execute the integration tests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sJ3ax2ZDZ5YFsZqwlqJNA.png" /></figure><p>In the end, all integration tests must be executed successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WCpVFcqRVo9mUmrUHijhA.png" /></figure><p>Repeat the same for the Spring Function project:</p><pre>$ mvn test -f src/city-tasks-events-function/pom.xml</pre><p>Notice that the Java Docker Client is downloading the required Docker images to run the integration tests, and in the end, all tests must be executed successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C96jXsm7OokPDXx9SPMG8w.png" /></figure><p>Let’s continue to deploy our backend projects locally to make more integration tests.</p><h3>Installing Docker Compose plugin.</h3><p>Working in the same project folder as in the previous section, we need to deploy our API and Lambda services locally, but this time, we must use Localstack.</p><p>Notice a “<strong>docker-compose.yml</strong>” file in the project’s root directory. Inside that file, you will find a service called &lt;<strong>tasks-localstack&gt; </strong>with the following definition:</p><pre>  tasks-localstack:<br>    image: localstack/localstack:2.2.0<br>    container_name: tasks-localstack<br>    ports:<br>      - &quot;4566:4566&quot;<br>    env_file:<br>      - ./utils/docker/env/localstack-dev.env<br>    volumes:<br>      ...<br>    depends_on:<br>      - tasks-events-function<br>    networks:<br>      - hiperium-network</pre><p>We need this LocalStack container to run our backend services locally, but we haven’t installed the Compose plugin yet. So, according to the official Docker <a href="https://docs.docker.com/compose/install/linux/">documentation</a>, let’s execute the following commands in a separate terminal tab/window:</p><p><strong>IMPORTANT</strong>: navigate to the <a href="https://github.com/docker/compose/releases">releases</a> Git page and select the latest version with the appropriate microprocessor version for your system.</p><pre>$ DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}<br>$ mkdir -p $DOCKER_CONFIG/cli-plugins<br>$ curl -SL https://github.com/docker/compose/releases/download/v2.26.1/docker-compose-darwin-aarch64 -o $DOCKER_CONFIG/cli-plugins/docker-compose</pre><p>Then, you must add execution permissions to the downloaded binary:</p><pre>$ chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose</pre><p>Finally, test if the Compose plugin installation was successful:</p><pre>$ docker compose version</pre><p>You must see the plugin version in the output of the command like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrV5ErZ4B-BOV47yZbwUsg.png" /></figure><p>Please return to the project’s terminal tab and try to deploy the entire Compose configuration declared for our backend services. But first, log in using the AWS SSO script and using the IDP profile:</p><pre>$ hiperium-login</pre><p>Then, execute the project’s main script and select option 1 to deploy the required services using Docker Compose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWU1gCkxZkpFltvuJOj4qg.png" /></figure><p>This shell script first obtains some values from the Cognito IdP Service from AWS and applies them to different configuration files. Then, the script executes the Docker Compose command to start a cluster with the required services:</p><pre>$ docker compose up --build</pre><p>If these steps are executed successfully, you must see in the terminal window that the Docker Compose is building the API and Functions projects before deploying them locally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*acG8ZeEE8Pu_wro_5LbaOQ.png" /></figure><p>This process takes significant time because the Spring projects use GraalVM to build Linux Native Executables.</p><p>If you want to wait until this process is finished, you must see the following output in your terminal indicating that Docker Compose deploys all required services successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_8q7hw3eO7rU_1ltF3d1g.png" /></figure><p>Notice how the &lt;tasks-localstack&gt; container prints all log messages in the console, creating the required AWS services for local testing.</p><p>Now, let’s try to deploy our backend services in AWS using an Infrastructure as a Code tool.</p><h3>Installing Docker Buildx plugin.</h3><p>In my previous tutorials, I used the AWS Copilot tool to deploy containerized services into a Fargate ECS cluster and SAM-CLI to deploy Lambda functions in AWS. I used Docker to build images in both cases and saved them in the AWS ECR service. So, let’s try to deploy our backend services to AWS.</p><p>As we did in the previous section, let’s use our AWS SSO script to login to the &lt;<strong>Tasks Development&gt;</strong> account:</p><pre>$ hiperium-login</pre><p>Then, run the project’s shell script, entering the IdP and Tasks profiles. Next, select option 2 to deploy the backend services into AWS:</p><pre>$ ./run-script</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfEID57yXi83wkGmSuh8ZQ.png" /></figure><p>After that, you must see a <strong>deprecated</strong> message indicating the use of the legacy &lt;<strong>builder</strong>&gt; component to build Docker images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N04p-a9ztiyFPmHquilTeQ.png" /></figure><p>We didn’t see this message before when executing the Docker Compose command because the Compose plugin uses a different context to build and deploy the containers.</p><p>It’s supposed that the Docker client uses Buildx as a default build option, as we can see in its official <a href="https://docs.docker.com/build/architecture/">documentation</a>:</p><blockquote>As of Docker Engine 23.0 and Docker Desktop 4.19, Buildx is the default build client.</blockquote><p>Let’s verify this configuration in our Colima settings file located in the following path, opening it in a new terminal tab with your preferred editor:</p><pre>$ vim $HOME/.colima/default/colima.yaml</pre><p>Try to find the &lt;<strong>docker</strong>&gt; section to see the details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFStCJ-XAA6MyiSO9tS_6g.png" /></figure><p>We can confirm that BuildKit is enabled by default. So, the missing part is the Buildx component.</p><p>Let’s return to the previous terminal tab, and you will see that our script finishes with an error indicating an exit status of 1. If you look at the logs before the exit status, you must see that Docker was building the API microservice when the error occurred:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni6R-ba8tipWJnEYeFvwNA.png" /></figure><p>Notice the &lt;<strong>Step</strong> <strong>8/13&gt;,</strong> where we try copying the resulting Linux Native Executable from a previous Docker stage. So, let’s go to our Dockerfile definition to take a more significant context about the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QIpFBuoQGv2tFNGrUMec0w.png" /></figure><p>The <strong>COPY</strong> command is not working. So, let’s try executing the build command independently to see what happens:</p><pre>$ docker build -t hiperium/city-tasks-api:1.7.0 -f src/city-tasks-api/Dockerfile .</pre><p>You must see at the end of the output the same error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6aIFUqc8EVAD4lf6-TYCFg.png" /></figure><p>It confirms that the COPY command is not working as expected. So, after researching the possible solutions for this error on the Internet, I found that it belongs to the BuildKit component according to Docker’s official <a href="https://docs.docker.com/build/building/multi-stage/#differences-between-legacy-builder-and-buildkit">documentation</a>:</p><blockquote>The legacy Docker Engine builder processes all stages of a Dockerfile leading up to the selected — target. It will build a stage even if the selected target doesn’t depend on that stage.</blockquote><blockquote><strong>BuildKit only builds</strong> the stages that the target stage depends on.</blockquote><p>As our final stage doesn’t depend directly on the intermediate one (which builds the Linux Native Image), Docker doesn’t process it according to the previous reference.</p><p>Until now, we have identified 2 related topics that we must address:</p><ol><li><strong>Error</strong>: the BuildKit component is not processing the intermediate stage, which builds our Linux Native Executable.</li><li><strong>Warning</strong>: The legacy builder is deprecated, so we must install the Buildx plugin.</li></ol><p>Let’s start with the first one. According to the Docker <a href="https://docs.docker.com/build/building/multi-stage/#differences-between-legacy-builder-and-buildkit">documentation</a>, adding the <strong>DOCKER_BUILDKIT</strong> environment variable with zero can turn off BuildKit. This is because we are currently using the legacy builder, and we want to process all declared stages:</p><pre>$ DOCKER_BUILDKIT=0 docker build --no-cache -t hiperium/city-tasks-api:1.7.0 -f src/city-tasks-api/Dockerfile .</pre><p>But this didn’t work. The problem with the COPY command still appears. So my next attempt was editing and restarting the Colima service, turning off the BuildKit property:</p><pre>docker:<br>  features:<br>    buildkit: false</pre><p>This didn’t work either, so I reverted these changes and started working on our second point to see if that could solve the problem.</p><p>So, let’s start installing the missing Buildx plugin in our system as we did with the Compose one, this time following the Buildx official plugin <a href="https://github.com/docker/buildx">documentation</a>:</p><pre>$ DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}<br>$ curl -SL https://github.com/docker/buildx/releases/download/v0.11.2/buildx-v0.11.2.darwin-arm64 -o $DOCKER_CONFIG/cli-plugins/docker-buildx<br>$ chmod +x $DOCKER_CONFIG/cli-plugins/docker-buildx</pre><p>Now, let’s execute the following command to configure Buildx as the default builder mechanism:</p><pre>$ docker buildx install</pre><p>This sets up the Docker builder command as an alias to the &lt;<strong>docker buildx build</strong>&gt; command, which results in the capacity to use the &lt;<strong>docker build</strong>&gt; as the default builder mechanism.</p><p>So, let’s try to build our API microservice again to see if the DEPRECATED message disappears:</p><pre>$ docker build -t hiperium/city-tasks-api:1.7.0 -f src/city-tasks-api/Dockerfile .</pre><p>And you can notice in the console that it disappeared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbJJNvYlycSww8LTrKbyXQ.png" /></figure><p>Wait until the process finishes, and you will see that the COPY error doesn’t appear anymore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNgkWjTbegjBnCp-0aGP3w.png" /></figure><p>As our problem was solved, let’s try to deploy our backend services to AWS again. This is because both tools, Copilot and SAM, use Docker to build the images and push them to ECR:</p><pre>$ ./run-scripts</pre><p>Enter the required AWS profiles and select option 2. The process of creating the docker images must be started, and each tool must deploy the necessary services to AWS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FRcp40YiweO4B9vKuoXbg.png" /></figure><p>And that’s it!!! We replaced the Docker Desktop tool with Colima using the required Docker plugins for our daily basis as software engineers :)</p><p>I hope this tutorial has been helpful, and I’ll see you in the next one.</p><p>See you the next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ce8b3bae158" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>