Skip to content

Commit e20d2f0

Browse files
Refactor: Fixes on AVDVaultHandler (#6509)
1 parent 50c5bed commit e20d2f0

3 files changed

Lines changed: 35 additions & 42 deletions

File tree

ansible_collections/arista/avd/plugins/action/validate_inputs.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -174,15 +174,15 @@ def main(self, task_vars: dict[str, Any]) -> None:
174174
mp_workers, mt_workers = get_workers(len(hosts_to_process), task_vars["ansible_forks"])
175175
templated_path, validated_path = get_role_tmp_paths(role_name=SCHEMA_MAP[plugin_args.schema_name], tmp_dir=plugin_args.tmp_dir, clean=True)
176176

177-
# Create vault and file handlers.
177+
# Create Vault and file handlers.
178178
vault_handler = AVDVaultHandler(self._loader, vault_id=plugin_args.vault_id)
179179
file_handler = AVDFileHandler(vault_handler)
180180

181-
# Check if vault is configured for encrypting temporary files.
182-
if vault_handler.has_vault:
183-
self.logger.info("Ansible Vault is configured - temporary files will be encrypted")
181+
# Check if Vault secrets are configured for encrypting temporary files.
182+
if vault_handler.has_vault_secrets:
183+
self.logger.info("Ansible Vault secrets are configured - temporary files will be encrypted")
184184
else:
185-
self.logger.info("Ansible Vault is not configured - temporary files will not be encrypted")
185+
self.logger.info("Ansible Vault secrets are not configured - temporary files will not be encrypted")
186186

187187
# Track worker failures globally for the task.
188188
self.crashed_hosts = set()
@@ -521,7 +521,7 @@ def _validate_host_worker(
521521
if not input_file_path.exists():
522522
return WorkerFailure(hostname=hostname, error=f"Missing input data file: {input_file_path}")
523523

524-
# Load file content (decrypted if vaulted).
524+
# Load file content (decrypted if Vault encrypted).
525525
file_content = file_handler.read_file(input_file_path)
526526

527527
if input_suffix in {"yml", "yaml"}:

ansible_collections/arista/avd/plugins/plugin_utils/utils/avd_file_handler.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Copyright (c) 2026 Arista Networks, Inc.
22
# Use of this source code is governed by the Apache License 2.0
33
# that can be found in the LICENSE file.
4-
"""File handler with automatic vault support for AVD plugins."""
4+
"""File handler with automatic Ansible Vault support for AVD plugins."""
55

66
from __future__ import annotations
77

@@ -14,7 +14,7 @@
1414

1515

1616
class AVDFileHandler:
17-
"""Handles file operations with automatic vault support."""
17+
"""Handles file operations with automatic Ansible Vault support."""
1818

1919
_vault_handler: AVDVaultHandler
2020

@@ -23,30 +23,30 @@ def __init__(self, vault_handler: AVDVaultHandler) -> None:
2323
Initialize the file handler.
2424
2525
Args:
26-
vault_handler: The AVDVaultHandler instance to use for vault operations.
26+
vault_handler: The AVDVaultHandler instance to use for Vault operations.
2727
"""
2828
self._vault_handler = vault_handler
2929

3030
def read_file(self, file_path: Path | str) -> bytes:
3131
"""
32-
Read a file with automatic vault decryption, returning raw bytes.
32+
Read a file with automatic Vault decryption, returning raw bytes.
3333
34-
This method reads a file and automatically decrypts it if it is vault encrypted.
34+
This method reads a file and automatically decrypts it if it is Vault encrypted.
3535
3636
Args:
3737
file_path: Path to the file to read.
3838
3939
Returns:
40-
Raw file content as bytes (decrypted if vaulted).
40+
Raw file content as bytes (decrypted if Vault encrypted).
4141
"""
4242
file_content = Path(file_path).read_bytes()
4343
return self._vault_handler.decrypt_if_needed(file_content)
4444

4545
def write_file(self, file_path: Path | str, data: bytes) -> None:
4646
"""
47-
Write bytes to a file with automatic vault encryption.
47+
Write bytes to a file with automatic Vault encryption.
4848
49-
This method encrypts the data if vault is configured, then writes to the file.
49+
This method encrypts the data if Vault secrets are configured, then writes to the file.
5050
5151
Args:
5252
file_path: Path to the file to write.
@@ -57,7 +57,7 @@ def write_file(self, file_path: Path | str, data: bytes) -> None:
5757

5858
def load_json(self, file_path: Path | str) -> Any:
5959
"""
60-
Load and parse a JSON file with automatic vault decryption.
60+
Load and parse a JSON file with automatic Vault decryption.
6161
6262
Args:
6363
file_path: Path to the JSON file to load.

ansible_collections/arista/avd/plugins/plugin_utils/utils/avd_vault_handler.py

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,71 +11,64 @@
1111

1212
if TYPE_CHECKING:
1313
from ansible.parsing.dataloader import DataLoader
14-
from ansible.parsing.vault import VaultSecret
1514

1615

1716
class AVDVaultHandler:
1817
"""Handles Ansible Vault encryption and decryption operations."""
1918

20-
_loader: DataLoader
21-
_encrypt_vault_id: str | None
22-
_encrypt_secret: VaultSecret | None
19+
__slots__ = ("__encrypt_secret", "__encrypt_vault_id", "__loader")
2320

2421
def __init__(self, loader: DataLoader, vault_id: str | None = None) -> None:
2522
"""
26-
Initialize the vault handler.
23+
Initialize the Vault handler.
2724
2825
Args:
2926
loader: The Ansible DataLoader instance.
30-
vault_id: Optional vault ID to use for encryption. If None, uses the first vault ID in the list (default Ansible behavior).
27+
vault_id: Optional Vault ID to use for encryption. If None, uses the first Vault ID in the list (default Ansible behavior).
3128
"""
32-
self._loader = loader
29+
self.__loader = loader
3330

34-
# Pre-compute encryption secret if vault is configured
31+
# Pre-compute encryption credentials if Vault secrets are configured.
3532
if loader._vault.secrets:
36-
self._encrypt_vault_id, self._encrypt_secret = match_encrypt_secret(loader._vault.secrets, vault_id)
33+
self.__encrypt_vault_id, self.__encrypt_secret = match_encrypt_secret(loader._vault.secrets, vault_id)
3734
else:
38-
self._encrypt_vault_id = None
39-
self._encrypt_secret = None
35+
self.__encrypt_vault_id = None
36+
self.__encrypt_secret = None
4037

4138
@property
42-
def has_vault(self) -> bool:
43-
"""Whether vault secrets are configured."""
44-
return bool(self._loader._vault.secrets)
39+
def has_vault_secrets(self) -> bool:
40+
"""Whether Vault secrets are configured."""
41+
return self.__encrypt_secret is not None
4542

4643
def encrypt_if_needed(self, data: bytes) -> bytes:
4744
"""
48-
Encrypt data if vault secrets are configured.
45+
Encrypt data if needed.
4946
5047
Args:
5148
data: Data to potentially encrypt.
5249
5350
Returns:
54-
Encrypted data if vault is configured, otherwise the original data.
55-
51+
Encrypted data if Vault secrets are configured, otherwise the original data.
5652
"""
57-
if not self.has_vault:
53+
if not self.has_vault_secrets:
5854
return data
5955

60-
return self._loader._vault.encrypt(data, secret=self._encrypt_secret, vault_id=self._encrypt_vault_id)
56+
return self.__loader._vault.encrypt(data, secret=self.__encrypt_secret, vault_id=self.__encrypt_vault_id)
6157

6258
def decrypt_if_needed(self, data: bytes) -> bytes:
6359
"""
64-
Decrypt data if it is vault encrypted.
60+
Decrypt data if needed.
6561
6662
Args:
6763
data: Data to potentially decrypt.
6864
6965
Returns:
70-
Decrypted data if it was vault encrypted, otherwise the original data.
66+
Decrypted data if Vault secrets are configured and data is encrypted, otherwise the original data.
7167
7268
Raises:
73-
AnsibleVaultError: If vault decryption fails.
69+
AnsibleVaultError: If Vault decryption fails.
7470
"""
75-
if self.has_vault and self._loader._vault.is_encrypted(data):
76-
# Vault is configured and data is encrypted, decrypt it
77-
decrypted_data, _vault_id, _vault_secret = self._loader._vault.decrypt_and_get_vault_id(data)
78-
return decrypted_data
71+
if self.has_vault_secrets and self.__loader._vault.is_encrypted(data):
72+
return self.__loader._vault.decrypt(data)
7973

80-
# Data is not vaulted or no vault configured - return data as-is
8174
return data

0 commit comments

Comments
 (0)