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

Validate that resource exists before retrieving keys

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

// 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);

在没有任何带有“pulumi up”的资源组的空白订阅上第一次启动时,我收到一个错误

Service returned an error. Status=404 Code="ResourceGroupNotFound" Message="Resource group 'myRG' could not be found.

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

您应该 link 通过在其构造函数中使用 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;
});