Debian Codegraph @

ansible_collections/community/aws/plugins/modules/config_delivery_channel.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_delivery_channel
10 version_added: 1.0.0
11 short_description: Manage AWS Config delivery channels
12 description:
13 - This module manages AWS Config delivery locations for rule checks and configuration info.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_config_delivery_channel).
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 s3_bucket:
31 description:
32 - The name of the Amazon S3 bucket to which AWS Config delivers configuration snapshots and configuration history files.
33 type: str
34 required: true
35 s3_prefix:
36 description:
37 - The prefix for the specified Amazon S3 bucket.
38 type: str
39 kms_key_arn:
40 description:
41 - The ARN of a KMS key used to encrypt objects delivered by Config. The key must belong to the same region as the destination S3 bucket.
42 type: str
43 sns_topic_arn:
44 description:
45 - The Amazon Resource Name (ARN) of the Amazon SNS topic to which AWS Config sends notifications about configuration changes.
46 type: str
47 delivery_frequency:
48 description:
49 - The frequency with which AWS Config delivers configuration snapshots.
50 choices: ['One_Hour', 'Three_Hours', 'Six_Hours', 'Twelve_Hours', 'TwentyFour_Hours']
51 type: str
52 extends_documentation_fragment:
53 - amazon.aws.common.modules
54 - amazon.aws.region.modules
55 - amazon.aws.boto3
56 """
57
58 EXAMPLES = r"""
59 - name: Create a delivery channel for AWS Config
60 community.aws.config_delivery_channel:
61 name: test_delivery_channel
62 state: present
63 s3_bucket: 'test_aws_config_bucket'
64 sns_topic_arn: 'arn:aws:sns:us-east-1:123456789012:aws_config_topic:1234ab56-cdef-7g89-01hi-2jk34l5m67no'
65 delivery_frequency: 'Twelve_Hours'
66
67 - name: Create a delivery channel with encrypted objects
68 community.aws.config_delivery_channel:
69 name: test_delivery_channel
70 state: present
71 s3_bucket: 'test_aws_config_bucket'
72 kms_key_arn: 'arn:aws:kms:us-east-1:123456789012:key/160f41cb-e660-4fa0-8bf6-976f53bf7851'
73 sns_topic_arn: 'arn:aws:sns:us-east-1:123456789012:aws_config_topic:1234ab56-cdef-7g89-01hi-2jk34l5m67no'
74 delivery_frequency: 'Twelve_Hours'
75 """
76
77 RETURN = r"""#"""
78
79
80 try:
81 import botocore
82 except ImportError:
83 pass # handled by AnsibleAWSModule
84
85 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
86
87 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
88 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
89
90 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
91
92 # this waits for an IAM role to become fully available, at the cost of
93 # taking a long time to fail when the IAM role/policy really is invalid
94 retry_unavailable_iam_on_put_delivery = AWSRetry.jittered_backoff(
95 catch_extra_error_codes=["InsufficientDeliveryPolicyException"],
96 )
97
98
99 def resource_exists(client, module, params):
100 try:
101 channel = client.describe_delivery_channels(
102 DeliveryChannelNames=[params["name"]],
103 aws_retry=True,
104 )
105 return channel["DeliveryChannels"][0]
106 except is_boto3_error_code("NoSuchDeliveryChannelException"):
107 return
108 except (
109 botocore.exceptions.ClientError,
110 botocore.exceptions.BotoCoreError,
111 ) as e: # pylint: disable=duplicate-except
112 module.fail_json_aws(e)
113
114
115 def create_resource(client, module, params, result):
116 try:
117 retry_unavailable_iam_on_put_delivery(
118 client.put_delivery_channel,
119 )(
120 DeliveryChannel=params,
121 )
122 result["changed"] = True
123 result["channel"] = camel_dict_to_snake_dict(resource_exists(client, module, params))
124 return result
125 except is_boto3_error_code("InvalidS3KeyPrefixException") as e:
126 module.fail_json_aws(
127 e,
128 msg="The `s3_prefix` parameter was invalid. Try '/' for no prefix",
129 )
130 except is_boto3_error_code("InsufficientDeliveryPolicyException") as e: # pylint: disable=duplicate-except
131 module.fail_json_aws(
132 e,
133 msg="The `s3_prefix` or `s3_bucket` parameter is invalid. Make sure the bucket exists and is available",
134 )
135 except (
136 botocore.exceptions.ClientError,
137 botocore.exceptions.BotoCoreError,
138 ) as e: # pylint: disable=duplicate-except
139 module.fail_json_aws(
140 e,
141 msg="Couldn't create AWS Config delivery channel",
142 )
143
144
145 def update_resource(client, module, params, result):
146 current_params = client.describe_delivery_channels(
147 DeliveryChannelNames=[params["name"]],
148 aws_retry=True,
149 )
150
151 if params != current_params["DeliveryChannels"][0]:
152 try:
153 retry_unavailable_iam_on_put_delivery(
154 client.put_delivery_channel,
155 )(
156 DeliveryChannel=params,
157 )
158 result["changed"] = True
159 result["channel"] = camel_dict_to_snake_dict(resource_exists(client, module, params))
160 return result
161 except is_boto3_error_code("InvalidS3KeyPrefixException") as e:
162 module.fail_json_aws(e, msg="The `s3_prefix` parameter was invalid. Try '/' for no prefix")
163 except is_boto3_error_code("InsufficientDeliveryPolicyException") as e: # pylint: disable=duplicate-except
164 module.fail_json_aws(
165 e,
166 msg="The `s3_prefix` or `s3_bucket` parameter is invalid. Make sure the bucket exists and is available",
167 )
168 except (
169 botocore.exceptions.ClientError,
170 botocore.exceptions.BotoCoreError,
171 ) as e: # pylint: disable=duplicate-except
172 module.fail_json_aws(e, msg="Couldn't create AWS Config delivery channel")
173
174
175 def delete_resource(client, module, params, result):
176 try:
177 client.delete_delivery_channel(DeliveryChannelName=params["name"])
178 result["changed"] = True
179 return result
180 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
181 module.fail_json_aws(e, msg="Couldn't delete AWS Config delivery channel")
182
183
184 def main():
185 module = AnsibleAWSModule(
186 argument_spec={
187 "name": dict(type="str", required=True),
188 "state": dict(type="str", choices=["present", "absent"], default="present"),
189 "s3_bucket": dict(type="str", required=True),
190 "s3_prefix": dict(type="str"),
191 "kms_key_arn": dict(type="str", no_log=True),
192 "sns_topic_arn": dict(type="str"),
193 "delivery_frequency": dict(
194 type="str",
195 choices=[
196 "One_Hour",
197 "Three_Hours",
198 "Six_Hours",
199 "Twelve_Hours",
200 "TwentyFour_Hours",
201 ],
202 ),
203 },
204 supports_check_mode=False,
205 )
206
207 result = {"changed": False}
208
209 name = module.params.get("name")
210 state = module.params.get("state")
211
212 params = {}
213 if name:
214 params["name"] = name
215 if module.params.get("s3_bucket"):
216 params["s3BucketName"] = module.params.get("s3_bucket")
217 if module.params.get("s3_prefix"):
218 params["s3KeyPrefix"] = module.params.get("s3_prefix")
219 if module.params.get("kms_key_arn"):
220 params["s3KmsKeyArn"] = module.params.get("kms_key_arn")
221 if module.params.get("sns_topic_arn"):
222 params["snsTopicARN"] = module.params.get("sns_topic_arn")
223 if module.params.get("delivery_frequency"):
224 params["configSnapshotDeliveryProperties"] = {"deliveryFrequency": module.params.get("delivery_frequency")}
225
226 client = module.client("config", retry_decorator=AWSRetry.jittered_backoff())
227
228 resource_status = resource_exists(client, module, params)
229
230 if state == "present":
231 if not resource_status:
232 create_resource(client, module, params, result)
233 if resource_status:
234 update_resource(client, module, params, result)
235
236 if state == "absent":
237 if resource_status:
238 delete_resource(client, module, params, result)
239
240 module.exit_json(**result)
241
242
243 if __name__ == "__main__":
244 main()