Skip to content

Commit

Permalink
Merge branch 'main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
sean-m-sullivan authored Dec 6, 2024
2 parents c2d5493 + a02bac4 commit 3737e95
Show file tree
Hide file tree
Showing 7 changed files with 235 additions and 60 deletions.
5 changes: 1 addition & 4 deletions .github/workflows/tox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ jobs:
needs:
- check
environment: release
if: github.event_name == 'push' && github.ref_type == 'tag'
steps:
- uses: actions/checkout@v4

Expand All @@ -266,9 +267,6 @@ jobs:
- run: pip install ansible-core

- name: Publish the collection on Galaxy
if: |
github.event_name == 'push' &&
(github.ref_type == 'tag' || github.ref == 'refs/heads/main')
run: >
[[ "${{ secrets.ANSIBLE_GALAXY_API_KEY != '' }}" ]] || { echo
"ANSIBLE_GALAXY_API_KEY is required to publish on galaxy" ; exit 1; }
Expand All @@ -277,7 +275,6 @@ jobs:
secrets.ANSIBLE_GALAXY_API_KEY }}"
- name: Upload the artifact to the release
if: github.ref_type == 'tag'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
Expand Down
35 changes: 34 additions & 1 deletion extensions/eda/plugins/event_source/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
final payload which can be used to trigger a shutdown of
the rulebook, especially when we are using rulebooks to
forward messages to other running rulebooks.
check_env_vars dict Optionally check if all the defined env vars are set
before generating the events. If any of the env_var is missing
or the value doesn't match the source plugin will end
with an exception
"""
Expand All @@ -53,16 +57,35 @@
from __future__ import annotations

import asyncio
import os
import random
import time
from dataclasses import dataclass, fields
from datetime import datetime
from pathlib import Path
from typing import Any
from typing import Any, Dict, Optional

import yaml


class MissingEnvVarError(Exception):
"""Exception class for missing env var."""

def __init__(self: "MissingEnvVarError", env_var: str) -> None:
"""Class constructor with the missing env_var."""
super().__init__(f"Env Var {env_var} is required")


class EnvVarMismatchError(Exception):
"""Exception class for mismatch in the env var value."""

def __init__(
self: "EnvVarMismatchError", env_var: str, value: str, expected: str
) -> None:
"""Class constructor with mismatch in env_var value."""
super().__init__(f"Env Var {env_var} expected: {expected} passed in: {value}")


@dataclass
class Args:
"""Class to store all the passed in args."""
Expand All @@ -84,6 +107,7 @@ class ControlArgs:
loop_count: int = 1
repeat_count: int = 1
timestamp: bool = False
check_env_vars: Optional[Dict[str, str]] = None


@dataclass
Expand Down Expand Up @@ -135,6 +159,7 @@ async def __call__(self: Generic) -> None:
msg = "time_format must be one of local, iso8601, epoch"
raise ValueError(msg)

await self._check_env_vars()
await self._load_payload_from_file()

if not isinstance(self.my_args.payload, list):
Expand Down Expand Up @@ -174,6 +199,14 @@ async def _post_event(self: Generic, event: dict[str, Any], index: int) -> None:
print(data) # noqa: T201
await self.queue.put(data)

async def _check_env_vars(self: Generic) -> None:
if self.control_args.check_env_vars:
for key, value in self.control_args.check_env_vars.items():
if key not in os.environ:
raise MissingEnvVarError(key)
if os.environ[key] != value:
raise EnvVarMismatchError(key, os.environ[key], value)

async def _load_payload_from_file(self: Generic) -> None:
if not self.my_args.payload_file:
return
Expand Down
2 changes: 1 addition & 1 deletion plugins/module_utils/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def lookup_resource_id(
endpoint: str,
name: str,
params: Optional[dict[str, Any]] = None,
) -> Optional[Any]:
) -> Optional[int]:
result = None

try:
Expand Down
116 changes: 63 additions & 53 deletions plugins/modules/rulebook_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,14 @@
project_name:
description:
- The name of the project associated with the rulebook activation.
- Required when state is present.
type: str
aliases:
- project
rulebook_name:
description:
- The name of the rulebook associated with the rulebook activation.
- Required when state is present.
type: str
aliases:
- rulebook
Expand All @@ -58,6 +60,7 @@
decision_environment_name:
description:
- The name of the decision environment associated with the rulebook activation.
- Required when state is present.
type: str
aliases:
- decision_environment
Expand All @@ -70,7 +73,7 @@
- token
organization_name:
description:
- The name of the organization.
- The name of the organization. Required when state is present.
- This parameter is supported in AAP 2.5 and onwards.
If specified for AAP 2.4, value will be ignored.
type: str
Expand Down Expand Up @@ -316,58 +319,54 @@ def create_params(
) -> Dict[str, Any]:
activation_params: Dict[str, Any] = {}

# Get the project id
project_id = None
if module.params.get("project_name"):
project_id = lookup_resource_id(
module, controller, "projects", module.params["project_name"]
)
if project_id is not None:
activation_params["project_id"] = project_id
# Get the project id, only required to get the rulebook id
project_name = module.params["project_name"]
project_id = lookup_resource_id(module, controller, "projects", project_name)

if project_id is None:
module.fail_json(msg=f"Project {project_name} not found.")

# Get the rulebook id
rulebook_id = None
params = {}
if project_id is not None:
params = {"data": {"project_id": project_id}}
if module.params.get("rulebook_name"):
rulebook_id = lookup_resource_id(
module,
controller,
"rulebooks",
module.params["rulebook_name"],
params,
rulebook_name = module.params["rulebook_name"]
params = {"data": {"project_id": project_id}}
rulebook_id = lookup_resource_id(
module,
controller,
"rulebooks",
rulebook_name,
params,
)
if rulebook_id is None:
module.fail_json(
msg=f"Rulebook {rulebook_name} not found for project {project_name}."
)
if rulebook_id is not None:
activation_params["rulebook_id"] = rulebook_id

activation_params["rulebook_id"] = rulebook_id

# Get the decision environment id
decision_environment_id = None
if module.params.get("decision_environment_name"):
decision_environment_id = lookup_resource_id(
module,
controller,
"decision-environments",
module.params["decision_environment_name"],
decision_environment_name = module.params["decision_environment_name"]
decision_environment_id = lookup_resource_id(
module,
controller,
"decision-environments",
decision_environment_name,
)
if decision_environment_id is None:
module.fail_json(
msg=f"Decision Environment {decision_environment_name} not found."
)
if decision_environment_id is not None:
activation_params["decision_environment_id"] = decision_environment_id
activation_params["decision_environment_id"] = decision_environment_id

# Get the organization id
organization_id = None
if not is_aap_24 and module.params.get("organization_name"):
organization_name = module.params["organization_name"]
if not is_aap_24:
organization_id = lookup_resource_id(
module, controller, "organizations", module.params["organization_name"]
module, controller, "organizations", organization_name
)
if organization_id is not None:
if organization_id is None:
module.fail_json(msg=f"Organization {organization_name} not found.")
activation_params["organization_id"] = organization_id

if module.params.get("description"):
activation_params["description"] = module.params["description"]

if module.params.get("extra_vars"):
activation_params["extra_var"] = module.params["extra_vars"]

# Get the AWX token id
awx_token_id = None
if module.params.get("awx_token_name"):
Expand All @@ -377,12 +376,6 @@ def create_params(
if awx_token_id is not None:
activation_params["awx_token_id"] = awx_token_id

if module.params.get("restart_policy"):
activation_params["restart_policy"] = module.params["restart_policy"]

if module.params.get("enabled"):
activation_params["is_enabled"] = module.params["enabled"]

# Get the eda credential ids
eda_credential_ids = None
if not is_aap_24 and module.params.get("eda_credentials"):
Expand All @@ -402,12 +395,26 @@ def create_params(
# Process event streams and source mappings
activation_params["source_mappings"] = yaml.dump(
process_event_streams(
rulebook_id=rulebook_id,
# ignore type error, if rulebook_id is None, it will fail earlier
rulebook_id=rulebook_id, # type: ignore[arg-type]
controller=controller,
module=module,
)
)

# Set the remaining parameters
if module.params.get("description"):
activation_params["description"] = module.params["description"]

if module.params.get("extra_vars"):
activation_params["extra_var"] = module.params["extra_vars"]

if module.params.get("restart_policy"):
activation_params["restart_policy"] = module.params["restart_policy"]

if module.params.get("enabled"):
activation_params["is_enabled"] = module.params["enabled"]

if not is_aap_24 and module.params.get("log_level"):
activation_params["log_level"] = module.params["log_level"]

Expand Down Expand Up @@ -492,9 +499,13 @@ def main() -> None:
organization_name = module.params.get("organization_name")
if state == "present" and not is_aap_24 and organization_name is None:
module.fail_json(
msg="Parameter organization_name is required when state is present."
msg=(
"Parameter organization_name is required when state "
"is present for this version of EDA."
),
)
# Attempt to find rulebook activation based on the provided name
activation = {}
try:
activation = controller.get_exactly_one("activations", name=name)
except EDAError as e:
Expand All @@ -511,14 +522,13 @@ def main() -> None:
module.exit_json(
msg=f"A rulebook activation with name: {name} already exists. "
"The module does not support modifying a rulebook activation.",
**{"changed": False, "id": activation["id"]},
changed=False,
id=activation["id"],
)

# Activation Data that will be sent for create/update
activation_params = create_params(module, controller, is_aap_24=is_aap_24)
activation_params["name"] = (
controller.get_item_name(activation) if activation else name
)
activation_params["name"] = name

# If the state was present and we can let the module build or update the
# existing activation, this will return on its own
Expand Down
Loading

0 comments on commit 3737e95

Please sign in to comment.