I’m trying to create an Azure Function that creates a secret in a Key Vault with an expiration time of 30 minutes from now.
Just creating a secret with no properties works without any issues:
using Azure.Identity;
using Azure.Security.KeyVault;
using Azure.Security.KeyVault.Secrets;
namespace Company.Function
{
public static class Save
{
[FunctionName("save")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
var client = new SecretClient(
new Uri("https://<my-vault>.vault.azure.net/"),
new DefaultAzureCredential()
);
var secret = await client.SetSecretAsync("name", "value");
return new OkObjectResult("Done");
}
}
}
(Access is set up by enabling a system-assigned identity and granting that access to write secrets to the Key Vault)
Ideally, I would like to do one request that includes both setting the secret and its properties but I can’t find documentation for that in C#.
I’ve tried adding this code, but it fails with a message that Version can’t be null:
var props = new SecretProperties(data.repo);
props.ExpiresOn = DateTime.UtcNow.AddMinutes(30);
await client.UpdateSecretPropertiesAsync("name");
Any idea what I’m missing? I’ve looked at a bunch of pages without finding a solution.
>Solution :
You should be able to use this different overload of SetSecretAsync:
var secret = new KeyVaultSecret("name", "value");
secret.Properties.ExpiresOn = DateTime.UtcNow.AddMinutes(30);
await client.SetSecretAsync(secret);