Skip to content

✨withEnvVariables #4835

Closed
Closed

Description

@RonanQuigley

What are you trying to do?

This came out of a convo on Discord.

I would like to Dagger to support a withEnvVariables call. The syntax would like like this

withEnvVariables({
    ENV_VAR_1: "VALUE",
    ENV_VAR_2: "VALUE"
    ENV_VAR_3: "VALUE"
    ...
})

[I might try and put a pull request in for this one, but I've raised in case I don't get around to it. cc @jpadams @kpenfound]

Why is this important to you?

Complex pipelines can require numerous environment vars to be configured. Writing out withEnvVariable over and over gets tedious and bloats the pipeline code.

How are you currently working around this?

Using withEnvVariable for every env var that needs set.

Activity

  1. helderco commented on Mar 29, 2023

    @helderco
    Contributor

    You can actually create a reusable function to help with that:

    import Client, { connect } from "@dagger.io/dagger"
    import { Container } from "@dagger.io/dagger/dist/api/client.gen"
    
    
    connect(async (client) => {
        const ctr = client
            .container()
            .from("alpine")
            .with(envVariables({
                ENV_VAR_1: "VALUE 1",
                ENV_VAR_2: "VALUE 2",
                ENV_VAR_3: "VALUE 3",
            }))
            .withExec(["env"])
    
        console.log(await ctr.stdout())
    })
    
    
    function envVariables(envs: Record<string, string>) {
        return (c: Container): Container => {
            Object.entries(envs).forEach(([key, value]) => {
                c = c.withEnvVariable(key, value)
            })
            return c
        }
    }

    That's using the new with(...) feature, and I'm assuming you're using the NodeJS SDK. Without using with(...) it's easy enough with a normal function, but then you have to break the chain:

    function withEnvVariables(c: Container, envs: Record<string, string>): Container {
        Object.entries(envs).forEach(([key, value]) => {
            c = c.withEnvVariable(key, value)
        })
        return c
    }
  2. grouville commented on Apr 17, 2023

    @grouville
    Member

    @mircubed I do not understand the actionable step on this issue ? It is currently stuck by #3885 nonetheless

  3. helderco commented on Apr 17, 2023

    @helderco
    Contributor

    It is currently stuck by #3885 nonetheless

    @grouville It's not stuck on #3885. I provided usage with that feature in above comment. In Node.js it has been released already. In the others it'll be available in next release but it's already in main.

    This issue just requires a decision if it's worth to add to the API or not.

  4. grouville commented on Apr 18, 2023

    @grouville
    Member

    @helderco, wdyt about adding that ? I can start the implementation right away, even though the with() implementation can indeed avoid overcharging the API

  5. helderco commented on Apr 18, 2023

    @helderco
    Contributor

    OP is right that it's common to need to set multiple env vars. I haven't seen so many of them put together to justify this, but if people find a need for it, each will have to create and reuse the helper above. So I think it's alright to add it to the API, but that's just me.

  6. self-assigned this
    on Apr 18, 2023
  7. grouville commented on Apr 25, 2023

    @grouville
    Member

    After digging into that, discussing with @vito, there is no clear winner on the developer experience for strongly typed languages.

    Current alternatives

    1. map[string]string:

    A simple map for environment variables, easy to use but without order guarantee.

    go
    // Datastructure
    type EnvVars map[string]string
    
    // Usage
    WithEnvVariables(EnvVars{
        "toto": "tata",
        "tutu": "titi",
    })
    python
    with_env_variables({
        "toto": "tata",
        "tutu": "titi",
    })
    node.js
    withEnvVariables({
      toto: 'tata',
      tutu: 'titi',
    });

    This provides the best developer experience and simplest implementation across languages. However, the lack of ordering can cause issues when there are cross-references between environment variables or duplicate keys (in such cases, it's unclear which variable takes precedence).

    2. []dagger.EnvVars

    A slice of dagger.EnvVars structs, preserves order but requires more verbose syntax.

    go
    type EnvVars struct {
        Name  string `json:"name"`
        Value string `json:"value"`
    }
    
    // Usage
    WithEnvVariables([]EnvVars{
        {Name: "toto", Value: "tata"},
        {Name: "tutu", Value: "titi"},
    })
    python
    # implementation
    from collections import namedtuple
    
    EnvVar = namedtuple('EnvVar', ['name', 'value'])
    
    # Usage
    with_env_variables([
        EnvVar("toto", "tata"),
        EnvVar("tutu", "titi"),
    ])
    node.js
    class EnvVar {
      constructor(name, value) {
        this.name = name;
        this.value = value;
      }
    }
    
    withEnvVariables([
      new EnvVar('toto', 'tata'),
      new EnvVar('tutu', 'titi'),
    ]);

    3. Ordered map

    A custom data structure combining a map and slice to maintain key order, but different DX with statically typed languages.

    go
    type EnvVars struct {
        varsMap   map[string]string
        varsOrder []string
    }
    
    
    // Usage
    WithEnvVariables(NewEnvVars(map[string]string{
        "toto": "tata",
        "tutu": "titi",
    }).ToSlice())
    python
    from collections import OrderedDict
    
    env_vars = OrderedDict([
        ("toto", "tata"),
        ("tutu", "titi"),
    ])
    
    with_env_variables(env_vars)
    node.js
    const envVars = new Map([
      ['toto', 'tata'],
      ['tutu', 'titi'],
    ]);
    
    withEnvVariables(envVars);

    4. Split string

    A slice of strings in "key=value" format; conflicts with current WithEnvironmentVariable implementation.

    go
    // Usage
    WithEnvVariables([]string{"toto=tata", "tutu=titi"})
    python
    # Usage
    with_env_variables(["toto=tata", "tutu=titi"])
    node.js
    // Usage
    withEnvVariables(['toto=tata', 'tutu=titi']);

    I've drafted a PR implementing option 2 (in Go), which is most compliant with the current DX across the API. However, introducing a non-perfect solution for a potential niche use-case may not be ideal. The With() solution by @helderco can help avoid API extension for niche cases.

    We may close this issue and let users reopen it if needed. Depending on the number of requests, we can consider implementing one of the solutions above.

  8. vito commented on Apr 25, 2023

    @vito
    Contributor

    @grouville Thanks for elucidating all of the options here 🙏

    I want to throw a sneaky option out there: what if we shortened WithEnvVariable to WithEnv? It feels pretty long for something that's used nearly everywhere. I wonder if this feature would have even been requested if it were shorter. I remember we considered shortening it but decided to keep it long because it clarifies the other env-related field names, but I'm not sure it's worth the constant tax on DX. It's pretty exhausting to type and read, frankly.

    The typed options above don't seem to help much TBH:

    WithEnvVariables([]EnvVars{
        {Name: "toto", Value: "tata"},
        {Name: "tutu", Value: "titi"},
    })
    
    // vs.
    WithEnvVariable("toto", "tata").
    WithEnvVariable("tutu", "titi")
    
    // vs.
    WithEnv("toto", "tata").
    WithEnv("tutu", "titi")

    Aside from WithEnv, I'm also partial to the NAME=value option because it's familiar from a Go and Unix perspective, but it might be weird in other languages that don't directly expose that underlying format. It's at least a lot shorter! If we changed Container.EnvVariables to return the same format you could even do this:

    vars, err := ctr.EnvVariables(ctx)
    ctr.WithEnvVariables(vars)
  9. grouville commented on Apr 25, 2023

    @grouville
    Member

    @grouville Thanks for elucidating all of the options here 🙏
    ...

    Thank you, @vito, for your addition ! 🙏

    The proposed changes are a solid alternative. I agree that deprecating the previous withEnvVariable implementation in favor of withEnv with option 4 makes sense. This would unify the API across all languages using []string{} or string.... datastruct.

    Although this approach deviates from other implementations like withLabel, it is more consistent with Unix principles. To guide users, proper examples in Go, Python and Node.js could always be provided, as well as a hint from linters ?
    WDYT @helderco ? @aluzzardi

    Summary:

    1. deprecate withEnvVariable and all related APIs
    2. create a withEnv, whose args is: []string{} or string.... Expected arg format: KEY=VALUE
    3. Create corresponding withEnvs()
  10. vito commented on Apr 25, 2023

    @vito
    Contributor

    Sorry, I crossed some streams there by suggesting multiple things at once.

    I think if we do WithEnv it'd be better to keep it WithEnv(name, value) rather than WithEnv("name=value"), the benefit being just a shorter name. A lot of times the value is a parameter so it's nice to not have to concatenate a string. The only scenario where name=value seems OK to me is when you're setting a bunch at once, and concatenating strings is the lesser evil to typing out a bunch of data structures.

    It might be cool if we supported WithEnv(...string) like you mentioned, since it'd all be one API, but it's tricky to support splat arguments because it prevents us from also supporting optional params in the same API. (WithExec is a good example of this.)

  11. mircubed commented on Apr 25, 2023

    @mircubed
    Contributor

    @aluzzardi could you give your thoughts on this, so @grouville can move forward?

  12. helderco commented on Apr 25, 2023

    @helderco
    Contributor

    On Ordered map, in Python a simple dict preserves key order (no need for OrderedDict these days). It's the same with Node.js objects1. And the Go implementation doesn’t seem correct because NewEnvVars receives a map[string]string so I don’t see how that implementation can preserve key order.

    At first glance, the simplest DX would be to use the simplest map structure that preserves key order. That means []dagger.EnvVar{} for Go and simple object/dict ({}) for Python and Node.js.

    The problem is that there’s no map primitive in GraphQL that we can use as input so that the SDKs would do the simplest thing for each language. You need a list of objects.

    We already have an EnvVariable type but it’s used for outputs, not inputs. If you adapt it or create a new EnvVar for input (😕) then you can’t codegen differently in the SDKs with simpler map structures, so you’re stuck with the more verbose implementation.

    Compared with what we have now, there’s not much gain for that, especially if we shorten the name like @vito suggests:

    // ❌ more verbose
    .withEnvVariables([
      new EnvVar('toto', 'tata'),
      new EnvVar('tutu', 'titi'),
    ])
    
    // ✅ simpler
    .withEnv('toto', 'tata')
    .withEnv('tutu', 'titi')

    We can instead create a custom input type that is generic:

    input KeyPair {
        key: String!
        value: String!
    }
    
    type Container {
        withEnvVariables(input: [KeyPair!])
    }

    That would allow codegen to do the simplest thing in each SDK, but the simplest thing in Go here is actually more verbose than what we already have, and we’re adding drift between the SDKs to keep things idiomatic.

    Go

    WithEnvVariables([]dagger.KeyPair{
        {Key: "toto", Value: "tata"},
        {Key: "tutu", Value: "titi"},
    })

    Python

    with_env_variables({
        "toto": "tata",
        "tutu": "titi",
    })

    Node.js

    withEnvVariables({
      toto: 'tata',
      tutu: 'titi',
    })

    I’ve been thinking for a while that SDKs could provide helpers (compatible with .with(), for example) to abstract patterns that users keep reinventing, but it’s not clear how much that can become obsolete with extensions in the future.

    // implementation by the SDK
    with(dagger.envVariables({
        ENV_VAR_1: "VALUE 1",
        ENV_VAR_2: "VALUE 2",
        ENV_VAR_3: "VALUE 3",
    })

    Simpler rename to withEnv sounds good to me.

    Footnotes

    1. Taking into consideration the interpreters that are supported by dagger ↩

  13. vito commented on Apr 25, 2023

    @vito
    Contributor

    If we rename to withEnv we'll also want to figure out what the names for all the env-related things should be:

    type Container {
      envVariables: [EnvVariable!]!
      envVariable(name: String!): String
      withEnvVariable(name: String!, value: String!): Container!
      withoutEnvVariable(name: String!): Container!
      withSecretVariable(name: String!, secret: SecretID!): Container!
    }

    I remember this being the hard part. :)

    Strawman:

    type Container {
      envs: [EnvVariable!]!
      env(name: String!): String
      withEnv(name: String!, value: String!): Container!
      withoutEnv(name: String!): Container!
      # consistent with withMountedSecret, + tab-complete discoverability
      withEnvSecret(name: String!, secret: SecretID!): Container!
    }
  14. grouville commented on Apr 26, 2023

    @grouville
    Member

    On Ordered map, in Python a simple dict preserves key order (no need for OrderedDict these days). It's the same with Node.js objects1. And the Go implementation doesn’t seem correct because NewEnvVars receives a map[string]string so I don’t see how that implementation can preserve key order.

    Thanks for the precision on Node && Python. Regarding the implementation of the ordered map in Go, I was thinking about settling on an ordering, not necessarily the ordering in which it was inputted in the map. (but you're right, the corresponding struct was created on top of my head, maybe not best implementation).

    I’ve been thinking for a while that SDKs could provide helpers (compatible with .with(), for example) to abstract patterns that users keep reinventing, but it’s not clear how much that can become obsolete with extensions in the future.

    I totally agree, and the more I explore the backlog, the more I feel this is needed. For example, I am currently writing docs for #4896 (as, after discussion with @vito, it seems to be the best way to fix this issue: creating a helper function that people can reuse, client-side).

    For that, I took the with() compatible approach:

    func mountSecretsFromDirectory(client *dagger.Client, sourceDir, targetDir string) func(*dagger.Container) *dagger.Container {
    	return func(c *dagger.Container) *dagger.Container {
    		err := filepath.Walk(sourceDir, func(path string, info fs.FileInfo, err error) error {
    			if err != nil {
    				return err
    			}
    
    			if !info.IsDir() {
    				relativePath, _ := filepath.Rel(sourceDir, path)
    				targetPath := filepath.Join(targetDir, relativePath)
    
    				// Read file
    				content, err := ioutil.ReadFile(path)
    				if err != nil {
    					return err
    				}
    
    				// Set secret to file content
    				secret := client.SetSecret("ghConfig-"+relativePath, string(content))
    
    				// Mount secret as file in container
    				c = c.WithMountedSecret(targetPath, secret)
    			}
    
    			return nil
    		})
    
    		if err != nil {
    			panic(err)
    		}
    
    		return c
    	}
    }

    This could be the solution here too, and I wonder if we're not starting to fight against the stream: part of DX issues at the moment are due to the root cause @helderco exposed right above, and if SDKs could provide helpers , in a unified manner (a new section on the docs page, where community could contribute on their helpers (like a universe section) ?

    On this universe page, community could vote for the most useful helpers, and we could slowly integrate them in the API when they get to a certain point? (pretty sure you've already thought about something like this or similar Helder)

    I'm ok with going to the withEnv solution ☑️

  15. helderco commented on May 9, 2023

    @helderco
    Contributor

    Just to summarize:

    • Doesn't seem worth it to add to the API;
    • Better suited for .with();

    Two improvements we can make:

    • Decide if we want to add it to the SDKs
      • Trade-off: more work for each SDK to maintain, possible source of drift in supported features.
    • Decide if it's worth it to rename env related fields to something shorter (with deprecation, like Exec → WithExec);
  16. mircubed commented on May 10, 2023

    @mircubed
    Contributor

    Next steps as suggested by @samalba - We should take user input on this since this will impact all users.

  17. samalba commented on May 10, 2023

    @samalba
    Contributor

    @mircubed flagged this issue to make sure we don't lose the momentum towards a resolution, and I agree.

    Seems like we have consensus on this one (from @vito @grouville @helderco)? @RonanQuigley, given you opened the issue, any opinion?

  18. grouville commented on May 15, 2023

    @grouville
    Member

    @mircubed flagged this issue to make sure we don't lose the momentum towards a resolution, and I agree.

    Seems like we have consensus on this one (from @vito @grouville @helderco)? @RonanQuigley, given you opened the issue, any opinion?

    Above PR (#5139) extends the docs, so that other users can learn about this with() pattern

  19. grouville commented on May 22, 2023

    @grouville
    Member

    @mircubed flagged this issue to make sure we don't lose the momentum towards a resolution, and I agree.

    Seems like we have consensus on this one (from @vito @grouville @helderco)? @RonanQuigley, given you opened the issue, any opinion?

    I think the PR #5139 closes this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions