Setting the file. One moment.
Env Setup Template · Agent Observability Experiment Bootstrap · datadog-labs/agent-skills · Skills Docs
ContentsBack to the top of the page (opens in a new tab)
references/python/ env_setup_template.py
Python · 91 lines · 3 KB
15 # before running this file — the loader never overwrites a value already in
16 # os.environ.
17
18 import os
19 import pathlib
20
21
22 def _load_env_files (extra: list[ str ] | None = None ) -> list[ str ]:
23 here = pathlib.Path( __file__ ).resolve().parent
24 cwd = pathlib.Path.cwd().resolve()
25 candidates: list[pathlib.Path] = []
26 for p in extra or []:
27 candidates.append(pathlib.Path(p).expanduser())
28 candidates += [
29 here / ".env" ,
30 here / ".env.local" ,
31 cwd / ".env" ,
32 cwd / ".env.local" ,
33 ]
34 p = cwd
35 while p != p.parent and p != pathlib.Path.home().parent:
36 candidates.append(p / ".env" )
37 p = p.parent
38 candidates.append(pathlib.Path.home() / ".datadog" / "credentials" )
39
40 loaded: list[ str ] = []
41 seen: set[pathlib.Path] = set ()
42 for path in candidates:
43 try :
44 path = path.resolve()
45 except Exception :
46 continue
47 if path in seen or not path.is_file():
48 continue
49 seen.add(path)
50 try :
51 text = path.read_text()
52 except Exception :
53 continue
54 for line in text.splitlines():
55 line = line.strip()
56 if not line or line.startswith( "#" ) or "=" not in line:
57 continue
58 if line.startswith( "export " ):
59 line = line[ len ( "export " ):]
60 k, _, v = line.partition( "=" )
61 k = k.strip()
62 v = v.strip().strip( '"' ).strip( "'" )
63 if k and k not in os.environ:
64 os.environ[k] = v
65 loaded.append( str (path))
66 return loaded
67
68
69 # Baked in at generation time from --env-file (always tried first). Edit this
70 # list to point at a different .env without regenerating the file.
71 ENV_FILE_OVERRIDE : list[ str ] = {{ ENV_FILE_OVERRIDE_LIST }}
72
73 _loaded_env_paths = _load_env_files( ENV_FILE_OVERRIDE )
74 if _loaded_env_paths:
75 print ( f "Loaded credentials from: { ', ' .join(_loaded_env_paths) } " )
76
77 # ─── Required key assertions ─────────────────────────────────────────────────
78 # Datadog keys are always required. Provider-key assertions are emitted
79 # conditionally by the skill (see Workflow step 2.6 — only the keys the wired
80 # task_fn actually calls).
81
82 assert os.getenv( "DD_API_KEY" ), (
83 "DD_API_KEY is not set. Export it in your shell or add it to a discovered "
84 ".env file (this file checked: cwd, app dir, parent dirs, "
85 "~/.datadog/credentials)."
86 )
87 assert os.getenv( "DD_APPLICATION_KEY" ) or os.getenv( "DD_APP_KEY" ), (
88 "DD_APPLICATION_KEY (or its alias DD_APP_KEY) is not set. Same fallback "
89 "paths as above."
90 )
91 {{ PROVIDER_ASSERTS }}