Struggling with `Output`. Would appreciate some he...
# python
r
Struggling with
Output
. Would appreciate some help I have a list of
iam.Roles
. I want to iterate and create a dict with
role.name
as the key and
role.arn
as the value. Then export the dict. But because
role.name
is
Output
, I cannot use it as key and do something like this:
Copy code
role_arns_dict = [{role.name: role.value} for role in roles]
pulumi.export("role_arns", role_arns_dict)
Instead,
Copy code
roles_output = Output.all(role_names=[role.name for role in roles], role_arns=[role.arn for role in roles])
roles_output.apply(lambda roles_dict: _export_roles(roles_dict))

def _export_roles(roles_dict: dict) -> None:
    role_arns = {}
    for role_name, role_arn in zip(roles_dict["role_names"], roles_dict["role_arns"]):
        role_arns[role_name] = role_arn

    pulumi.export("role_arns", role_arns)
But the problem is seems because
.apply
is async,
pulumi preview
or
pulumi up
would finish without the
pulumi.export
has been executed yet. Any advice?
d
pulumi.export
takes Outputs as an input. Instead of calling export inside the apply, return the role_arns
You should also be able to use your roles directly like this, for some cleaner code:
Copy code
pulumi.Output.all(*roles).apply(
  lambda roles: {role.name: role.arn for role in roles}
)
r
Thanks Anthony! It looks like with this, within the
apply
,
role.name
is still
Output
, and it creates this error if I use it as a key of dict
Copy code
File "/Users/dennis.pan.117/code/iac/iam/venv/lib/python3.11/site-packages/pulumi/runtime/stack.py", line 242, in <dictcomp>
        key: massage(attr[key], seen) for key in attr if not key.startswith("_")
                                                             ^^^^^^^^^^^^^^^^^^^
    TypeError: 'Output' object is not callable
f
Copy code
role_dict_output = pulumi.Output.all(*[role.name.apply(lambda name: (name, role.arn)) for role in roles]).apply(
    lambda role_name_arn_pairs: {name: arn for name, arn in role_name_arn_pairs}
)
try something like this