Search code examples
pythonazurepulumi

Receive an error when I using F-string for creating a connection string with Python in the Pulumi


I want to create a storage connection string with F-String in my code (Pulumi). The scenario and sample code are:

for example, My storage name is test

I received the storage name with:

storage_name = storage_account.name

I received the storage key with:

 storage_primary_key = pulumi.Output.all(resource_group.name, storage_account.name).apply(lambda args: storage.list_storage_account_keys(
     resource_group_name=args[0], account_name=args[1])).apply(lambda accountkeys: accountkeys.keys[0].value)

The output of the below are ok:

pulumi.export('storage name is', storage_name)
pulumi.export('storage key is', storage_primary_key)

output:

storage name is: test
storage key is: sg373dhh

Now, I want crate connection string with the below code:

conn_str = f"DefaultEndpointsProtocol=https;AccountName={storage_name};AccountKey={storage_primary_key};EndpointSuffix=core.windows.net"

when run this code:

pulumi.export('storage connection string is', conn_str )

But, the output is different:

storage connection string is "DefaultEndpointsProtocol=https;AccountName=<pulumi.output.Output object at 0x000002152C3233D0>;AccountKey=<pulumi.output.Output object at 0x000002152C3233D0>;EndpointSuffix=core.windows.net"

I don't know why add <pulumi.output.Output object at 0x000002152C3233D0> instead of true value.


Solution

  • Outputs that contain strings cannot be used directly in operations such as string concatenation. Since storage_primary_key and storage_name are both pulumi outputs, you get strange looking result when you concatenate them directly.

    You should either use Output.all with .apply or Output.concat and construct your string as follows. Note that conn_str is again a pulumi Output:

        # using concat
        conn_str = pulumi.Output.concat(
            "DefaultEndpointsProtocol=https;AccountName=",
            storage_name,
            ";AccountKey=",
            storage_primary_key,
            ";EndpointSuffix=core.windows.net",
        )
    
        # using Output.all with apply
        conn_str = pulumi.Output.all(storage_name, storage_primary_key).apply(
            lambda args: f"DefaultEndpointsProtocol=https;AccountName={args[0]};AccountKey={args[1]};EndpointSuffix=core.windows.net",
        )