|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +from http import HTTPStatus |
| 4 | + |
| 5 | +import requests |
| 6 | +from ansible.module_utils.basic import AnsibleModule |
| 7 | + |
| 8 | +from ..module_utils.payload import sanitize_payload |
| 9 | +from ..module_utils.flagsmith import get_project_ids_from_names, get_tag_ids_from_labels |
| 10 | + |
| 11 | +import collections |
| 12 | + |
| 13 | +import ast |
| 14 | + |
| 15 | +import json |
| 16 | + |
| 17 | +TAG_FIELDS = { |
| 18 | + "api_key": {"required": True, "type": "str", "no_log": True}, |
| 19 | + "base_url": {"required": True, "type": "str"}, |
| 20 | + "state": {"required": True, "choices": ["present", "absent"], "type": "str"}, |
| 21 | + "project_name": {"required": True, "type": "str"}, |
| 22 | + "name": {"required": True, "type": "str"}, |
| 23 | + "type": {"required": False, "type": "str"}, |
| 24 | + "default_enabled": {"required": False, "type": "bool"}, |
| 25 | + "initial_value": {"required": False, "type": "str"}, |
| 26 | + "description": {"required": False, "type": "str"}, |
| 27 | + "is_archived": {"required": False, "type": "bool"}, |
| 28 | + "tags": {"required": False, "type": "list", "elements": "str"}, |
| 29 | +} |
| 30 | + |
| 31 | +class FlagsmithFeature: |
| 32 | + def __init__(self, module): |
| 33 | + self.module = module |
| 34 | + self.payload = module.params |
| 35 | + self.api_key = self.payload.pop("api_key") |
| 36 | + self.base_url = self.payload.pop("base_url") |
| 37 | + self.project_name = self.payload.pop("project_name") |
| 38 | + self.state = self.payload.pop("state") |
| 39 | + self.headers = {"Authorization": f"Token {self.api_key}", "Accept": "application/json"} |
| 40 | + self.id = None |
| 41 | + self.project_id = None |
| 42 | + self.retrieved_attributes = None |
| 43 | + |
| 44 | + self.payload = sanitize_payload(self.payload) |
| 45 | + |
| 46 | + if 'initial_value' in self.payload: |
| 47 | + # Transform to a valid json string if initial_value is a dict |
| 48 | + try: |
| 49 | + typed_initial_value = ast.literal_eval(self.payload['initial_value']) |
| 50 | + if type(typed_initial_value) is dict: |
| 51 | + self.payload['initial_value'] = json.dumps(typed_initial_value) |
| 52 | + except ValueError: |
| 53 | + pass |
| 54 | + |
| 55 | + def retrieve_id(self, api_url): |
| 56 | + """ Retrieve the id of a feature if it exists """ |
| 57 | + response = requests.get(api_url, headers=self.headers) |
| 58 | + json_object = response.json() |
| 59 | + |
| 60 | + for item in json_object["results"]: |
| 61 | + if item["name"] == self.payload["name"]: |
| 62 | + self.id = item["id"] |
| 63 | + self.retrieved_attributes = { |
| 64 | + "name": item["name"], |
| 65 | + "type": item["type"], |
| 66 | + "default_enabled": item["default_enabled"], |
| 67 | + "initial_value": item["initial_value"], |
| 68 | + "description": item["description"], |
| 69 | + "is_archived": item["is_archived"], |
| 70 | + "tags": item["tags"] |
| 71 | + } |
| 72 | + return |
| 73 | + |
| 74 | + if json_object["next"] is not None: |
| 75 | + self.retrieve_id(json_object["next"]) |
| 76 | + |
| 77 | + def diff_attributes(self): |
| 78 | + """ Update the payload to only have the diff between the wanted and the existing attributes """ |
| 79 | + diff_attributes = {} |
| 80 | + for key in self.payload: |
| 81 | + if key == "tags": |
| 82 | + if collections.Counter(self.retrieved_attributes[key]) != collections.Counter(self.payload[key]): |
| 83 | + # tags is a special case since we are comparing two unordered lists |
| 84 | + diff_attributes[key] = self.payload[key] |
| 85 | + elif key not in self.retrieved_attributes or self.retrieved_attributes[key] != self.payload[key]: |
| 86 | + diff_attributes[key] = self.payload[key] |
| 87 | + |
| 88 | + self.payload = diff_attributes |
| 89 | + |
| 90 | + def create(self): |
| 91 | + """ Create a new feature """ |
| 92 | + if 'tags' in self.payload: |
| 93 | + self.payload['tags'] = get_tag_ids_from_labels(f"{self.base_url}/projects/{self.project_id}/tags/", self.headers, self.project_id, self.payload['tags']) |
| 94 | + |
| 95 | + resp = requests.post(f"{self.base_url}/projects/{self.project_id}/features/", headers=self.headers, json=self.payload) |
| 96 | + if resp.status_code == HTTPStatus.CREATED: |
| 97 | + self.module.exit_json(changed=True) |
| 98 | + else: |
| 99 | + self.module.fail_json(msg=resp.content) |
| 100 | + |
| 101 | + def update(self): |
| 102 | + """ Update an existing feature """ |
| 103 | + if 'tags' in self.payload: |
| 104 | + self.payload['tags'] = get_tag_ids_from_labels(f"{self.base_url}/projects/{self.project_id}/tags/", self.headers, self.project_id, self.payload['tags']) |
| 105 | + |
| 106 | + self.diff_attributes() |
| 107 | + if not self.payload: |
| 108 | + self.module.exit_json(changed=False) |
| 109 | + |
| 110 | + resp = requests.patch(f"{self.base_url}/projects/{self.project_id}/features/{self.id}/", headers=self.headers, json=self.payload) |
| 111 | + |
| 112 | + if resp.status_code == HTTPStatus.OK: |
| 113 | + self.module.exit_json(changed=True) |
| 114 | + else: |
| 115 | + self.module.fail_json(msg=resp.content) |
| 116 | + |
| 117 | + def delete(self): |
| 118 | + """ Delete an existing feature """ |
| 119 | + resp = requests.delete(f"{self.base_url}/projects/{self.project_id}/features/{self.id}/", headers=self.headers) |
| 120 | + if resp.status_code == HTTPStatus.NO_CONTENT: |
| 121 | + self.module.exit_json(changed=True) |
| 122 | + else: |
| 123 | + self.module.fail_json(msg=resp.content) |
| 124 | + |
| 125 | + def manage(self): |
| 126 | + """ Manage state of a feature """ |
| 127 | + project_ids = get_project_ids_from_names(self.base_url, self.headers, [self.project_name]) |
| 128 | + if len(project_ids) == 0: |
| 129 | + self.module.fail_json(msg="Project was not found") |
| 130 | + else: |
| 131 | + self.project_id = project_ids[0] |
| 132 | + |
| 133 | + self.retrieve_id(f"{self.base_url}/projects/{self.project_id}/features?search={self.payload['name']}") |
| 134 | + |
| 135 | + if self.state == "present": |
| 136 | + if not self.id: |
| 137 | + self.create() |
| 138 | + else: |
| 139 | + self.update() |
| 140 | + elif self.state == "absent": |
| 141 | + if not self.id: |
| 142 | + self.module.exit_json(changed=False, msg="No feature to delete") |
| 143 | + else: |
| 144 | + self.delete() |
| 145 | + |
| 146 | + |
| 147 | +def main(): |
| 148 | + module = AnsibleModule( |
| 149 | + argument_spec=TAG_FIELDS, |
| 150 | + supports_check_mode=True, |
| 151 | + ) |
| 152 | + |
| 153 | + feature_object = FlagsmithFeature(module) |
| 154 | + |
| 155 | + if not module.check_mode: |
| 156 | + feature_object.manage() |
| 157 | + else: |
| 158 | + return module.exit_json(changed=False) |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + main() |
0 commit comments