Skip to content

Commit

Permalink
Issue/582 reference (#583)
Browse files Browse the repository at this point in the history
* Added create_environment_reference plugin
  • Loading branch information
wouterdb authored Feb 25, 2025
1 parent 817a5d6 commit 446e95e
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## v8.3.0 - ?

- Added create_environment_reference plugin to create reference to environment variables
- Added the 'value' attribute to std::testing::NullResource
- Log warning when environment variable is not found by get_env plugin
- Deprecate get_env_int plugin in favor of int(get_env())

Expand Down
4 changes: 3 additions & 1 deletion model/testing.cf
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,17 @@ entity NullResource extends ManagedResource, PurgeableResource:
A resource that does nothing, for use in tests and examples

:attr name: the name of this resource
:attr value: a value this resource can cary, has no purpose
:attr agentname: the name of the agent to deploy this resource on
:attr fail: when true, this resource will always fail on both dryrun and deploy
"""
string name = "null"
string agentname = "internal"
string value = ""
bool send_event = true
bool fail = false
end

index NullResource(agentname, name)

implement NullResource using std::none
implement NullResource using std::none
38 changes: 38 additions & 0 deletions plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
# don't bind to `resources` because this package has a submodule named resources that will bind to `resources` when imported
import inmanta.resources
from inmanta import util
from inmanta.agent.handler import LoggerABC
from inmanta.ast import NotFoundException, OptionalValueException, RuntimeException
from inmanta.config import Config
from inmanta.execute.proxy import DynamicProxy, UnknownException
Expand Down Expand Up @@ -1313,3 +1314,40 @@ def json_dumps(obj: "any") -> "string":
:param obj: The inmanta object that should be serialized as json.
"""
return json.dumps(obj, default=util.internal_json_encoder)


try:
from inmanta.references import Reference, reference

@reference("std::Environment")
class EnvironmentReference(Reference[str]):
"""A reference to fetch environment variables"""

def __init__(self, name: str | Reference[str]) -> None:
"""
:param name: The name of the environment variable.
"""
super().__init__()
self.name = name

def resolve(self, logger: LoggerABC) -> str:
"""Resolve the reference"""
env_var_name = self.resolve_other(self.name, logger)
logger.debug("Resolving environment variable %(name)s", name=self.name)
value = os.getenv(env_var_name)
if value is None:
raise LookupError(f"Environment variable {env_var_name} is not set")
return value

@plugin
def create_environment_reference(name: str | Reference[str]) -> Reference[str]:
"""Create an environment reference
:param name: The name of the variable to fetch from the environment
:return: A reference to what can be resolved to a string
"""
return EnvironmentReference(name=name)

except ImportError:
# Reference are not yet supported by this core version
pass
3 changes: 2 additions & 1 deletion plugins/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

@resource("std::testing::NullResource", agent="agentname", id_attribute="name")
class Null(ManagedResource, PurgeableResource):
fields = ("name", "agentname", "fail")
fields = ("name", "agentname", "fail", "value")


@resource("std::AgentConfig", agent="agent", id_attribute="agentname")
Expand Down Expand Up @@ -61,6 +61,7 @@ class NullProvider(CRUDHandler):
def read_resource(self, ctx: HandlerContext, resource: PurgeableResource) -> None:
if resource.fail:
raise Exception("This resource is set to fail")
ctx.debug("Observed value: %(value)s", value=resource.value)
return

def create_resource(self, ctx: HandlerContext, resource: PurgeableResource) -> None:
Expand Down
54 changes: 54 additions & 0 deletions tests/test_reference.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""
Copyright 2025 Inmanta
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contact: [email protected]
"""

from pytest_inmanta.plugin import Project

from inmanta import const


def test_references_resource(project: Project, monkeypatch) -> None:

project.compile(
"""
import std::testing
metavalue = std::create_environment_reference("METATESTENV")
value = std::create_environment_reference(metavalue)
std::testing::NullResource(agentname="test", name="aaa", value=value)
"""
)

project.deploy_resource_v2(
"std::testing::NullResource",
name="aaa",
expected_status=const.ResourceState.failed,
)

monkeypatch.setenv("METATESTENV", "TESTENV")
monkeypatch.setenv("TESTENV", "testvalue")

project.compile(
"""
import std::testing
metavalue = std::create_environment_reference("METATESTENV")
value = std::create_environment_reference(metavalue)
std::testing::NullResource(agentname="test", name="aaa", value=value)
"""
)

result = project.deploy_resource_v2("std::testing::NullResource", name="aaa")
assert result.assert_has_logline("Observed value: testvalue")

0 comments on commit 446e95e

Please sign in to comment.