Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/iam_policy_info.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Contributors to the Ansible project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: iam_policy_info
10 version_added: 5.0.0
11 short_description: Retrieve inline IAM policies for users, groups, and roles
12 description:
13 - Supports fetching of inline IAM policies for IAM users, groups and roles.
14 - This module was originally added to C(community.aws) in release 1.0.0.
15 options:
16 iam_type:
17 description:
18 - Type of IAM resource you wish to retrieve inline policies for.
19 required: true
20 choices: [ "user", "group", "role"]
21 type: str
22 iam_name:
23 description:
24 - Name of IAM resource you wish to retrieve inline policies for. In other words, the user name, group name or role name.
25 required: true
26 type: str
27 policy_name:
28 description:
29 - Name of a specific IAM inline policy you with to retrieve.
30 required: false
31 type: str
32 author:
33 - Mark Chappell (@tremble)
34 extends_documentation_fragment:
35 - amazon.aws.common.modules
36 - amazon.aws.region.modules
37 - amazon.aws.boto3
38 """
39
40 EXAMPLES = r"""
41 - name: Describe all inline IAM policies on an IAM User
42 amazon.aws.iam_policy_info:
43 iam_type: user
44 iam_name: example_user
45
46 - name: Describe a specific inline policy on an IAM Role
47 amazon.aws.iam_policy_info:
48 iam_type: role
49 iam_name: example_role
50 policy_name: example_policy
51 """
52
53 RETURN = r"""
54 policies:
55 description: A list containing the matching IAM inline policy names and their data.
56 returned: success
57 type: list
58 elements: dict
59 contains:
60 policy_name:
61 description: The Name of the inline policy.
62 returned: success
63 type: str
64 sample: "test-ec2-list-policy"
65 policy_document:
66 description: The JSON document representing the inline IAM policy.
67 returned: success
68 type: str
69 sample: {
70 "Statement": [
71 {
72 "Action": "ec2:DescribeAccountAttributes",
73 "Effect": "Allow",
74 "Resource": "*",
75 "Sid": "VisualEditor0"
76 }
77 ],
78 "Version": "2012-10-17"
79 }
80 policy_names:
81 description: A list of matching names of the IAM inline policies on the queried object.
82 returned: success
83 type: list
84 sample: [
85 "example-ec2-policy-1",
86 "example-ec2-policy-2"
87 ]
88 all_policy_names:
89 description: A list of names of all of the IAM inline policies on the queried object.
90 returned: success
91 type: list
92 sample: [
93 "example-ec2-policy-1",
94 "example-ec2-policy-2"
95 ]
96 """
97
98 try:
99 import botocore
100 except ImportError:
101 pass
102
103 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
104 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
105 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
106
107
108 class Policy:
109 def __init__(self, client, name, policy_name):
110 self.client = client
111 self.name = name
112 self.policy_name = policy_name
113 self.changed = False
114
115 @staticmethod
116 def _iam_type():
117 return ""
118
119 def _list(self, name):
120 return {}
121
122 def list(self):
123 return self._list(self.name).get("PolicyNames", [])
124
125 def _get(self, name, policy_name):
126 return "{}"
127
128 def get(self, policy_name):
129 return self._get(self.name, policy_name)["PolicyDocument"]
130
131 def get_all(self):
132 policies = list()
133 for policy in self.list():
134 policies.append({"policy_name": policy, "policy_document": self.get(policy)})
135 return policies
136
137 def run(self):
138 policy_list = self.list()
139 ret_val = {"changed": False, self._iam_type() + "_name": self.name, "all_policy_names": policy_list}
140 if self.policy_name is None:
141 ret_val.update(policies=self.get_all())
142 ret_val.update(policy_names=policy_list)
143 elif self.policy_name in policy_list:
144 ret_val.update(policies=[{"policy_name": self.policy_name, "policy_document": self.get(self.policy_name)}])
145 ret_val.update(policy_names=[self.policy_name])
146 return ret_val
147
148
149 class UserPolicy(Policy):
150 @staticmethod
151 def _iam_type():
152 return "user"
153
154 def _list(self, name):
155 return self.client.list_user_policies(aws_retry=True, UserName=name)
156
157 def _get(self, name, policy_name):
158 return self.client.get_user_policy(aws_retry=True, UserName=name, PolicyName=policy_name)
159
160
161 class RolePolicy(Policy):
162 @staticmethod
163 def _iam_type():
164 return "role"
165
166 def _list(self, name):
167 return self.client.list_role_policies(aws_retry=True, RoleName=name)
168
169 def _get(self, name, policy_name):
170 return self.client.get_role_policy(aws_retry=True, RoleName=name, PolicyName=policy_name)
171
172
173 class GroupPolicy(Policy):
174 @staticmethod
175 def _iam_type():
176 return "group"
177
178 def _list(self, name):
179 return self.client.list_group_policies(aws_retry=True, GroupName=name)
180
181 def _get(self, name, policy_name):
182 return self.client.get_group_policy(aws_retry=True, GroupName=name, PolicyName=policy_name)
183
184
185 def main():
186 argument_spec = dict(
187 iam_type=dict(required=True, choices=["user", "group", "role"]),
188 iam_name=dict(required=True),
189 policy_name=dict(default=None, required=False),
190 )
191
192 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
193
194 args = dict(
195 client=module.client("iam", retry_decorator=AWSRetry.jittered_backoff()),
196 name=module.params.get("iam_name"),
197 policy_name=module.params.get("policy_name"),
198 )
199 iam_type = module.params.get("iam_type")
200
201 try:
202 if iam_type == "user":
203 policy = UserPolicy(**args)
204 elif iam_type == "role":
205 policy = RolePolicy(**args)
206 elif iam_type == "group":
207 policy = GroupPolicy(**args)
208
209 module.exit_json(**(policy.run()))
210 except is_boto3_error_code("NoSuchEntity") as e:
211 module.exit_json(changed=False, msg=e.response["Error"]["Message"])
212 except (
213 botocore.exceptions.ClientError,
214 botocore.exceptions.BotoCoreError,
215 ) as e: # pylint: disable=duplicate-except
216 module.fail_json_aws(e)
217
218
219 if __name__ == "__main__":
220 main()