Skip to content

Commit

Permalink
Support multiple destinations in host_copy. (#259)
Browse files Browse the repository at this point in the history
* Support multiple destinations in host_copy.

  - Also reduces output noise.
  - Also handles the situation where a destination already has the role in question.
  - Requires Role to be hashable.
  • Loading branch information
terjekv authored Jun 6, 2024
1 parent 02681f0 commit 5dabdac
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
4 changes: 4 additions & 0 deletions mreg_cli/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,10 @@ class Role(HostPolicy, WithHistory):

history_resource: ClassVar[HistoryResource] = HistoryResource.HostPolicy_Role

def __hash__(self) -> int:
"""Hash the role by ID and name."""
return hash(str(self.id) + self.name)

@classmethod
def endpoint(cls) -> Endpoint:
"""Return the endpoint for the class."""
Expand Down
24 changes: 15 additions & 9 deletions mreg_cli/commands/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ def host_add(args: argparse.Namespace) -> None:
short_desc="Copy roles between hosts",
flags=[
Flag("source", description="Source host", metavar="SOURCE"),
Flag("destination", description="Destination host", metavar="DESTINATION"),
Flag("destination", description="Destination host", nargs="+", metavar="DESTINATION"),
],
)
def host_copy(args: argparse.Namespace) -> None:
Expand All @@ -326,16 +326,22 @@ def host_copy(args: argparse.Namespace) -> None:
:param args: argparse.Namespace (source, destination)
"""
source_name: str = args.source
destination_name: str = args.destination

source = Host.get_by_any_means_or_raise(source_name)
destination = Host.get_by_any_means_or_raise(destination_name)
source_roles = set(source.roles())

for role in source.roles():
role.add_host(destination.name.hostname)
OutputManager().add_line(
f"Copied role {role.name} from {source_name} to {destination_name}"
)
for destination_name in args.destination:
destination = Host.get_by_any_means_or_raise(destination_name)
destination_roles = set(destination.roles())
OutputManager().add_line(f"Copying roles from from {source_name} to {destination_name}")

# Check if role already exists in destination
for role in source_roles & destination_roles:
OutputManager().add_line(f" + {role.name} (existing membership)")

# Check what roles need to be added
for role in source_roles - destination_roles:
role.add_host(destination.name.hostname)
OutputManager().add_line(f" + {role.name}")


@command_registry.register_command(
Expand Down

0 comments on commit 5dabdac

Please sign in to comment.