| 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 |
| 10 |
version_added: 5.0.0 |
| 11 |
short_description: Manage inline IAM policies for users, groups, and roles |
| 12 |
description: |
| 13 |
- Allows uploading or removing inline IAM policies for IAM users, groups or roles. |
| 14 |
- To administer managed policies please see M(community.aws.iam_user), M(community.aws.iam_role), |
| 15 |
M(amazon.aws.iam_group) and M(community.aws.iam_managed_policy). |
| 16 |
- This module was originally added to C(community.aws) in release 1.0.0. |
| 17 |
options: |
| 18 |
iam_type: |
| 19 |
description: |
| 20 |
- Type of IAM resource. |
| 21 |
required: true |
| 22 |
choices: [ "user", "group", "role"] |
| 23 |
type: str |
| 24 |
iam_name: |
| 25 |
description: |
| 26 |
- Name of IAM resource you wish to target for policy actions. In other words, the user name, group name or role name. |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
policy_name: |
| 30 |
description: |
| 31 |
- The name label for the policy to create or remove. |
| 32 |
required: true |
| 33 |
type: str |
| 34 |
policy_json: |
| 35 |
description: |
| 36 |
- A properly json formatted policy as string. |
| 37 |
type: json |
| 38 |
state: |
| 39 |
description: |
| 40 |
- Whether to create or delete the IAM policy. |
| 41 |
choices: [ "present", "absent"] |
| 42 |
default: present |
| 43 |
type: str |
| 44 |
skip_duplicates: |
| 45 |
description: |
| 46 |
- When O(skip_duplicates=true) the module looks for any policies that match the document you pass in. |
| 47 |
If there is a match it will not make a new policy object with the same rules. |
| 48 |
default: false |
| 49 |
type: bool |
| 50 |
|
| 51 |
author: |
| 52 |
- "Jonathan I. Davila (@defionscode)" |
| 53 |
- "Dennis Podkovyrin (@sbj-ss)" |
| 54 |
extends_documentation_fragment: |
| 55 |
- amazon.aws.common.modules |
| 56 |
- amazon.aws.region.modules |
| 57 |
- amazon.aws.boto3 |
| 58 |
""" |
| 59 |
|
| 60 |
EXAMPLES = r""" |
| 61 |
# Advanced example, create two new groups and add a READ-ONLY policy to both |
| 62 |
# groups. |
| 63 |
- name: Create Two Groups, Mario and Luigi |
| 64 |
amazon.aws.iam_group: |
| 65 |
name: "{{ item }}" |
| 66 |
state: present |
| 67 |
loop: |
| 68 |
- Mario |
| 69 |
- Luigi |
| 70 |
register: new_groups |
| 71 |
|
| 72 |
- name: Apply READ-ONLY policy to new groups that have been recently created |
| 73 |
amazon.aws.iam_policy: |
| 74 |
iam_type: group |
| 75 |
iam_name: "{{ item.iam_group.group.group_name }}" |
| 76 |
policy_name: "READ-ONLY" |
| 77 |
policy_json: "{{ lookup('template', 'readonly.json.j2') }}" |
| 78 |
state: present |
| 79 |
loop: "{{ new_groups.results }}" |
| 80 |
|
| 81 |
# Create a new S3 policy with prefix per user |
| 82 |
- name: Create S3 policy from template |
| 83 |
amazon.aws.iam_policy: |
| 84 |
iam_type: user |
| 85 |
iam_name: "{{ item.user }}" |
| 86 |
policy_name: "s3_limited_access_{{ item.prefix }}" |
| 87 |
state: present |
| 88 |
policy_json: "{{ lookup('template', 's3_policy.json.j2') }}" |
| 89 |
loop: |
| 90 |
- user: s3_user |
| 91 |
prefix: s3_user_prefix |
| 92 |
""" |
| 93 |
|
| 94 |
RETURN = r""" |
| 95 |
user_name: |
| 96 |
description: Name of IAM user. |
| 97 |
returned: When I(iam_type=user) |
| 98 |
type: str |
| 99 |
sample: "ExampleUser001" |
| 100 |
group_name: |
| 101 |
description: Name of IAM group. |
| 102 |
returned: When I(iam_type=group) |
| 103 |
type: str |
| 104 |
sample: "ExampleGroup001" |
| 105 |
role_name: |
| 106 |
description: Name of IAM role. |
| 107 |
returned: When I(iam_type=role) |
| 108 |
type: str |
| 109 |
sample: "ExampleRole001" |
| 110 |
policy_names: |
| 111 |
description: A list of names of the inline policies embedded in the specified IAM resource (user, group, or role). |
| 112 |
returned: always |
| 113 |
type: list |
| 114 |
elements: str |
| 115 |
sample: ["READ-ONLY"] |
| 116 |
diff: |
| 117 |
description: A dict representing difference between policies applied on IAM resource (user, group, or role). |
| 118 |
returned: always |
| 119 |
type: dict |
| 120 |
contains: |
| 121 |
before: |
| 122 |
description: The policy that exists on IAM resource before new policy is applied. |
| 123 |
returned: always |
| 124 |
type: dict |
| 125 |
sample: { |
| 126 |
"READ-ONLY": { |
| 127 |
"Statement": [ |
| 128 |
{ |
| 129 |
"Action": "ec2:DescribeAccountAttributes", |
| 130 |
"Effect": "Deny", |
| 131 |
"Resource": "*", |
| 132 |
"Sid": "VisualEditor0" |
| 133 |
} |
| 134 |
], |
| 135 |
"Version": "2012-10-17" |
| 136 |
} |
| 137 |
} |
| 138 |
after: |
| 139 |
description: The current policy on IAM resource after new policy is applied. |
| 140 |
returned: always |
| 141 |
type: dict |
| 142 |
sample: { |
| 143 |
"READ-ONLY": { |
| 144 |
"Statement": [ |
| 145 |
{ |
| 146 |
"Action": "ec2:DescribeAccountAttributes", |
| 147 |
"Effect": "Allow", |
| 148 |
"Resource": "*", |
| 149 |
"Sid": "VisualEditor0" |
| 150 |
} |
| 151 |
], |
| 152 |
"Version": "2012-10-17" |
| 153 |
} |
| 154 |
} |
| 155 |
""" |
| 156 |
|
| 157 |
import json |
| 158 |
|
| 159 |
try: |
| 160 |
from botocore.exceptions import BotoCoreError |
| 161 |
from botocore.exceptions import ClientError |
| 162 |
except ImportError: |
| 163 |
pass |
| 164 |
|
| 165 |
|
| 166 |
from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code |
| 167 |
from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule |
| 168 |
from ansible_collections.amazon.aws.plugins.module_utils.policy import compare_policies |
| 169 |
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry |
| 170 |
|
| 171 |
|
| 172 |
class PolicyError(Exception): |
| 173 |
pass |
| 174 |
|
| 175 |
|
| 176 |
class Policy: |
| 177 |
def __init__(self, client, name, policy_name, policy_json, skip_duplicates, state, check_mode): |
| 178 |
self.client = client |
| 179 |
self.name = name |
| 180 |
self.policy_name = policy_name |
| 181 |
self.policy_json = policy_json |
| 182 |
self.skip_duplicates = skip_duplicates |
| 183 |
self.state = state |
| 184 |
self.check_mode = check_mode |
| 185 |
self.changed = False |
| 186 |
|
| 187 |
self.original_policies = self.get_all_policies().copy() |
| 188 |
self.updated_policies = {} |
| 189 |
|
| 190 |
@staticmethod |
| 191 |
def _iam_type(): |
| 192 |
return "" |
| 193 |
|
| 194 |
def _list(self, name): |
| 195 |
return {} |
| 196 |
|
| 197 |
def list(self): |
| 198 |
try: |
| 199 |
return self._list(self.name).get("PolicyNames", []) |
| 200 |
except is_boto3_error_code("AccessDenied"): |
| 201 |
return [] |
| 202 |
|
| 203 |
def _get(self, name, policy_name): |
| 204 |
return "{}" |
| 205 |
|
| 206 |
def get(self, policy_name): |
| 207 |
try: |
| 208 |
return self._get(self.name, policy_name)["PolicyDocument"] |
| 209 |
except is_boto3_error_code("AccessDenied"): |
| 210 |
return {} |
| 211 |
|
| 212 |
def _put(self, name, policy_name, policy_doc): |
| 213 |
pass |
| 214 |
|
| 215 |
def put(self, policy_doc): |
| 216 |
self.changed = True |
| 217 |
|
| 218 |
if self.check_mode: |
| 219 |
return |
| 220 |
|
| 221 |
self._put(self.name, self.policy_name, json.dumps(policy_doc, sort_keys=True)) |
| 222 |
|
| 223 |
def _delete(self, name, policy_name): |
| 224 |
pass |
| 225 |
|
| 226 |
def delete(self): |
| 227 |
self.updated_policies = self.original_policies.copy() |
| 228 |
|
| 229 |
if self.policy_name not in self.list(): |
| 230 |
self.changed = False |
| 231 |
return |
| 232 |
|
| 233 |
self.changed = True |
| 234 |
self.updated_policies.pop(self.policy_name, None) |
| 235 |
|
| 236 |
if self.check_mode: |
| 237 |
return |
| 238 |
|
| 239 |
self._delete(self.name, self.policy_name) |
| 240 |
|
| 241 |
def get_policy_text(self): |
| 242 |
try: |
| 243 |
if self.policy_json is not None: |
| 244 |
return self.get_policy_from_json() |
| 245 |
except json.JSONDecodeError as e: |
| 246 |
raise PolicyError(f"Failed to decode the policy as valid JSON: {str(e)}") |
| 247 |
return None |
| 248 |
|
| 249 |
def get_policy_from_json(self): |
| 250 |
if isinstance(self.policy_json, str): |
| 251 |
pdoc = json.loads(self.policy_json) |
| 252 |
else: |
| 253 |
pdoc = self.policy_json |
| 254 |
return pdoc |
| 255 |
|
| 256 |
def get_all_policies(self): |
| 257 |
policies = {} |
| 258 |
for pol in self.list(): |
| 259 |
policies[pol] = self.get(pol) |
| 260 |
return policies |
| 261 |
|
| 262 |
def create(self): |
| 263 |
matching_policies = [] |
| 264 |
policy_doc = self.get_policy_text() |
| 265 |
policy_match = False |
| 266 |
for pol in self.list(): |
| 267 |
if not compare_policies(self.original_policies[pol], policy_doc): |
| 268 |
matching_policies.append(pol) |
| 269 |
policy_match = True |
| 270 |
|
| 271 |
self.updated_policies = self.original_policies.copy() |
| 272 |
|
| 273 |
if self.policy_name in matching_policies: |
| 274 |
return |
| 275 |
if self.skip_duplicates and policy_match: |
| 276 |
return |
| 277 |
|
| 278 |
self.put(policy_doc) |
| 279 |
self.updated_policies[self.policy_name] = policy_doc |
| 280 |
|
| 281 |
def run(self): |
| 282 |
if self.state == "present": |
| 283 |
self.create() |
| 284 |
elif self.state == "absent": |
| 285 |
self.delete() |
| 286 |
return { |
| 287 |
"changed": self.changed, |
| 288 |
self._iam_type() + "_name": self.name, |
| 289 |
"policy_names": self.list(), |
| 290 |
"diff": dict( |
| 291 |
before=self.original_policies, |
| 292 |
after=self.updated_policies, |
| 293 |
), |
| 294 |
} |
| 295 |
|
| 296 |
|
| 297 |
class UserPolicy(Policy): |
| 298 |
@staticmethod |
| 299 |
def _iam_type(): |
| 300 |
return "user" |
| 301 |
|
| 302 |
def _list(self, name): |
| 303 |
return self.client.list_user_policies(aws_retry=True, UserName=name) |
| 304 |
|
| 305 |
def _get(self, name, policy_name): |
| 306 |
return self.client.get_user_policy(aws_retry=True, UserName=name, PolicyName=policy_name) |
| 307 |
|
| 308 |
def _put(self, name, policy_name, policy_doc): |
| 309 |
return self.client.put_user_policy( |
| 310 |
aws_retry=True, UserName=name, PolicyName=policy_name, PolicyDocument=policy_doc |
| 311 |
) |
| 312 |
|
| 313 |
def _delete(self, name, policy_name): |
| 314 |
return self.client.delete_user_policy(aws_retry=True, UserName=name, PolicyName=policy_name) |
| 315 |
|
| 316 |
|
| 317 |
class RolePolicy(Policy): |
| 318 |
@staticmethod |
| 319 |
def _iam_type(): |
| 320 |
return "role" |
| 321 |
|
| 322 |
def _list(self, name): |
| 323 |
return self.client.list_role_policies(aws_retry=True, RoleName=name) |
| 324 |
|
| 325 |
def _get(self, name, policy_name): |
| 326 |
return self.client.get_role_policy(aws_retry=True, RoleName=name, PolicyName=policy_name) |
| 327 |
|
| 328 |
def _put(self, name, policy_name, policy_doc): |
| 329 |
return self.client.put_role_policy( |
| 330 |
aws_retry=True, RoleName=name, PolicyName=policy_name, PolicyDocument=policy_doc |
| 331 |
) |
| 332 |
|
| 333 |
def _delete(self, name, policy_name): |
| 334 |
return self.client.delete_role_policy(aws_retry=True, RoleName=name, PolicyName=policy_name) |
| 335 |
|
| 336 |
|
| 337 |
class GroupPolicy(Policy): |
| 338 |
@staticmethod |
| 339 |
def _iam_type(): |
| 340 |
return "group" |
| 341 |
|
| 342 |
def _list(self, name): |
| 343 |
return self.client.list_group_policies(aws_retry=True, GroupName=name) |
| 344 |
|
| 345 |
def _get(self, name, policy_name): |
| 346 |
return self.client.get_group_policy(aws_retry=True, GroupName=name, PolicyName=policy_name) |
| 347 |
|
| 348 |
def _put(self, name, policy_name, policy_doc): |
| 349 |
return self.client.put_group_policy( |
| 350 |
aws_retry=True, GroupName=name, PolicyName=policy_name, PolicyDocument=policy_doc |
| 351 |
) |
| 352 |
|
| 353 |
def _delete(self, name, policy_name): |
| 354 |
return self.client.delete_group_policy(aws_retry=True, GroupName=name, PolicyName=policy_name) |
| 355 |
|
| 356 |
|
| 357 |
def main(): |
| 358 |
argument_spec = dict( |
| 359 |
iam_type=dict(required=True, choices=["user", "group", "role"]), |
| 360 |
state=dict(default="present", choices=["present", "absent"]), |
| 361 |
iam_name=dict(required=True), |
| 362 |
policy_name=dict(required=True), |
| 363 |
policy_json=dict(type="json", default=None, required=False), |
| 364 |
skip_duplicates=dict(type="bool", default=False, required=False), |
| 365 |
) |
| 366 |
required_if = [ |
| 367 |
("state", "present", ("policy_json",), True), |
| 368 |
] |
| 369 |
|
| 370 |
module = AnsibleAWSModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) |
| 371 |
|
| 372 |
args = dict( |
| 373 |
client=module.client("iam", retry_decorator=AWSRetry.jittered_backoff()), |
| 374 |
name=module.params.get("iam_name"), |
| 375 |
policy_name=module.params.get("policy_name"), |
| 376 |
policy_json=module.params.get("policy_json"), |
| 377 |
skip_duplicates=module.params.get("skip_duplicates"), |
| 378 |
state=module.params.get("state"), |
| 379 |
check_mode=module.check_mode, |
| 380 |
) |
| 381 |
iam_type = module.params.get("iam_type") |
| 382 |
|
| 383 |
try: |
| 384 |
if iam_type == "user": |
| 385 |
policy = UserPolicy(**args) |
| 386 |
elif iam_type == "role": |
| 387 |
policy = RolePolicy(**args) |
| 388 |
elif iam_type == "group": |
| 389 |
policy = GroupPolicy(**args) |
| 390 |
|
| 391 |
module.exit_json(**(policy.run())) |
| 392 |
except (BotoCoreError, ClientError) as e: |
| 393 |
module.fail_json_aws(e) |
| 394 |
except PolicyError as e: |
| 395 |
module.fail_json(msg=str(e)) |
| 396 |
|
| 397 |
|
| 398 |
if __name__ == "__main__": |
| 399 |
main() |