<?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 Felip Miguel Puig on Medium]]></title>
        <description><![CDATA[Stories by Felip Miguel Puig on Medium]]></description>
        <link>https://medium.com/@fmiguel?source=rss-b98f4c941924------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wX9kNtm3ScqXenySgeBSvg.jpeg</url>
            <title>Stories by Felip Miguel Puig on Medium</title>
            <link>https://medium.com/@fmiguel?source=rss-b98f4c941924------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 16:15:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fmiguel/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[Passwordless authentication for Azure Databases with .Net]]></title>
            <link>https://medium.com/@fmiguel/passwordless-authentication-for-azure-databases-with-net-92a50462878?source=rss-b98f4c941924------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a50462878</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[passwordless-login]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Felip Miguel Puig]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 23:59:30 GMT</pubDate>
            <atom:updated>2024-07-19T23:59:30.593Z</atom:updated>
            <content:encoded><![CDATA[<h3>Passwordless authentication for Azure Databases with .Net</h3><p>Most of Azure Services support Azure AD authentication, including Azure Database for MySQL and Postgres Flexible Server. This is a great feature that allow to use those services without the inconvinients of managing credentials in our applications. However. it is not always clear how to take advantage of that capability from our applications and the documentation sometimes can be confusing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2JduE2_geg3GQH3z" /><figcaption>Photo by <a href="https://unsplash.com/@usinglight?utm_source=medium&amp;utm_medium=referral">Stefan Steinbauer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>According to Azure docs, it is possible to use an Azure AD token as password for MySQL and Postgres Flexible server. Something like this:</p><pre>// Azure AD resource ID for Azure Database for PostgreSQL Flexible Server is https://ossrdbms-aad.database.windows.net/<br>string accessToken = null;<br><br>try<br>{<br>    // Call managed identities for Azure resources endpoint.<br>    var sqlServerTokenProvider = new DefaultAzureCredential();<br>    accessToken = (await sqlServerTokenProvider.GetTokenAsync(<br>                    new Azure.Core.TokenRequestContext(scopes: new string[] { &quot;https://ossrdbms-aad.database.windows.net/.default&quot; }) { })).Token;<br>}<br>catch (Exception e)<br>{<br>    Console.Out.WriteLine(&quot;{0} \n\n{1}&quot;, e.Message, e.InnerException != null ? e.InnerException.Message : &quot;Acquire token failed&quot;);<br>    System.Environment.Exit(1);<br>}<br>// Open a connection to the PostgreSQL server using the access token.<br>string connString = String.Format(<br>                    &quot;Server={0}; User Id={1}; Database={2}; Port={3}; Password={4}; SSLMode=Prefer&quot;,<br>                    Host,<br>                    User,<br>                    Database,<br>                    5432,<br>                    accessToken);<br><br>using (var conn = new NpgsqlConnection(connString))<br>{<br>    Console.Out.WriteLine(&quot;Opening connection using access token...&quot;);<br>    conn.Open();<br>    ...<br>    // do whatever you want to do with your database<br>}</pre><p>This sample will work, but… It has important drawbacks:</p><p><strong>It is not connection pool-friendly.</strong> .Net manages database connection pools automatically; database connections with identical connection strings will share and reuse connections from a pool instead of establishing new connections each time a call to the database occurs. This results in a significant performance improvement. In this case, the connection string contains the access token, a time-limited credential. So, the connection pool will be invalidated every time the access token expires. This is not a problem if the application is short-lived, but it can be a problem if the application is long-lived. In addition, if another part of the application retrieves a connection in the same way, the connection pool will be invalidated again.</p><p><strong>It’s not Asp.Net/Entity Framework friendly</strong>. Usually, Entity Framework connection is configured during application startup. The connection string is not configured later; hence, the access token cannot be refreshed. The problem is that connection pools, by default, are dynamic. It means that few connections are created at startup, and more connections are created as needed. So, if the application is long-lived, and a new connection needs to be created after the access token has expired, it will fail.</p><p>To avoid these issues, I created some Nuget packages that make using passwordless connections in your application easier. This is how it looks for Azure Database for PostgreSQL:</p><pre>NpgsqlDataSourceBuilder dataSourceBuilder = new NpgsqlDataSourceBuilder(&quot;Server=superserver.postgres.database.azure.com;Database=sampledb;Port=5432;User Id=myuser@mydomain.onmicrosoft.com;Ssl Mode=Require;&quot;);<br>NpgsqlDataSource dataSource = dataSourceBuilder<br>                .UseAzureADAuthentication(new DefaultAzureCredential())<br>                .Build();<br>using NpgsqlConnection connection = await dataSource.OpenConnectionAsync();</pre><p>Note that the connection string doesn’t contain a password. As the connection string doesn’t change, it is properly pooled. Npgsql driver provides a method to retrieve the password periodically. Hence, it will work well with aspnet and Entity Framework.</p><p>Here is an example of usage with Npgsql EntityFrameworkCore:</p><pre>// configuring services<br>var services = new ServiceCollection();<br>services.AddDbContextFactory&lt;SampleContext&gt;(options =&gt;<br>{<br>    options.UseNpgsql(&quot;POSTGRESQL CONNECTION STRING&quot;,<br>        npgsqlOptions =&gt; npgsqlOptions.UseAzureADAuthentication(new DefaultAzureCredential())); // Usage of this library<br>});</pre><p>There are also equivalent implementations for the MySqlConnector driver and Pomelo EntityFrameworkCore.</p><p>MySqlConnector example:</p><pre>TokenCredentialMysqlPasswordProvider passwordProvider = new TokenCredentialMysqlPasswordProvider(new DefaultAzureCredential());<br>using MySqlConnection connection = new MySqlConnection(configuration.GetConnectionString());<br>connection.ProvidePasswordCallback = passwordProvider.ProvidePassword;<br>await connection.OpenAsync();</pre><p>And Pomelo EntityFrameworkCore:</p><pre>// Pomelo requires to specify the server version<br>ServerVersion serverVersion = ServerVersion.Parse(&quot;5.7&quot;, Pomelo.EntityFrameworkCore.MySql.Infrastructure.ServerType.MySql);<br>// configuring services<br>var services = new ServiceCollection();<br>services.AddDbContextFactory&lt;SampleContext&gt;(options =&gt;<br>{<br>    options<br>        .UseMySql(&quot;MYSQL CONNECTION STRING&quot;, serverVersion)<br>        .UseAzureADAuthentication(new DefaultAzureCredential());<br>});</pre><p>As you probably realized, I used <em>DefaultAzureCredential </em>in all samples. Its main advantage is that it can be used with an end user, for instance, by you in your local development environment and other service principals, such as Managed Identities in production.</p><p>You can find the implementation of these libraries in <a href="https://github.com/felipmiguel/AzureDb.Passwordless">Github</a>, or just import in your projects the following nuget packages:</p><ul><li><a href="https://www.nuget.org/packages/Batec.Azure.Data.Extensions.Npgsql/">Batec.Azure.Data.Extensions.Npgsql</a></li><li><a href="https://www.nuget.org/packages/Batec.Azure.Data.Extensions.MySqlConnector/">Batec.Azure.Data.Extensions.MySqlConnector</a></li><li><a href="https://www.nuget.org/packages/Batec.Azure.Data.Extensions.Npgsql.EntityFrameworkCore/">Batec.Azure.Data.Extensions.Npgsql.EntityFrameworkCore</a></li><li><a href="https://www.nuget.org/packages/Batec.Azure.Data.Extensions.Pomelo.EntityFrameworkCore/">Batec.Azure.Data.Extensions.Pomelo.EntityFrameworkCore</a></li></ul><p>You can find a reference sample <a href="https://github.com/felipmiguel/batec-ossrdbms-demo">here</a>. It is a customization of a Todo sample generated with azd. There is a Terraform script to generate the infrastructure:</p><ul><li>An Azure Database for MySQL flexible server configured for Azure AD authentication.</li><li>An Azure Database for Postgres flexible server configured for Azure AD authentication.</li><li>A User-Assigned Managed Identity.</li><li>An Azure Container App connecting to MySQL flexible server.</li><li>An Azure Container App connecting to Postgres flexible server.</li></ul><p>The sample also contains the scripts to create the database users linked to the managed identities and grant the appropriate permissions.</p><p>You can find more details about the sample in my following <a href="https://medium.com/@fmiguel/passwordless-net-end-to-end-example-to-access-mysql-and-postgresql-hosted-on-azure-6978242cb033">article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a50462878" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passwordless .Net end-to-end example to access MySQL and PostgreSQL hosted on Azure]]></title>
            <link>https://medium.com/@fmiguel/passwordless-net-end-to-end-example-to-access-mysql-and-postgresql-hosted-on-azure-6978242cb033?source=rss-b98f4c941924------2</link>
            <guid isPermaLink="false">https://medium.com/p/6978242cb033</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[azure-managed-identities]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[passwordless]]></category>
            <dc:creator><![CDATA[Felip Miguel Puig]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 23:07:29 GMT</pubDate>
            <atom:updated>2024-07-20T00:00:37.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Passwordless access to Azure MySQL and Postgres end-to-end sample with .Net</h3><p>So you want to connect your .Net application to Azure Database for MySQL or Postgres using Azure AD authentication, but you don’t know how. In this example, you will find how to deploy an ASP.net core application in an Azure Container that, using a Managed Identity, is able to connect to an Azure Database for MySQL or Azure Database for Postgres. To make it easy, I will use Batec extensions to simplify the implementation in the dotnet client side. You can read my previous <a href="https://medium.com/@fmiguel/passwordless-authentication-for-azure-databases-with-net-92a50462878">story</a> to learn more about Batec extensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBv4ztOfv-4tpPsc" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The application for the demo is based on the <a href="https://github.com/Azure-Samples/todo-csharp-sql">todo-csharp-sql sample</a>, but:</p><ul><li>Uses Azure Database for MySQL and Azure Database for Postgres instead of SQL Server.</li><li>Uses Container Apps.</li><li>There are no passwords; it doesn’t require an Azure Key Vault to store secrets. Instead it uses a User Assigned Managed Identity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*NPrQMwDuvHSlrkYxQ0HVfw.png" /><figcaption>Azure Components</figcaption></figure><p>The first thing I did was use <a href="https://nubesgen.com/">Nubesgen</a> to generate a base Terraform template to generate the infrastructure. This simple tool can generate a Terraform configuration for Azure following best practices and naming conventions. For instance, I used this link to generate my initial Terraform configuration:</p><pre>curl &quot;https://nubesgen.com/batec-ossrdbms-demo.zip?iactool=TERRAFORM&amp;region=northeurope&amp;application=CONTAINER_APPS.basic&amp;runtime=DOCKER&amp;database=POSTGRESQL.basic&quot; | tar -xzvf -</pre><p>You can customize that base configuration for your specific scenario. I adapted the configuration with the following actions:</p><p>Configure database authentication to use AAD authentication only. Hence removing database passwords.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6fe10ad4fd7362f35cabe63ee2cbc76/href">https://medium.com/media/f6fe10ad4fd7362f35cabe63ee2cbc76/href</a></iframe><p>Create a user-assigned managed identity to be used by the applications to access the database.</p><p>Configure the user-assigned managed identity with permissions to pull images from an Azure Container Registry.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b0f97763b3a3bfaa017b1f4df5f18b0/href">https://medium.com/media/6b0f97763b3a3bfaa017b1f4df5f18b0/href</a></iframe><p>Move container app creation out of the Terraform configuration. Apps will be created from the Azure cli, as I’ll explain later.</p><p>Now, it is possible to create the users in the databases linked to the Managed Identities.</p><p>In Azure Database for Postgres, you can create a user by executing the following SQL commands:</p><pre>select * from pgaadauth_create_principal_with_oid(&#39;${APPLICATION_LOGIN_NAME}&#39;, &#39;${APPLICATION_IDENTITY_APPID}&#39;, &#39;service&#39;, false, false);<br>GRANT ALL PRIVILEGES ON DATABASE &quot;${DATABASE_NAME}&quot; TO &quot;${APPLICATION_LOGIN_NAME}&quot;;<br>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO &quot;${APPLICATION_LOGIN_NAME}&quot;;<br>GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO &quot;${APPLICATION_LOGIN_NAME}&quot;;</pre><p>The first command creates a user who authenticates with Azure AD, while the last three commands grant database permissions.</p><p>In Azure MySQL, you can create the user by executing the following commands:</p><pre>CREATE AADUSER &#39;${APPLICATION_LOGIN_NAME}&#39; IDENTIFIED BY &#39;${APPLICATION_IDENTITY_APPID}&#39;;<br>GRANT ALL PRIVILEGES ON ${DATABASE_NAME}.* TO &#39;${APPLICATION_LOGIN_NAME}&#39;@&#39;%&#39;;</pre><p>To execute these SQL commands, you can use your favorite database client tool, or you can use Azure CLI extension rdbms-connect.</p><p>For instance, for MySQL you can execute:</p><pre>az mysql flexible-server execute --name ${MYSQL_SERVER} --file-path mysqluser.sql --admin-password &quot;${ADMIN_PASSWORD}&quot; --admin-user &quot;${ADMIN_USER}&quot; --verbose</pre><p>Now that the databases are created, you can connect your application to the databases. First, add the package dependencies:</p><ul><li>Batec.Azure.Data.Extensions.Pomelo.EntityFrameworkCore - If you want to use MySQL.</li><li>Batec.Azure.Data.Extensions.Npgsql.EntityFrameworkCore - If you want to use Postgresql.</li><li>Azure.Identity - To use Azure Active Directory authentication.</li></ul><p>Configure the database connection during application startup using a TokenCredential. The most convenient TokenCredential implementation for a demo application like this is DefaultAzureCredential. This implementation will try to authenticate using different methods, like Managed Identity, Azure CLI, Visual Studio, and so on. With this approach it is possible to test from our local development computer. Note that Terraform script uses the logged-in user in Azure cli as the Database AAD admin. This means that you will be able to use your Azure cli user to connect to the database. The code will look like this:</p><pre>DefaultAzureCredential azureCredential;<br>if (string.IsNullOrEmpty(builder.Configuration[&quot;UserAssignedManagedClientId&quot;]))<br>{<br>    azureCredential = new DefaultAzureCredential();<br>}<br>else<br>{<br>    azureCredential = new DefaultAzureCredential(new DefaultAzureCredentialOptions<br>    {<br>        ManagedIdentityClientId = builder.Configuration[&quot;UserAssignedManagedClientId&quot;]<br>    });<br>}<br>// use this code for Postgres<br>builder.Services.AddDbContext&lt;TodoDb&gt;(options =&gt;<br>{<br>    string npgConnString = builder.Configuration[&quot;PgSqlConnection&quot;] ?? throw new InvalidOperationException(&quot;PgSqlConnection must be set in the configuration&quot;);<br>    options<br>            .UseNpgsql(npgConnString, npgsqlOptions =&gt; npgsqlOptions.UseAzureADAuthentication(azureCredential).EnableRetryOnFailure());<br>});<br><br>// use this code for MySQL<br>builder.Services.AddDbContext&lt;TodoDb&gt;(options =&gt;<br>{<br>    string mysqlConnString = builder.Configuration[&quot;MySqlConnection&quot;] ?? throw new InvalidOperationException(&quot;MySqlConnection must be set in the configuration&quot;);<br>    var serverVersion = ServerVersion.Parse(&quot;5.7&quot;, ServerType.MySql);<br>    options<br>        .UseMySql(mysqlConnString, serverVersion, options =&gt; options.EnableRetryOnFailure())<br>        .UseAzureADAuthentication(azureCredential);<br>});</pre><blockquote>Note that using Azure AD authentication only requires calling the UseAzureADAuthentication extension method andpassing a TokenCredential.</blockquote><p>Now, you can build the Docker images and deploy themto Azure Container Apps. You can use your local Docker tools to create the images and upload them to Azure Container Registry or use Azure Container Registry to build them directly. I’ll use Azure Container Registry to build the images. For that, in the folder containing the code, execute the following command:</p><pre>az acr build -t $ACR_NAME.azurecr.io/todoapi:latest -t $ACR_NAME.azurecr.io/todoapi:1.0.0 -r $ACR_NAME .</pre><p>Then you can deploy to Azure Container Apps:</p><pre># Deploy MySQL API application<br>az containerapp create -n mysqlapi -g ${RESOURCE_GROUP} \<br>    --image ${ACR_NAME}.azurecr.io/todoapi:1.0.0 --environment ${CONTAINER_APP_ENVIRONMENT} \<br>    --ingress external --target-port 80 \<br>    --registry-server ${ACR_NAME}.azurecr.io --registry-identity &quot;${MSI_CONTAINER_IDENTITY}&quot; \<br>    --user-assigned ${MSI_CONTAINER_IDENTITY} \<br>    --cpu 0.25 --memory 0.5Gi \<br>    --env-vars TargetDb=&quot;MySql&quot; MySqlConnection=&quot;${MYSQL_CONNECTION_STRING};UserID=${MSI_LOGIN_NAME};&quot; UserAssignedManagedClientId=&quot;${APPLICATION_IDENTITY_APPID}&quot;<br># Configure CORS on MySQL API application to allow access from any Web application<br>az containerapp ingress cors update -n mysqlapi -g ${RESOURCE_GROUP} --allowed-origins &quot;*&quot; --allowed-methods &quot;*&quot;<br><br># Deploy Postgres API application<br>az containerapp create -n pgsqlapi -g ${RESOURCE_GROUP} \<br>    --image ${ACR_NAME}.azurecr.io/todoapi:1.0.0 --environment ${CONTAINER_APP_ENVIRONMENT} \<br>    --ingress external --target-port 80 \<br>    --registry-server ${ACR_NAME}.azurecr.io --registry-identity &quot;${MSI_CONTAINER_IDENTITY}&quot; \<br>    --user-assigned ${MSI_CONTAINER_IDENTITY} \<br>    --cpu 0.25 --memory 0.5Gi \<br>    --env-vars TargetDb=&quot;Postgresql&quot; PgSqlConnection=&quot;${PGSQL_CONNECTION_STRING};User Id=${MSI_LOGIN_NAME};&quot; UserAssignedManagedClientId=&quot;${APPLICATION_IDENTITY_APPID}&quot;<br># Configure CORS on Postgres API application to allow access from any Web application<br>az containerapp ingress cors update -n pgsqlapi -g ${RESOURCE_GROUP} --allowed-origins &quot;*&quot; --allowed-methods &quot;*&quot;<br><br># Get MySQL API application FQDN<br>MYSQLAPI_FQDN=$(az containerapp show -n mysqlapi -g ${RESOURCE_GROUP} -o tsv --query &quot;properties.configuration.ingress.fqdn&quot;)<br># Get Postgres API application FQDN<br>PGSQLAPI_FQDN=$(az containerapp show -n pgsqlapi -g ${RESOURCE_GROUP} -o tsv --query &quot;properties.configuration.ingress.fqdn&quot;)<br><br># Deploy MySQL Web application<br>az containerapp create -n mysqlweb -g ${RESOURCE_GROUP} \<br>    --image ${ACR_NAME}.azurecr.io/todoweb:1.0.0 --environment ${CONTAINER_APP_ENVIRONMENT} \<br>    --ingress external --target-port 80 \<br>    --registry-server ${ACR_NAME}.azurecr.io --registry-identity &quot;${MSI_CONTAINER_IDENTITY}&quot; \<br>    --cpu 0.25 --memory 0.5Gi \<br>    --env-vars REACT_APP_API_BASE_URL=&quot;https://${MYSQLAPI_FQDN}&quot; REACT_APP_APPLICATIONINSIGHTS_CONNECTION_STRING=&quot;${APPINSIGHTS_CONNECTIONSTRING}&quot;<br><br># Deploy Postgres Web application<br>az containerapp create -n pgsqlweb -g ${RESOURCE_GROUP} \<br>    --image ${ACR_NAME}.azurecr.io/todoweb:1.0.0 --environment ${CONTAINER_APP_ENVIRONMENT} \<br>    --ingress external --target-port 80 \<br>    --registry-server ${ACR_NAME}.azurecr.io --registry-identity &quot;${MSI_CONTAINER_IDENTITY}&quot; \<br>    --cpu 0.25 --memory 0.5Gi \<br>    --env-vars REACT_APP_API_BASE_URL=&quot;https://${PGSQLAPI_FQDN}&quot;  REACT_APP_APPLICATIONINSIGHTS_CONNECTION_STRING=&quot;${APPINSIGHTS_CONNECTIONSTRING}&quot;</pre><p>The above commands deployed two API applications, one for Postgres, andone for MySQL. The same goes for Web applications, withone pointing to each API application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4D292jVuQoEkVhdwWpyz9Q.png" /></figure><p>In this example, I intentionally skipped some details to make it easier to follow, but if you want to review the detailed deployment instructions, you can check the repo on <a href="https://github.com/felipmiguel/batec-ossrdbms-demo/">felipmiguel/batec-ossrdbms-demo (github.com)</a>. It also contains scripts to deploy all components end to end without user interactions.</p><p>Using Batec extensions in your project is quite simple, and it follows best practices for accessing the database. However, as explained in this article, Using Azure AD authentication can be difficult if you don’t have these libraries to facilitate the integration with Azure AD.</p><p>I hope you enjoy this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6978242cb033" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Azure Container Registry to build Docker images for Java projects]]></title>
            <link>https://medium.com/@fmiguel/using-azure-container-registry-to-build-docker-images-for-java-projects-ae5082772744?source=rss-b98f4c941924------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae5082772744</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[azure-container-registry]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[azure-container-apps]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Felip Miguel Puig]]></dc:creator>
            <pubDate>Fri, 05 Aug 2022 10:41:23 GMT</pubDate>
            <atom:updated>2022-08-05T10:41:23.737Z</atom:updated>
            <content:encoded><![CDATA[<p>There are many choices to build Docker images using Maven plugins, such as JKube, JIB or Spotify docker plugin. In all cases, they require having Docker tools installed in the building machine. So, if you execute maven in your development workstation then you need Docker Desktop installed in your machine.</p><p>The proposal of this article is building the Docker images directly in Azure Container Registry.</p><p>The first clear advantage of this approach is that it doesn’t require Docker installed in your dev box. For instance, deploying Docker in a virtual machine requires nested virtualization.</p><p>The second advantage is that your Docker image is immediately available in the registry, it is not necessary to push the image from your dev box, thus it can save some building time.</p><p>For the demo I will create a Docker image and I will deploy it in a Docker container compatible hosting service in Azure, for instance Azure Container Apps. Here the requirements:</p><ul><li>JDK 1.8+</li><li>Maven</li><li>Azure CLI</li><li>GIT</li></ul><p>And an Azure subscription with:</p><ul><li>Azure Container Registry</li><li>Azure Container App. This resource can be changed by other container hosting service, such as Azure App Service, Azure Functions or Azure Kubernetes Service.</li></ul><p>These Azure Services can be created from Azure cli using the following commands:</p><pre>LOCATION=westeurope<br>RESOURCE_GROUP=rg-acrbuild-demo<br>ACR_NAME=acrbuilddemo<br>CONTAINERAPPS_ENVIRONMENT=containerapp-demo<br>CONTAINERAPPS_NAME=spring-petclinic<br># create a resource group to hold resources for the demo<br>az group create --location $LOCATION --name $RESOURCE_GROUP<br># create an Azure Container Registry (ACR) to hold the images for the demo<br>az acr create --resource-group $RESOURCE_GROUP --name $ACR_NAME --sku Standard --location $LOCATION</pre><pre># register container apps extension<br>az extension add --name containerapp --upgrade<br># register Microsoft.App namespace provider<br>az provider register --namespace Microsoft.App<br># create an azure container app environment<br>az containerapp env create \<br>    --name $CONTAINERAPPS_ENVIRONMENT \<br>    --resource-group $RESOURCE_GROUP \<br>    --location $LOCATION</pre><pre># Create a user managed identity and assign AcrPull role on the ACR.<br>USER_IDENTITY=$(az identity create -g $RESOURCE_GROUP -n $CONTAINERAPPS_NAME --location $LOCATION --query clientId -o tsv)<br>ACR_RESOURCEID=$(az acr show --name $ACR_NAME --resource-group $RESOURCE_GROUP --query &quot;id&quot; --output tsv)<br>az role assignment create \<br>    --assignee &quot;$USER_IDENTITY&quot; --role AcrPull --scope &quot;$ACR_RESOURCEID&quot;</pre><pre># container app will be created once the image is pushed to the ACR</pre><p>Let’s take a sample application, for instance the well-known <a href="https://github.com/spring-projects/spring-petclinic">spring pet clinic</a>.</p><pre>git clone <a href="https://github.com/spring-projects/spring-petclinic.git">https://github.com/spring-projects/spring-petclinic.git</a><br>cd spring-petclinic</pre><p>Then create a Dockerfile, in the root project folder. For demo purposes it will be as simple as possible.</p><pre>FROM openjdk:8-jdk-slim<br># takes the jar file as an argument<br>ARG ARTIFACT_NAME<br># assumes the application entry port is 8080<br>EXPOSE 8080</pre><pre># The application&#39;s jar file<br>ARG JAR_FILE=${ARTIFACT_NAME}</pre><pre># Add the application&#39;s jar to the container<br>ADD ${JAR_FILE} app.jar</pre><pre># Run the jar file<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]</pre><p>If we wanted to build locally, we would use the following command.</p><pre>docker build -t myacr.azurecr.io/spring-petclinic:2.7.0 \<br>    -f Dockerfile \<br>    --build-arg ARTIFACT_NAME=target/spring-petclinic-2.7.0-SNAPSHOT.jar \<br>    .</pre><p>But it is NOT necessary, as the image will be built directly in Azure Container Registry. To build the image in Azure Container Registry you can use the following Azure cli command:</p><pre>az acr build \<br>        --resource-group rg-spring-petclinic \<br>        --registry myacr \<br>        --image spring-petclinic:2.7.0 \<br>        --build-arg ARTIFACT_NAME=target/spring-petclinic-2.7.0-SNAPSHOT.jar \<br>        .</pre><p>And you can integrate this command in your Maven build cycle. To do this, Iwill use <em>org.codehaus.mojo:exec-maven-plugin</em>. This plugin allows to execute system or Java programs. It will be used to execute the previous az cli command. To include as part of the build lifecycle it will create a new maven profile.</p><pre>&lt;profile&gt;<br>    &lt;id&gt;buildAcr&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;version&gt;3.0.0&lt;/version&gt;<br>                &lt;executions&gt;<br>                    &lt;execution&gt;<br>                        &lt;id&gt;acr-package&lt;/id&gt;<br>                        &lt;phase&gt;package&lt;/phase&gt;<br>                        &lt;goals&gt;<br>                            &lt;goal&gt;exec&lt;/goal&gt;<br>                        &lt;/goals&gt;<br>                        &lt;configuration&gt;<br>                            &lt;executable&gt;az&lt;/executable&gt;<br>                            &lt;workingDirectory&gt;${project.basedir}&lt;/workingDirectory&gt;<br>                            &lt;arguments&gt;<br>                                &lt;argument&gt;acr&lt;/argument&gt;<br>                                &lt;argument&gt;build&lt;/argument&gt;<br>                                &lt;argument&gt;--resource-group&lt;/argument&gt;<br>                                &lt;argument&gt;${RESOURCE_GROUP}&lt;/argument&gt;<br>                                &lt;argument&gt;--registry&lt;/argument&gt;<br>                                &lt;argument&gt;${ACR_NAME}&lt;/argument&gt;<br>                                &lt;argument&gt;--image&lt;/argument&gt;<br>                                &lt;argument&gt;${project.artifactId}:${project.version}&lt;/argument&gt;<br>                                &lt;argument&gt;--build-arg&lt;/argument&gt;<br>                                &lt;argument&gt;ARTIFACT_NAME=target/${project.build.finalName}.jar&lt;/argument&gt;<br>                                &lt;argument&gt;-f&lt;/argument&gt;<br>                                &lt;argument&gt;Dockerfile&lt;/argument&gt;<br>                                &lt;argument&gt;.&lt;/argument&gt;<br>                            &lt;/arguments&gt;<br>                        &lt;/configuration&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;</pre><p>To execute this process just execute the following maven goal with the new profile.</p><pre>mvn package -PbuildAcr -DRESOURCE_GROUP=$RESOURCE_GROUP -DACR_NAME=$ACR_NAME</pre><p>The resource group and the Azure Container Registry are passed as environment variables, but the can be defined as maven parameters or just hardcoding.</p><p>Now the image already exists in Azure Container Registry.</p><figure><img alt="Azure Container Registry with the just built Docker image" src="https://cdn-images-1.medium.com/max/998/0*ZnaHsDoGfalJpp4f" /></figure><p>Now that I have the image available in Azure Container Registry, it’s time to create the Azure Container App.</p><pre># Create the container app<br>az containerapp create \<br>    --name ${CONTAINERAPPS_NAME} \<br>    --resource-group $RESOURCE_GROUP \<br>    --environment $CONTAINERAPPS_ENVIRONMENT \<br>    --container-name spring-petclinic-container \<br>    --user-assigned ${CONTAINERAPPS_NAME} \<br>    --registry-server $ACR_NAME.azurecr.io \<br>    --image $ACR_NAME.azurecr.io/spring-petclinic:2.7.0-SNAPSHOT \<br>    --ingress external \<br>    --target-port 8080 \<br>    --cpu 1 \<br>    --memory 2</pre><p>Now the application is deployed and running on Azure Container Apps.</p><figure><img alt="Docker application deployed in Azure Container Apps" src="https://cdn-images-1.medium.com/max/999/0*abIX-SsEzd4rXRRn" /></figure><p>And voila:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/0*wXF1nkd7UDsq2FTa" /></figure><p>You can find the source code for this sample <a href="https://github.com/felipmiguel/acr-build-demo">here</a>.</p><p>This article was originally published in Fast Track for Azure blog, here the original article <a href="https://techcommunity.microsoft.com/t5/fasttrack-for-azure/using-azure-container-registry-to-build-docker-images-for-java/ba-p/3563875">Using Azure Container Registry to build Docker images for Java projects</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5082772744" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>