Wrapper around reading, validating, and updating the terraform.tfvars config file.
| 55 | |
| 56 | |
| 57 | class BinaryAlertConfig: |
| 58 | """Wrapper around reading, validating, and updating the terraform.tfvars config file.""" |
| 59 | # Expected configuration value formats. |
| 60 | VALID_AWS_ACCOUNT_ID_FORMAT = r'\d{12}' |
| 61 | VALID_AWS_REGION_FORMAT = r'[a-z]{2}-[a-z]{2,15}-\d' |
| 62 | VALID_NAME_PREFIX_FORMAT = r'[a-z][a-z0-9_]{3,50}' |
| 63 | VALID_CB_API_TOKEN_FORMAT = r'[a-f0-9]{40}' # CarbonBlack API token. |
| 64 | VALID_CB_ENCRYPTED_TOKEN_FORMAT = r'\S{50,500}' |
| 65 | VALID_CB_URL_FORMAT = r'https?://\S+' |
| 66 | |
| 67 | def __init__(self) -> None: |
| 68 | """Parse the terraform.tfvars config file and make sure it contains every variable. |
| 69 | |
| 70 | Raises: |
| 71 | InvalidConfigError: If any variable is defined in variables.tf but not terraform.tfvars. |
| 72 | """ |
| 73 | with open(CONFIG_FILE) as f: |
| 74 | self._config = hcl.load(f) # Dict[str, Union[int, str]] |
| 75 | |
| 76 | with open(VARIABLES_FILE) as f: |
| 77 | variable_names = hcl.load(f)['variable'].keys() |
| 78 | |
| 79 | for variable in variable_names: |
| 80 | # Verify that the variable is defined. |
| 81 | if variable not in self._config: |
| 82 | raise InvalidConfigError( |
| 83 | 'variable "{}" is not defined in {}'.format(variable, CONFIG_FILE) |
| 84 | ) |
| 85 | |
| 86 | @property |
| 87 | def aws_account_id(self) -> str: |
| 88 | return self._config['aws_account_id'] |
| 89 | |
| 90 | @aws_account_id.setter |
| 91 | def aws_account_id(self, value: str) -> None: |
| 92 | if not re.fullmatch(self.VALID_AWS_ACCOUNT_ID_FORMAT, value, re.ASCII): |
| 93 | raise InvalidConfigError( |
| 94 | 'aws_account_id "{}" does not match format {}'.format( |
| 95 | value, self.VALID_AWS_ACCOUNT_ID_FORMAT) |
| 96 | ) |
| 97 | self._config['aws_account_id'] = value |
| 98 | |
| 99 | @property |
| 100 | def aws_region(self) -> str: |
| 101 | return self._config['aws_region'] |
| 102 | |
| 103 | @aws_region.setter |
| 104 | def aws_region(self, value: str) -> None: |
| 105 | if not re.fullmatch(self.VALID_AWS_REGION_FORMAT, value, re.ASCII): |
| 106 | raise InvalidConfigError( |
| 107 | 'aws_region "{}" does not match format {}'.format( |
| 108 | value, self.VALID_AWS_REGION_FORMAT) |
| 109 | ) |
| 110 | self._config['aws_region'] = value |
| 111 | |
| 112 | @property |
| 113 | def name_prefix(self) -> str: |
| 114 | return self._config['name_prefix'] |
no outgoing calls