Debian Codegraph @

ansible_collections/community/aws/plugins/modules/config_recorder.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Aaron Smith <[email protected]>
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: config_recorder
10 version_added: 1.0.0
11 short_description: Manage AWS Config Recorders
12 description:
13 - Module manages AWS Config configuration recorder settings.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_config_recorder).
15 The usage did not change.
16 author:
17 - "Aaron Smith (@slapula)"
18 options:
19 name:
20 description:
21 - The name of the AWS Config resource.
22 required: true
23 type: str
24 state:
25 description:
26 - Whether the Config rule should be present or absent.
27 default: present
28 choices: ['present', 'absent']
29 type: str
30 role_arn:
31 description:
32 - Amazon Resource Name (ARN) of the IAM role used to describe the AWS resources associated with the account.
33 - Required when I(state=present).
34 type: str
35 recording_group:
36 description:
37 - Specifies the types of AWS resources for which AWS Config records configuration changes.
38 - Required when I(state=present)
39 suboptions:
40 all_supported:
41 description:
42 - Specifies whether AWS Config records configuration changes for every supported type of regional resource.
43 - If I(all_supported=true), when AWS Config adds support for a new type of regional resource, it starts
44 recording resources of that type automatically.
45 - If I(all_supported=true), you cannot enumerate a list of I(resource_types).
46 include_global_types:
47 description:
48 - Specifies whether AWS Config includes all supported types of global resources (for example, IAM resources)
49 with the resources that it records.
50 - The configuration details for any global resource are the same in all regions. To prevent duplicate configuration items,
51 you should consider customizing AWS Config in only one region to record global resources.
52 - If you set I(include_global_types=true), you must also set I(all_supported=true).
53 - If you set I(include_global_types=true), when AWS Config adds support for a new type of global resource, it starts recording
54 resources of that type automatically.
55 resource_types:
56 description:
57 - A list that specifies the types of AWS resources for which AWS Config records configuration changes (for example,
58 C(AWS::EC2::Instance) or C(AWS::CloudTrail::Trail)).
59 - Before you can set this option, you must set I(all_supported=false).
60 type: dict
61 extends_documentation_fragment:
62 - amazon.aws.common.modules
63 - amazon.aws.region.modules
64 - amazon.aws.boto3
65 """
66
67 EXAMPLES = r"""
68 - name: Create Configuration Recorder for AWS Config
69 community.aws.config_recorder:
70 name: test_configuration_recorder
71 state: present
72 role_arn: 'arn:aws:iam::123456789012:role/AwsConfigRecorder'
73 recording_group:
74 all_supported: true
75 include_global_types: true
76 """
77
78 RETURN = r"""#"""
79
80
81 try:
82 import botocore
83 except ImportError:
84 pass # handled by AnsibleAWSModule
85
86 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
87
88 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
89 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
90
91 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
92
93
94 def resource_exists(client, module, params):
95 try:
96 recorder = client.describe_configuration_recorders(ConfigurationRecorderNames=[params["name"]])
97 return recorder["ConfigurationRecorders"][0]
98 except is_boto3_error_code("NoSuchConfigurationRecorderException"):
99 return
100 except (
101 botocore.exceptions.ClientError,
102 botocore.exceptions.BotoCoreError,
103 ) as e: # pylint: disable=duplicate-except
104 module.fail_json_aws(e)
105
106
107 def create_resource(client, module, params, result):
108 try:
109 client.put_configuration_recorder(ConfigurationRecorder=params)
110 result["changed"] = True
111 result["recorder"] = camel_dict_to_snake_dict(resource_exists(client, module, params))
112 return result
113 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
114 module.fail_json_aws(e, msg="Couldn't create AWS Config configuration recorder")
115
116
117 def update_resource(client, module, params, result):
118 current_params = client.describe_configuration_recorders(ConfigurationRecorderNames=[params["name"]])
119
120 if params != current_params["ConfigurationRecorders"][0]:
121 try:
122 client.put_configuration_recorder(ConfigurationRecorder=params)
123 result["changed"] = True
124 result["recorder"] = camel_dict_to_snake_dict(resource_exists(client, module, params))
125 return result
126 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
127 module.fail_json_aws(e, msg="Couldn't update AWS Config configuration recorder")
128
129
130 def delete_resource(client, module, params, result):
131 try:
132 client.delete_configuration_recorder(ConfigurationRecorderName=params["name"])
133 result["changed"] = True
134 return result
135 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
136 module.fail_json_aws(e, msg="Couldn't delete AWS Config configuration recorder")
137
138
139 def main():
140 module = AnsibleAWSModule(
141 argument_spec={
142 "name": dict(type="str", required=True),
143 "state": dict(type="str", choices=["present", "absent"], default="present"),
144 "role_arn": dict(type="str"),
145 "recording_group": dict(type="dict"),
146 },
147 supports_check_mode=False,
148 required_if=[
149 ("state", "present", ["role_arn", "recording_group"]),
150 ],
151 )
152
153 result = {"changed": False}
154
155 name = module.params.get("name")
156 state = module.params.get("state")
157
158 params = {}
159 if name:
160 params["name"] = name
161 if module.params.get("role_arn"):
162 params["roleARN"] = module.params.get("role_arn")
163 if module.params.get("recording_group"):
164 params["recordingGroup"] = {}
165 if module.params.get("recording_group").get("all_supported") is not None:
166 params["recordingGroup"].update({"allSupported": module.params.get("recording_group").get("all_supported")})
167 if module.params.get("recording_group").get("include_global_types") is not None:
168 params["recordingGroup"].update(
169 {"includeGlobalResourceTypes": module.params.get("recording_group").get("include_global_types")}
170 )
171 if module.params.get("recording_group").get("resource_types"):
172 params["recordingGroup"].update(
173 {"resourceTypes": module.params.get("recording_group").get("resource_types")}
174 )
175 else:
176 params["recordingGroup"].update({"resourceTypes": []})
177
178 client = module.client("config", retry_decorator=AWSRetry.jittered_backoff())
179
180 resource_status = resource_exists(client, module, params)
181
182 if state == "present":
183 if not resource_status:
184 create_resource(client, module, params, result)
185 if resource_status:
186 update_resource(client, module, params, result)
187
188 if state == "absent":
189 if resource_status:
190 delete_resource(client, module, params, result)
191
192 module.exit_json(changed=result["changed"])
193
194
195 if __name__ == "__main__":
196 main()