在检索键之前验证资源是否存在



创建一个资源组和一个数据库帐户:

// Create resourceGroup:
var rg= new ResourceGroup("myRG",
new ResourceGroupArgs
{
Name = "myRG",
Location = "westeurope"
});
// Create DBAccount:
var account = new DatabaseAccount(accountName, new Pulumi.AzureNextGen.DocumentDB.Latest.DatabaseAccountArgs
{
AccountName = "myAcc",
DatabaseAccountOfferType = DatabaseAccountOfferType.Standard,
Location = "WestEurope",
ResourceGroupName = rg.GetResourceName()
});

之后,我想检索主键:

var keys = ListDatabaseAccountKeys.InvokeAsync(new ListDatabaseAccountKeysArgs
{
AccountName = account.GetResourceName(),
ResourceGroupName = rg.GetResourceName()
});
var cosmosWriteKey = Output.Create(keys).Apply(q => q.PrimaryMasterKey);

第一次启动没有任何resourcegroup的空白订阅时,使用"pulumi up"我收到一个错误

服务返回错误。状态= 404代码="ResourceGroupNotFound"消息="资源组' myg '找不到。

我目前通过设置一个环境变量来解决这个问题,在第一次运行时禁用"Key"部分,并在创建ResourceGroup后再次运行代码。但是,也许有一种更聪明的方法来确保在检索键之前创建资源组?

您应该通过在其构造函数中使用rg.Name将帐户链接到资源组,并将ListDatabaseAccountKeys调用放在Apply中:

var account = new DatabaseAccount(accountName, new DatabaseAccountArgs
{
AccountName = "myAcc",
DatabaseAccountOfferType = DatabaseAccountOfferType.Standard,
Location = "WestEurope",
ResourceGroupName = rg.Name
});
var cosmosWriteKey = account.Name.Apply(async name =>
{
var keys = await ListDatabaseAccountKeys.InvokeAsync(new ListDatabaseAccountKeysArgs
{
AccountName = name,
ResourceGroupName = "myRG"
});
return keys.PrimaryMasterKey;
});

这样,调用只会在创建帐户并解析Name输出之后发生。

如果迁移到Azure-Native,可以使用自动命名:

var rg = new ResourceGroup("myRG");
var account = new DatabaseAccount(accountName, new DatabaseAccountArgs
{
DatabaseAccountOfferType = DatabaseAccountOfferType.Standard,
ResourceGroupName = rg.Name
});
var cosmosWriteKey = Output.Tuple(rg.Name, account.Name).Apply(async values =>
{
var keys = await ListDatabaseAccountKeys.InvokeAsync(new ListDatabaseAccountKeysArgs
{
ResourceGroupName = values[0],
AccountName = values[1]
});
return keys.PrimaryMasterKey;
});

最新更新