https://pulumi.com logo
Docs
Join the conversationJoin Slack
Channels
announcements
automation-api
aws
azure
blog-posts
built-with-pulumi
cloudengineering
cloudengineering-support
content-share
contribex
contribute
docs
dotnet
finops
general
getting-started
gitlab
golang
google-cloud
hackathon-03-19-2020
hacktoberfest
install
java
jobs
kubernetes
learn-pulumi-events
linen
localstack
multi-language-hackathon
office-hours
oracle-cloud-infrastructure
plugin-framework
pulumi-cdk
pulumi-crosscode
pulumi-deployments
pulumi-kubernetes-operator
pulumi-service
pulumiverse
python
registry
status
testingtesting123
testingtesting321
typescript
welcome
workshops
yaml
Powered by Linen
dotnet
  • b

    breezy-salesmen-85534

    01/26/2021, 10:57 AM
    Vipps.Vce.International.BlueGreen.Tests.BlueGreenStackTests.Test_BaseStack_Constructor_CreatesAKS.Test_BaseStack_Constructor_CreatesAKS(environment: uat, projectType: Green, name: "dv-uat-green-aks")
    
    Pulumi.RunException: Running program '/Applications/Rider.app/Contents/lib/ReSharperHost/TestRunner/netcoreapp2.0/ReSharperTestRunner64.dll' failed wi...
    
    Pulumi.RunException
    Running program '/Applications/Rider.app/Contents/lib/ReSharperHost/TestRunner/netcoreapp2.0/ReSharperTestRunner64.dll' failed with an unhandled exception:
    System.InvalidOperationException: This operation cannot be performed on a default instance of ImmutableArray<T>.  Consider initializing the array, or checking the ImmutableArray<T>.IsDefault property.
       at System.Collections.Immutable.ImmutableArray`1.ThrowInvalidOperationIfNotInitialized()
       at System.Collections.Immutable.ImmutableArray`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
       at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
       at System.Linq.Enumerable.SelectEnumerableIterator`2.ToArray()
       at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
       at System.Collections.Immutable.ImmutableArray.CreateRange[T](IEnumerable`1 items)
       at System.Collections.Immutable.ImmutableArray.ToImmutableArray[TSource](IEnumerable`1 items)
       at Pulumi.Kubernetes.Yaml.Parser.<>c__DisplayClass2_0.<ParseYamlDocument>b__0(ImmutableArray`1 objs)
       at Pulumi.Output`1.ApplyHelperAsync[U](Task`1 dataTask, Func`2 func)
       at Pulumi.Output`1.ApplyHelperAsync[U](Task`1 dataTask, Func`2 func)
       at Pulumi.Output`1.Pulumi.IOutput.GetDataAsync()
       at Pulumi.Serialization.Serializer.SerializeAsync(String ctx, Object prop, Boolean keepResources)
       at Pulumi.Deployment.SerializeFilteredPropertiesAsync(String label, IDictionary`2 args, Predicate`1 acceptKey, Boolean keepResources)
       at Pulumi.Deployment.SerializeAllPropertiesAsync(String label, IDictionary`2 args, Boolean keepResources)
       at Pulumi.Deployment.RegisterResourceOutputsAsync(Resource resource, Output`1 outputs)
       at Pulumi.Deployment.Runner.<>c__DisplayClass9_0.<<WhileRunningAsync>g__HandleCompletion|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at Pulumi.Deployment.Runner.WhileRunningAsync()
       at Pulumi.Deployment.TestAsync(IMocks mocks, Func`2 runAsync, TestOptions options)
       at Vipps.Vce.International.BlueGreen.Tests.BlueGreenStackTests.Test_BaseStack_Constructor_CreatesAKS() in /Users/andreas.dreyer.hysing/code/vce/src/International.BlueGreen.Tests/BlueGreenStackTests.cs:line TAKEN OUT
       at Xunit.Sdk.TestInvoker`1.<>c__DisplayClass48_1.<<InvokeTestMethodAsync>b__1>d.MoveNext() in C:\Dev\xunit\xunit\src\xunit.execution\Sdk\Frameworks\Runners\TestInvoker.cs:line 264
    --- End of stack trace from previous location where exception was thrown ---
       at Xunit.Sdk.ExecutionTimer.AggregateAsync(Func`1 asyncAction) in C:\Dev\xunit\xunit\src\xunit.execution\Sdk\Frameworks\ExecutionTimer.cs:line 48
       at Xunit.Sdk.ExceptionAggregator.RunAsync(Func`1 code) in C:\Dev\xunit\xunit\src\xunit.core\Sdk\ExceptionAggregator.cs:line 90
    t
    • 2
    • 2
  • b

    breezy-salesmen-85534

    01/27/2021, 9:09 AM
    Vipps.Vce.Core.Tests.K8s.KubernetesClusterTests.Test_Create_Cluster
    
    Pulumi.RunException: Running program '/Applications/Rider.app/Contents/lib/ReSharperHost/TestRunner/netcoreapp2.0/ReSharperTestRunner64.dll' failed wi...
    
    Pulumi.RunException
    Running program '/Applications/Rider.app/Contents/lib/ReSharperHost/TestRunner/netcoreapp2.0/ReSharperTestRunner64.dll' failed with an unhandled exception:
    System.NullReferenceException: Object reference not set to an instance of an object.
       at Pulumi.Testing.MockMonitor.SerializeToDictionary(Object o)
       at Pulumi.Testing.MockMonitor.RegisterResourceAsync(Resource resource, RegisterResourceRequest request)
       at Pulumi.Deployment.RegisterResourceAsync(Resource resource, Boolean remote, Func`2 newDependency, ResourceArgs args, ResourceOptions options)
       at Pulumi.Deployment.ReadOrRegisterResourceAsync(Resource resource, Boolean remote, Func`2 newDependency, ResourceArgs args, ResourceOptions options)
       at Pulumi.Deployment.CompleteResourceAsync(Resource resource, Boolean remote, Func`2 newDependency, ResourceArgs args, ResourceOptions options, ImmutableDictionary`2 completionSources)
       at Pulumi.Output`1.GetValueAsync()
       at Pulumi.Deployment.Logger.TryGetResourceUrnAsync(Resource resource)
       at Pulumi.Deployment.Runner.<>c__DisplayClass9_0.<<WhileRunningAsync>g__HandleCompletion|0>d.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at Pulumi.Deployment.Runner.WhileRunningAsync()
       at Pulumi.Deployment.TestAsync(IMocks mocks, Func`2 runAsync, TestOptions options)
       at Vipps.Vce.Core.Tests.K8s.KubernetesClusterTests.CreateCluster() in /Users/andreas.dreyer.hysing/code/vce/src/Core.Tests/K8s/KubernetesClusterTests.cs:line 39
       at Vipps.Vce.Core.Tests.K8s.KubernetesClusterTests.Test_Create_Cluster() in /Users/andreas.dreyer.hysing/code/vce/src/Core.Tests/K8s/KubernetesClusterTests.cs:line 48
       at Xunit.Sdk.TestInvoker`1.<>c__DisplayClass48_1.<<InvokeTestMethodAsync>b__1>d.MoveNext() in C:\Dev\xunit\xunit\src\xunit.execution\Sdk\Frameworks\Runners\TestInvoker.cs:line 264
    --- End of stack trace from previous location where exception was thrown ---
       at Xunit.Sdk.ExecutionTimer.AggregateAsync(Func`1 asyncAction) in C:\Dev\xunit\xunit\src\xunit.execution\Sdk\Frameworks\ExecutionTimer.cs:line 48
       at Xunit.Sdk.ExceptionAggregator.RunAsync(Func`1 code) in C:\Dev\xunit\xunit\src\xunit.core\Sdk\ExceptionAggregator.cs:line 90
    t
    • 2
    • 4
  • b

    breezy-salesmen-85534

    01/27/2021, 9:09 AM
    Yesterday I stated that testing Kubernetes, helm and azure on pulumi gave mysterious crashes with stacktraces. You encuraged me write a minimal version of
    BlueGreenStack
    , and provide as an example. with Network Security Groups (NSGs), Role Based Access Control (RBAC), fluentd, in that stack I don’t think that is possible. However today i tried setting up a single Kubernetes cluster as a mock in pulumi. I hade a similar issue. If I can get some input how to create KubernetesCluster , then I can probably fix my BlueGreenStack. Here is thee example and the test tesult. What can I to test this?
    using Moq;
    using System.ComponentModel;
    using System.Linq;
    using System.Threading.Tasks;
    using Pulumi;
    using Pulumi.Azure.ContainerService;
    using Pulumi.Azure.ContainerService.Inputs;
    using Pulumi.Testing;
    using Xunit;
    
    namespace Vipps.Vce.Core.Tests.K8s
    {
        public class KubernetesClusterStack : Stack
        {
            public KubernetesClusterStack()
            {
                KubernetesClusterArgs args = new KubernetesClusterArgs
                {
                    DefaultNodePool = new KubernetesClusterDefaultNodePoolArgs
                    {
                        Name = "any node pool name",
                        VmSize = "any VM size"
                    },
                    DnsPrefix = "any string",
                    ResourceGroupName = "any string"
                };
                CustomResourceOptions options = new CustomResourceOptions();
                var _ = new KubernetesCluster("foo", args, options);
            }
        }
    
        public class KubernetesClusterTests
        {
            private async Task<KubernetesCluster> CreateCluster()
            {
                string projectName = "project";
                string stackName = "project-blue";
                var mocks = new Mock<IMocks>();
                var deployment = await Deployment.TestAsync<KubernetesClusterStack>(mocks.Object,
                    new TestOptions {ProjectName = projectName, StackName = stackName});
                return deployment.OfType<KubernetesCluster>().FirstOrDefault();
            }
    
            [Fact]
            [Category("pulumi")]
            public async Task Test_Create_Cluster()
            {
                var akscluster = await CreateCluster();
                Assert.NotNull(akscluster);
            }
        }
    }
    And the related test result
  • w

    wet-noon-14291

    01/30/2021, 1:03 AM
    Is there a way to tell pulumi to retry before failing when creating a resource. I have some trouble creating an API Management thing that seems timing related, so 1-2 retry should fix it. I have dependencies, but that doesn't seem to help for some reason.
    t
    • 2
    • 15
  • b

    brainy-ocean-92780

    02/01/2021, 10:54 PM
    Hello All! What's the best way to look at the resources in my current stack at runtime? The problem I'm attempting to solve, in azure, is to make a backup of my database in the event that it exists or to ignore this case if it does not.
  • b

    brainy-ocean-92780

    02/01/2021, 10:55 PM
    I want to look and see if the resource exists at the beginning of pulumi up and create the backup just in case something goes awry.
  • r

    red-lighter-44012

    02/02/2021, 7:01 AM
    I think that you need to use one of the
    ResourceType.Get()
    method variations to look up your resource by name. Maybe this: https://www.pulumi.com/docs/reference/pkg/azure/sql/database/#look-up But it requires a known resource ID. The more generic Get works with a name IIRC.
  • t

    tall-needle-56640

    02/04/2021, 11:44 PM
    Any idea what is going on here? Why is the reference after the
    Output.Create
    possibly null?
    private void DoSomething(ResourceGroup resourceGroup)
    {
        var test = resourceGroup.Name;  // No null warning
        var output = Output.Create(resourceGroup);
        var test2 = resourceGroup.Name; // Possible null reference warning
    }
    t
    • 2
    • 2
  • a

    able-rose-67471

    02/11/2021, 9:17 AM
    Hey guys! Just wondering if it's possible to import resources from a different subscription? We have a CI pipeline that stands up infrastructure for each development branch and then deploys to that infrastructure to our 'dev' subscription. We also have a 'global' subscription that hosts a KeyVault to store all of our applications SSL certificates. I was hoping using the
    KeyVault.Get()
    method would work, since it requires the full resource ID (including the subscription segment). But when I try that, it returns "does not exist". Similarly, I've also tried the
    pulumi import
    and that won't work either (I would have to switch subscriptions before running it, and then switch back after which results in the same "does not exist" message. I thought I'd check on here before heading back to the drawing board as I fear I may have misunderstood the import capabilities!
    f
    t
    • 3
    • 4
  • a

    adamant-bird-10534

    02/14/2021, 8:31 AM
    hi guys, i'm creating a pulumi pipeline in Azure DevOps. For a dotnet application, i would normally build the code, and ship the artifacts to a stage where i would deploy them. It looks like the Pulumi Up command does build the code before running the deployment. Is there a way for me prebuild the code before running Pulumi Up? I.e. to either run dotnet build, or "pulumi build" to compile the code and emit assemblies. I would then ship those assemblies and then Pulumi Up on those assemblies, not on the C# code?
    t
    • 2
    • 2
  • c

    curved-doctor-83600

    02/16/2021, 11:01 AM
    Hi, I am currently stuck trying to set the values for a helm chart in c#. I am using ingress-nginx helm chart (to deploy it to aks) and want to set a static ip to the loadbalancer. There is a value controller.service.loadBalancerIP available to set for the chart, but it seems that I can't set that to an output (the staticIP is an output). I am using a Dictionary here, because trying to use an InputMap results in this (https://github.com/pulumi/pulumi/issues/5961). Any hints on how to do that?
    Values =
                {
                    { "controller", new Dictionary<string,object>
                        {
                            { "replicaCount", NodeCount },
                            { "service", new Dictionary<string, object>
                                {
                                    { "externalTrafficPolicy", "local" },
                                    { "loadBalancerIP", staticIp }
                                }
                            }
                        }
                    }
                }
    t
    m
    • 3
    • 6
  • w

    wet-noon-14291

    02/16/2021, 11:29 AM
    Let's say I want to do something after a resource to get a value that is input to another resource, how do I achieve that? Do I do something like:
    var someVal = resource1.Id.Apply(id => { return GetSomeValue(); });
    var resource2 = new SomeResource("name", SomeArgs({AValue = someVal}));
    Am I guaranteed that
    someVal
    will "resolve" after
    resource1
    is done or is there another way to do this?
    t
    • 2
    • 3
  • n

    numerous-artist-1705

    02/17/2021, 12:24 PM
    @wet-noon-14291 (and anyone else interested): I just released
    Pulumi.FSharp.Kubernetes
    all should be working now. I'd appreciate if anyone could test it as I do not have any K8s cluster at the moment to use it.
  • m

    miniature-leather-70472

    02/17/2021, 2:46 PM
    I've got some C# Pulumi deployment that works great, but at the end of the deployment I need to call an http webhook, passing one of the values created during my deployment. Can I do this in my Pulumi project, maybe using httpclient or similar, or does this need to occur outside of my Pulumi code in another pipeline step or similar? I'm not clear how Pulumi deals with additional C# code that depends on a value generated by the deployment
    w
    t
    n
    • 4
    • 9
  • t

    tall-needle-56640

    02/25/2021, 5:46 PM
    Does integration testing exist for .NET? I see GO is importing
    "<http://github.com/pulumi/pulumi/pkg/testing/integration|github.com/pulumi/pulumi/pkg/testing/integration>"
    , but I don't see an
    Integration
    namespace in the NuGet package. As part of moving away from ARM to Pulumi, the team would like to see all integration tests still passing.
    t
    • 2
    • 4
  • w

    wet-noon-14291

    03/01/2021, 10:06 PM
    Is it possible to use a
    CustomResource
    as a dependency but it should only return created when one or more of the resources it wraps are done? Pseudo example:
    MyCustomResource: CustomResource {
       var resourceA = new A();
       var resourceB = new B();
       var resourceC = new C();
    }
    
    Deploy {
       var myResource = new MyCustomResource();
       var someOtherResournce = new SomeOtherResource({ dependsOn = [myResource]);
    }
    In the
    dependsOn
    there, is it possible to have that resource to delegate the check to one or more of resourceA, resourceB or resourceC? I think that is what causing one of our deploy to fail now since we "wrap" a kubernetes deployment, but the dependency is to our
    CustomResource
    and not to the actual deployment.
    t
    • 2
    • 2
  • m

    magnificent-television-29869

    03/10/2021, 11:09 AM
    Hi All, I am getting a panic when doing up
    f
    • 2
    • 1
  • m

    magnificent-television-29869

    03/10/2021, 11:09 AM
    panic: runtime error: invalid memory address or nil pointer dereference
    t
    • 2
    • 3
  • m

    magnificent-television-29869

    03/16/2021, 9:50 AM
    So ehm, I am trying to create a RecordSet, but I am am unsure why it says it cannot find the dns zone resource, I specify the name of the resource group and the domain name for the dns zone (which seems to be the way its named in azure), however pulumi says it cant find the resource, is this because the dns zone resources are not managed by this particular stack ?
    b
    t
    • 3
    • 9
  • m

    magnificent-television-29869

    03/16/2021, 2:02 PM
    and so Im at it again,
    azure-native:cdn:CustomDomain (abc-de.fgh.ijk.lm):
        error: Preview failed: autorest/azure: Service returned an error. Status=400 Code="BadRequest" Message="Property 'CustomDomainEntityKey.CustomDomainName' cannot be set to 'abc-de.fgh.ijk.lm'
    the code I am running is
    return new CustomDomain(fqdn, new CustomDomainArgs()
            {
                EndpointName = cdnEndpoint.Name,
                ProfileName = cdnProfile.Name,
                HostName = fqdn,
                ResourceGroupName = resourceGroup.Name,
                CustomDomainName = fqdn
            });
    What am I doing wrong ?
    b
    • 2
    • 2
  • m

    magnificent-television-29869

    03/17/2021, 8:32 AM
    Anyone have any ideer why this happens?
  • a

    average-dinner-84543

    03/17/2021, 1:42 PM
    Hi everybody! Just wondering if there is a SDK for accessing SQL SERVER no matters where it is (Azure or VM). Because the only thing I could find is cloud specific : https://www.pulumi.com/docs/reference/pkg/azure-native/sqlvirtualmachine/sqlvirtualmachine/
    g
    • 2
    • 2
  • c

    creamy-crowd-26033

    03/17/2021, 6:07 PM
    Sorry, new to slack and didn't see this channel originally. The question probably belongs here.
    • 1
    • 1
  • a

    average-spoon-16995

    03/18/2021, 8:14 AM
    Hi guys! When adding this property to my ManagedCluster I get the following error message.
    Identity = new AzureNative.ContainerService.Inputs.ManagedClusterIdentityArgs
                {
                    Type = AzureNative.ContainerService.ResourceIdentityType.UserAssigned,
                    UserAssignedIdentities = {
                     { $"/subscriptions/(i have my sub id here)/resourcegroups/rg-aks-pulumi-fabio9d58994b/providers/Microsoft.ManagedIdentity/userAssignedIdentities/fabio-Test", "" }
                }
                },
    error: Code="FailedIdentityOperation" Message="Identity operation for resource '/subscriptions/(here to)/resourceGroups/rg-aks-pulumi-fabio9d58994b/providers/Microsoft.ContainerService/managedClusters/aks-test38e10d3d' failed with error 'Failed to perform resource identity operation. Status: 'BadRequest'. Response: '{\"error\":{\"code\":\"BadRequest\",\"message\":\"Resource name Request does not support null for removing assigned identities.  is invalid for user assigned identity.\"}}'.'."
    t
    • 2
    • 3
  • a

    average-spoon-16995

    03/18/2021, 8:17 AM
    This is from the documentation
    Identity = new AzureNative.ContainerService.Inputs.ManagedClusterIdentityArgs
                {
                    Type = "UserAssigned",
                    UserAssignedIdentities = 
                    {
                        { "/subscriptions/subid1/resourceGroups/rgName1/providers/Microsoft.ManagedIdentity/userAssignedIdentities/identity1",  },
                    },
                },
  • a

    astonishing-monitor-96741

    03/23/2021, 5:03 PM
    Hey all! Has anyone had issues when creating multiple Docker images at the same time? We have a scenario where we fire off 4
    new Docker.Image(new Docker.ImageArgs { Build = new Docker.DockerBuild....
    commands to build 4 different images and frequently (not always) have it throw an error during pulumi up:
    Executing ' docker login'
    Executing ' docker login'
    Executing ' docker login'
    Executing ' docker login'
    Login Succeeded
    Login Succeeded
    Login Succeeded
    warning: WARNING! Your password will be stored unencrypted in C:\Users\AzDevOps.vmss000026\.docker\config.json.Configure a credential helper to remove this warning. See<https://docs.docker.com/engine/reference/commandline/login/#credentials-store>
    error: WARNING! Your password will be stored unencrypted in C:\Users\AzDevOps.vmss000026\.docker\config.json.Configure a credential helper to remove this warning. See<https://docs.docker.com/engine/reference/commandline/login/#credentials-storeError> saving credentials: rename C:\Users\AzDevOps.vmss000026\.docker\config.json866015259 C:\Users\AzDevOps.vmss000026\.docker\config.json: Access is denied.
    warning: WARNING! Your password will be stored unencrypted in C:\Users\AzDevOps.vmss000026\.docker\config.json.Configure a credential helper to remove this warning. See<https://docs.docker.com/engine/reference/commandline/login/#credentials-store>
    ' docker login' failed with exit code 1
    warning: WARNING! Your password will be stored unencrypted in C:\Users\AzDevOps.vmss000026\.docker\config.json.Configure a credential helper to remove this warning. See<https://docs.docker.com/engine/reference/commandline/login/#credentials-store>
    So 1 of the 4 above has issues writing to the warning temp docker config file, I'm assuming at the same time.
    👍 1
    • 1
    • 3
  • f

    flat-mouse-20634

    03/29/2021, 8:01 AM
    Hello All, I am migrating C# code from classic Azure to Azure-Native which is going well so far but I am facing a small issue with unit tests. Here is the code that I’d like to test
    var resourceGroup = new ResourceGroup("mystaticsite");
    var storageAccount = new StorageAccount("mysite", new StorageAccountArgs
    {
        ResourceGroupName = resourceGroup.Name,
        EnableHttpsTrafficOnly = true,
        Sku = new SkuArgs
        {
            Name = SkuName.Standard_LRS
        },
        AccessTier = AccessTier.Hot,
        Kind = Kind.StorageV2,
    });
    PrimaryWebEndpoint = storageAccount.PrimaryEndpoints.Apply(x=>x.Web);
    My test is trying to verify that the ResourceGroup was created
    private static Task<ImmutableArray<Pulumi.Resource>> TestAsync()
    {
        return Pulumi.Deployment.TestAsync<WebsiteStack>(new Mocks(), new TestOptions {IsPreview = false});
    }
    
    [Fact]
    public async Task ResourceGroup_ShouldExist()
    {
        var resources = await TestAsync();
    
        var resourceGroups = resources.OfType<ResourceGroup>().ToList();
    
        resourceGroups.Count.ShouldBe(1);
    }
    I couldn’t get the test to pass because I can’t find a way to mock
    EndpointsResponse
    Are there a recommended way to handle this scenario?
    p
    • 2
    • 2
  • c

    chilly-hairdresser-56259

    03/31/2021, 9:33 PM
    With pulumi_aws am I correct we cannot supply WLM json to the Cluster? Or where is that at?
  • p

    purple-train-14007

    03/31/2021, 11:02 PM
    I have to say as a dotnet dev, I love pulumi. It is not often that as a developer we get any love from platforms/tools. Ty Pulumi.
    🙏 2
    b
    • 2
    • 2
  • t

    tall-needle-56640

    04/01/2021, 4:22 PM
    Can this code be simplified?
    foreach (var element in Environment.GetEnvironmentVariables())
    {
        if (element is KeyValuePair<string, object> pair
            && pair.Value is string valueStr)
            env[pair.Key] = valueStr;
    }
    Environment.GetEnvironmentVariables
    returns an
    IDictionary
    . Ideally, it would be typed, but generics probably hadn't been introduced yet. I think it's obvious that it should actually return
    IDictionary<string, string?>
    , but in case of any doubt
    Environment.GetEnvironmentVariable(string)
    only returns
    string?
    , not
    object
    . So what value does
    element is KeyValuePair<string, object>
    give us? Therefore, couldn't the code be simplified to
    foreach (var pair in Environment.GetEnvironmentVariables())
    {
        if (pair.Value is string valueStr)
            env[pair.Key] = valueStr;
    }
    @bored-oyster-3147
    b
    p
    e
    • 4
    • 23
Powered by Linen
Title
t

tall-needle-56640

04/01/2021, 4:22 PM
Can this code be simplified?
foreach (var element in Environment.GetEnvironmentVariables())
{
    if (element is KeyValuePair<string, object> pair
        && pair.Value is string valueStr)
        env[pair.Key] = valueStr;
}
Environment.GetEnvironmentVariables
returns an
IDictionary
. Ideally, it would be typed, but generics probably hadn't been introduced yet. I think it's obvious that it should actually return
IDictionary<string, string?>
, but in case of any doubt
Environment.GetEnvironmentVariable(string)
only returns
string?
, not
object
. So what value does
element is KeyValuePair<string, object>
give us? Therefore, couldn't the code be simplified to
foreach (var pair in Environment.GetEnvironmentVariables())
{
    if (pair.Value is string valueStr)
        env[pair.Key] = valueStr;
}
@bored-oyster-3147
b

bored-oyster-3147

04/01/2021, 4:25 PM
Maybe? But I don't know if we know the type of
pair.Key
is
string
at compile-time so
env[pair.key] = ...;
might give you an error?
Here's your answer I think:
We need to get the KVP first.
Did you find that we were losing environment variables doing it this way?
t

tall-needle-56640

04/01/2021, 4:44 PM
Ah, that makes sense. There's no problems, I was just confused why the second type was
object
and not
string
.
b

bored-oyster-3147

04/01/2021, 5:17 PM
Have you personally tried passing environment variables from your system into pulumi? I was just messing with this code in a console app and I found some issues (thanks for bringing it up, lol). First of all,
element
is of type
System.Collection.DictionaryEntry?
. And none of them satisfied
KeyValuePair<string, object>
,
KeyValuePair<string, string>
, or
KeyValuePair<string, string?>
... which is concerning I actually had to do this to get working:
var env = Environment.GetEnvironmentVariables();
            foreach (DictionaryEntry? element in env)
            {
                if (element is null || !element.HasValue)
                    continue;

                if (element.Value.Key is string keyStr
                    && element.Value.Value != null
                    && element.Value.Value is string valueStr)
                    Console.WriteLine($"[{keyStr}] = {valueStr}");
            }
@enough-garden-22763 this may be an oversight on my part we might want a test that system environment vars are making it into pulumi execution, I think my
is KeyValuePair<string, object>
check might never be satisfied currently
Specifically here: https://github.com/pulumi/pulumi/blob/7f8985ab0fb870f0cd577f474255b348d6ebeefe/sdk/dotnet/Pulumi.Automation/Commands/LocalPulumiCmd.cs#L101
p

prehistoric-coat-10166

04/01/2021, 5:25 PM
https://docs.microsoft.com/en-us/dotnet/api/system.environment.getenvironmentvariables?view=net-5.0 for more details on
System.GetEnvironmentVariables
But yeah
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
should do the trick and then checking the key & value
b

bored-oyster-3147

04/01/2021, 5:26 PM
that's a pretty big faux pas on my part yikes
@prehistoric-coat-10166 unfortunately with the nullable reference types enabled that function is returning nullable dictionary entries for some reason so that added null check complexity in my example above is necessary
t

tall-needle-56640

04/01/2021, 5:29 PM
This is redundant:
element.Value.Value != null
                    && element.Value.Value is string valueStr
If it's null, it won't say it's a string
b

bored-oyster-3147

04/01/2021, 5:31 PM
you are correct, that is because I was doing this first and was getting an error and switched to what I posted
p

prehistoric-coat-10166

04/01/2021, 5:33 PM
if (element.Value.Key is string keyString
                    && element.Value.Value is string valueString)
                {
                    env[keyString] = valueString;
                }
Should work (with the element null check)
e

enough-garden-22763

04/01/2021, 5:38 PM
Hey team just seeing this discussion here 👋
System environment vars are making it into pulumi execution indeed, we don’t have a test checked in but some test I’ve done indicate its’ happening.
b

bored-oyster-3147

04/01/2021, 5:45 PM
Cool so we should be good with your PR, then. Awesome.
p

prehistoric-coat-10166

04/01/2021, 5:46 PM
Yeah, deleted code is best code!
🙌 1
Do we want to still allow the nullable environment variables on our end? With for example default value of empty to consistently "unset" environment variables until CliWrap allows nulls?
Although I guess it might just as easy on the users' side to use
ValueWhichMayBeNull ?? ""
Heh, actually the problem seems to go deeper to
Process
https://github.com/dotnet/runtime/issues/34446
View count: 1