/idem_aws/states/aws/organizations/policy_attachment.py

https://gitlab.com/pgeorgiev_vmw/idem-aws
Python | 266 lines | 225 code | 12 blank | 29 comment | 2 complexity | 255a568701efec3f45de647fe8892139 MD5 | raw file
  1. """
  2. Autogenerated using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__
  3. hub.exec.boto3.client.organizations.attach_policy
  4. hub.exec.boto3.client.organizations.create_policy
  5. hub.exec.boto3.client.organizations.delete_policy
  6. hub.exec.boto3.client.organizations.describe_policy
  7. hub.exec.boto3.client.organizations.detach_policy
  8. hub.exec.boto3.client.organizations.list_policies
  9. hub.exec.boto3.client.organizations.update_policy
  10. """
  11. import copy
  12. from typing import Any
  13. from typing import Dict
  14. __contracts__ = ["resource"]
  15. TREQ = {
  16. "present": {
  17. "require": [
  18. "aws.organizations.organization.present",
  19. "aws.organizations.organization_unit.present",
  20. "aws.organizations.account.present",
  21. "aws.organizations.policy.present",
  22. ],
  23. },
  24. }
  25. async def present(
  26. hub, ctx, name: str, policy_id: str, target_id: str
  27. ) -> Dict[str, Any]:
  28. r"""
  29. **Autogenerated function**
  30. Attaches a policy to a root, an organizational unit (OU), or an individual account.
  31. How the policy affects accounts depends on the type of policy. Supported policy type is :
  32. SERVICE_CONTROL_POLICY
  33. Args:
  34. name(Text): An ID to identify the resource.
  35. policy_id(str): The unique identifier (ID) of the policy that you want to attach to the target.
  36. You can get the ID for the policy by calling the ListPolicies operation.
  37. target_id(str): The unique identifier (ID) of the root, OU, or account that you want to attach the policy to.
  38. Request Syntax:
  39. [policy_id-target_id]:
  40. aws.organizations.policy_attachment.present:
  41. - policy_id: 'string'
  42. - target_id: 'string'
  43. Returns:
  44. Dict[str, Any]
  45. Examples:
  46. .. code-block:: sls
  47. p-id-ou-bitz-1223:
  48. aws.organizations.policy_attachment.present:
  49. - policy_id: p-id
  50. - target_id: ou-bitz-1223
  51. """
  52. result = dict(comment="", name=name, result=True, old_state=None, new_state=None)
  53. try:
  54. before_ret = await hub.exec.aws.organizations.policy_attachment.is_target_policy_attached(
  55. ctx, policy_id=policy_id, target_id=target_id
  56. )
  57. except hub.tool.boto3.exception.ClientError as e:
  58. result["comment"] = f"{e.__class__.__name__}: {e}"
  59. result["result"] = False
  60. return result
  61. # If before_ret has False result and has an error message in comment, then immediately return with the error.
  62. if before_ret["result"] is False and before_ret["comment"]:
  63. result["result"] = False
  64. result["comment"] = before_ret["comment"]
  65. return result
  66. if ctx.get("test", False):
  67. if before_ret["result"]:
  68. result[
  69. "comment"
  70. ] = f"aws.organizations.policy_attachment {name} already exists"
  71. else:
  72. result[
  73. "comment"
  74. ] = f"Would attach aws.organizations.policy_attachment {name}"
  75. return result
  76. if before_ret["result"]:
  77. result["old_state"] = before_ret["ret"]
  78. result["new_state"] = copy.deepcopy(before_ret["ret"])
  79. result["comment"] = f"'{name}' already exists"
  80. else:
  81. try:
  82. ret = await hub.exec.boto3.client.organizations.attach_policy(
  83. ctx,
  84. PolicyId=policy_id,
  85. TargetId=target_id,
  86. )
  87. result["result"] = ret["result"]
  88. if not result["result"]:
  89. result["comment"] = ret["comment"]
  90. return result
  91. result["comment"] = f"Attached '{name}'"
  92. result["new_state"] = {"PolicyId": policy_id}
  93. except hub.tool.boto3.exception.ClientError as e:
  94. result["comment"] = f"{e.__class__.__name__}: {e}"
  95. result["result"] = False
  96. return result
  97. async def absent(hub, ctx, name: str, policy_id: str, target_id: str) -> Dict[str, Any]:
  98. r"""
  99. **Autogenerated function**
  100. Detaches a policy from a target root, organizational unit (OU), or account.
  101. Every root, OU, and account must have at least one SCP attached. If you want
  102. to replace the default FullAWSAccess policy with an SCP that limits the
  103. permissions that can be delegated, you must attach the replacement SCP
  104. before you can remove the default SCP. This is the authorization strategy
  105. of an "allow list ". If you instead attach a second SCP and leave the FullAWSAccess
  106. SCP still attached, and specify "Effect": "Deny" in the second SCP to override
  107. the "Effect": "Allow" in the FullAWSAccess policy (or any other attached SCP),
  108. you're using the authorization strategy of a "deny list ".
  109. Args:
  110. name(Text): An ID to identify the resource.
  111. policy_id(str): The unique identifier (ID) of the policy that you want to attach to the target.
  112. You can get the ID for the policy by calling the ListPolicies operation.
  113. target_id(str): The unique identifier (ID) of the root, OU, or account that you want to detach the policy to.
  114. Request Syntax:
  115. [policy-target-id_detach]:
  116. aws.organizations.policy_attachment.absent:
  117. - policy_id: 'string'
  118. - target_id: 'string'
  119. Returns:
  120. Dict[str, Any]
  121. Examples:
  122. .. code-block:: sls
  123. p-id-ou-bitz-1223:
  124. aws.organizations.policy_attachment.absent:
  125. - policy_id: p-id
  126. - target_id: ou-bitz-1223
  127. """
  128. result = dict(comment="", name=name, result=True, old_state=None, new_state=None)
  129. try:
  130. before_ret = await hub.exec.aws.organizations.policy_attachment.is_target_policy_attached(
  131. ctx, policy_id=policy_id, target_id=target_id
  132. )
  133. except hub.tool.boto3.exception.ClientError as e:
  134. result["comment"] = f"{e.__class__.__name__}: {e}"
  135. result["result"] = False
  136. return result
  137. if before_ret["result"] is False and before_ret["comment"]:
  138. result["result"] = False
  139. result["comment"] = before_ret["comment"]
  140. return result
  141. if not before_ret["result"]:
  142. result["comment"] = f"'{name}' already absent"
  143. elif ctx.get("test", False):
  144. result["comment"] = f"Would detach aws.organizations.policy_attachment {name}"
  145. return result
  146. else:
  147. try:
  148. result["old_state"] = before_ret["ret"]
  149. ret = await hub.exec.boto3.client.organizations.detach_policy(
  150. ctx,
  151. PolicyId=policy_id,
  152. TargetId=target_id,
  153. )
  154. result["result"] = ret["result"]
  155. if not result["result"]:
  156. result["comment"] = ret["comment"]
  157. result["result"] = False
  158. return result
  159. result["comment"] = f"Detached '{name}'"
  160. except hub.tool.boto3.exception.ClientError as e:
  161. result["comment"] = f"{e.__class__.__name__}: {e}"
  162. return result
  163. async def describe(hub, ctx) -> Dict[str, Dict[str, Any]]:
  164. r"""
  165. **Autogenerated function**
  166. Retrieves the list of all policies in an organization of a specified type.
  167. This operation can be called only from the organization's management account
  168. or by a member account that is a delegated administrator for an AWS service.
  169. Currently Idem AWS supports only SERVICE_CONTROL_POLICY for a policy type.
  170. Returns:
  171. Dict[str, Any]
  172. Examples:
  173. .. code-block:: bash
  174. $ idem describe aws.organizations.policy_attachment
  175. """
  176. result = {}
  177. ret = await hub.exec.boto3.client.organizations.list_policies(
  178. ctx, Filter="SERVICE_CONTROL_POLICY"
  179. )
  180. if not ret or not ret["ret"]:
  181. hub.log.debug(f"Could not describe policy_attachments {ret['comment']}")
  182. return result
  183. all_policies = ret["ret"].get("Policies", [])
  184. if all_policies:
  185. for policy in all_policies:
  186. policy_attachments_ret = (
  187. await hub.exec.boto3.client.organizations.list_targets_for_policy(
  188. ctx, PolicyId=policy["Id"]
  189. )
  190. )
  191. if not policy_attachments_ret["result"]:
  192. hub.log.warning(
  193. f"Could not get attached target list with policy {policy['Id']} with error"
  194. f" {policy_attachments_ret['comment']} . Describe will skip this policy and continue."
  195. )
  196. else:
  197. targets = policy_attachments_ret["ret"].get("Targets", [])
  198. if not targets:
  199. hub.log.warning(
  200. f"Attached target list with policy {policy['Id']} is empty."
  201. f"Describe will skip this policy and continue."
  202. )
  203. continue
  204. for target in targets:
  205. resource_name = f"{target['TargetId']}-{policy['Id']}"
  206. translated_target = list()
  207. translated_target.append({"policy_id": policy["Id"]})
  208. translated_target.append({"target_id": target["TargetId"]})
  209. result[resource_name] = {
  210. "aws.organizations.policy_attachment.present": translated_target
  211. }
  212. return result