<p>I am trying to Dockerize the java spring application and deploy it in Azure kubernetes. This application is connected to the database and currently it reads the connection string from the configuration file.</p>
<p>As this application will be Dockerized and deployed on AKS, I want to read the connection string from the Azure Key vault using managed identity.</p>
<p>Are there any samples available which demonstrates the above scenario?</p>

One Developer
<p>You could store the connection as a keyvault secret, then use the java sdk to get it.</p>
<p>Make sure you have <a href="https://learn.microsoft.com/en-us/azure/key-vault/general/assign-access-policy-portal" rel="nofollow noreferrer">added your MSI(managed identity) to the keyvault access policy</a>, then use the code below.</p>
<p>1.<a href="https://learn.microsoft.com/en-us/java/api/overview/azure/security-keyvault-secrets-readme?view=azure-java-stable#create-secret-client" rel="nofollow noreferrer">Create secret client</a></p>
<p>It uses <a href="https://learn.microsoft.com/en-us/java/api/overview/azure/identity-readme?view=azure-java-stable#authenticating-with-defaultazurecredential" rel="nofollow noreferrer"><code>DefaultAzureCredential</code></a> to authenticate, don't set the environment vars, then it will use your MSI to authenticate automatically, you can also use <a href="https://learn.microsoft.com/en-us/java/api/com.azure.identity.managedidentitycredentialbuilder?view=azure-java-stable" rel="nofollow noreferrer"><code>ManagedIdentityCredentialBuilder</code></a> instead of <code>DefaultAzureCredentialBuilder</code>, specify the <a href="https://learn.microsoft.com/en-us/java/api/com.azure.identity.managedidentitycredentialbuilder.clientid?view=azure-java-stable" rel="nofollow noreferrer"><code>clientId</code></a> of your MSI.</p>
<pre><code>import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.security.keyvault.secrets.SecretClient;
import com.azure.security.keyvault.secrets.SecretClientBuilder;

SecretClient secretClient = new SecretClientBuilder()
    .vaultUrl(&quot;&lt;your-key-vault-url&gt;&quot;)
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildClient();
</code></pre>
<p>2.<a href="https://learn.microsoft.com/en-us/java/api/overview/azure/security-keyvault-secrets-readme?view=azure-java-stable#retrieve-a-secret" rel="nofollow noreferrer">Retrieve a secret</a></p>
<pre><code>KeyVaultSecret secret = secretClient.getSecret(&quot;&lt;secret-name&gt;&quot;);
System.out.printf(&quot;Retrieved secret with name \&quot;%s\&quot; and value \&quot;%s\&quot;%n&quot;, secret.getName(), secret.getValue());
</code></pre>
<p>For more details see - <a href="https://learn.microsoft.com/en-us/java/api/overview/azure/security-keyvault-secrets-readme?view=azure-java-stable" rel="nofollow noreferrer">Azure Key Vault Secret client library for Java - Version 4.2.0</a></p>
