Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 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 version_added: 3.2.0
10 module: cloudfront_response_headers_policy
11
12 short_description: Create, update and delete response headers policies to be used in a Cloudfront distribution
13
14 description:
15 - Create, update and delete response headers policies to be used in a Cloudfront distribution for inserting custom headers
16 - See docs at U(https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudfront.html#CloudFront.Client.create_response_headers_policy)
17
18 author:
19 - Stefan Horning (@stefanhorning)
20
21 options:
22 state:
23 description: Decides if the named policy should be absent or present
24 choices:
25 - present
26 - absent
27 default: present
28 type: str
29 name:
30 description: Name of the policy
31 required: true
32 type: str
33 comment:
34 description: Description of the policy
35 required: false
36 type: str
37 cors_config:
38 description: CORS header config block
39 required: false
40 default: {}
41 type: dict
42 security_headers_config:
43 description: Security headers config block. For headers suchs as XSS-Protection, Content-Security-Policy or Strict-Transport-Security
44 required: false
45 default: {}
46 type: dict
47 custom_headers_config:
48 description: Custom headers config block. Define your own list of headers and values as a list
49 required: false
50 default: {}
51 type: dict
52
53 extends_documentation_fragment:
54 - amazon.aws.common.modules
55 - amazon.aws.region.modules
56 - amazon.aws.boto3
57 """
58
59 EXAMPLES = r"""
60 - name: Creationg a Cloudfront header policy using all predefined header features and a custom header for demonstration
61 community.aws.cloudfront_response_headers_policy:
62 name: my-header-policy
63 comment: My header policy for all the headers
64 cors_config:
65 access_control_allow_origins:
66 items:
67 - 'https://foo.com/bar'
68 - 'https://bar.com/foo'
69 access_control_allow_headers:
70 items:
71 - 'X-Session-Id'
72 access_control_allow_methods:
73 items:
74 - GET
75 - OPTIONS
76 - HEAD
77 access_control_allow_credentials: true
78 access_control_expose_headers:
79 items:
80 - 'X-Session-Id'
81 access_control_max_age_sec: 1800
82 origin_override: true
83 security_headers_config:
84 xss_protection:
85 protection: true
86 report_uri: 'https://my.report-uri.com/foo/bar'
87 override: true
88 frame_options:
89 frame_option: 'SAMEORIGIN'
90 override: true
91 referrer_policy:
92 referrer_policy: 'same-origin'
93 override: true
94 content_security_policy:
95 content_security_policy: "frame-ancestors 'none'; report-uri https://my.report-uri.com/r/d/csp/enforce;"
96 override: true
97 content_type_options:
98 override: true
99 strict_transport_security:
100 include_subdomains: true
101 preload: true
102 access_control_max_age_sec: 63072000
103 override: true
104 custom_headers_config:
105 items:
106 - { header: 'X-Test-Header', value: 'Foo', override: true }
107 state: present
108
109 - name: Delete header policy
110 community.aws.cloudfront_response_headers_policy:
111 name: my-header-policy
112 state: absent
113 """
114
115 RETURN = r"""
116 response_headers_policy:
117 description: The policy's information
118 returned: success
119 type: complex
120 contains:
121 id:
122 description: ID of the policy
123 returned: always
124 type: str
125 sample: '10a45b52-630e-4b7c-77c6-205f06df0462'
126 last_modified_time:
127 description: Timestamp of last modification of policy
128 returned: always
129 type: str
130 sample: '2022-02-04T13:23:27.304000+00:00'
131 response_headers_policy_config:
132 description: The response headers config dict containing all the headers configured
133 returned: always
134 type: complex
135 contains:
136 name:
137 description: Name of the policy
138 type: str
139 returned: always
140 sample: my-header-policy
141 """
142
143 import datetime
144
145 try:
146 from botocore.exceptions import BotoCoreError
147 from botocore.exceptions import ClientError
148 except ImportError:
149 pass # caught by imported AnsibleAWSModule
150
151 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
152 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
153
154 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
155
156
157 class CloudfrontResponseHeadersPolicyService(object):
158 def __init__(self, module):
159 self.module = module
160 self.client = module.client("cloudfront")
161 self.check_mode = module.check_mode
162
163 def find_response_headers_policy(self, name):
164 try:
165 policies = self.client.list_response_headers_policies()["ResponseHeadersPolicyList"]["Items"]
166 for policy in policies:
167 if policy["ResponseHeadersPolicy"]["ResponseHeadersPolicyConfig"]["Name"] == name:
168 # as the list_ request does not contain the Etag (which we need), we need to do another get_ request here
169 return self.client.get_response_headers_policy(Id=policy["ResponseHeadersPolicy"]["Id"])
170
171 except (ClientError, BotoCoreError) as e:
172 self.module.fail_json_aws(e, msg="Error fetching policy information")
173 return None
174
175 def create_response_header_policy(self, name, comment, cors_config, security_headers_config, custom_headers_config):
176 cors_config = snake_dict_to_camel_dict(cors_config, capitalize_first=True)
177 security_headers_config = snake_dict_to_camel_dict(security_headers_config, capitalize_first=True)
178
179 # Little helper for turning xss_protection into XSSProtection and not into XssProtection
180 if "XssProtection" in security_headers_config:
181 security_headers_config["XSSProtection"] = security_headers_config.pop("XssProtection")
182
183 custom_headers_config = snake_dict_to_camel_dict(custom_headers_config, capitalize_first=True)
184
185 config = {
186 "Name": name,
187 "Comment": comment,
188 "CorsConfig": self.insert_quantities(cors_config),
189 "SecurityHeadersConfig": security_headers_config,
190 "CustomHeadersConfig": self.insert_quantities(custom_headers_config),
191 }
192
193 config = {k: v for k, v in config.items() if v}
194
195 matching_policy = self.find_response_headers_policy(name)
196
197 changed = False
198
199 if self.check_mode:
200 self.module.exit_json(changed=True, response_headers_policy=camel_dict_to_snake_dict(config))
201
202 if matching_policy is None:
203 try:
204 result = self.client.create_response_headers_policy(ResponseHeadersPolicyConfig=config)
205 changed = True
206 except (ClientError, BotoCoreError) as e:
207 self.module.fail_json_aws(e, msg="Error creating policy")
208 else:
209 policy_id = matching_policy["ResponseHeadersPolicy"]["Id"]
210 etag = matching_policy["ETag"]
211 try:
212 result = self.client.update_response_headers_policy(
213 Id=policy_id, IfMatch=etag, ResponseHeadersPolicyConfig=config
214 )
215
216 changed_time = result["ResponseHeadersPolicy"]["LastModifiedTime"]
217 seconds = 3 # threshhold for returned timestamp age
218 seconds_ago = datetime.datetime.now(changed_time.tzinfo) - datetime.timedelta(0, seconds)
219
220 # consider change made by this execution of the module if returned timestamp was very recent
221 if changed_time > seconds_ago:
222 changed = True
223 except (ClientError, BotoCoreError) as e:
224 self.module.fail_json_aws(e, msg="Updating creating policy")
225
226 self.module.exit_json(changed=changed, **camel_dict_to_snake_dict(result))
227
228 def delete_response_header_policy(self, name):
229 matching_policy = self.find_response_headers_policy(name)
230
231 if matching_policy is None:
232 self.module.exit_json(msg="Didn't find a matching policy by that name, not deleting")
233 else:
234 policy_id = matching_policy["ResponseHeadersPolicy"]["Id"]
235 etag = matching_policy["ETag"]
236 if self.check_mode:
237 result = {}
238 else:
239 try:
240 result = self.client.delete_response_headers_policy(Id=policy_id, IfMatch=etag)
241 except (ClientError, BotoCoreError) as e:
242 self.module.fail_json_aws(e, msg="Error deleting policy")
243
244 self.module.exit_json(changed=True, **camel_dict_to_snake_dict(result))
245
246 # Inserts a Quantity field into dicts with a list ('Items')
247 @staticmethod
248 def insert_quantities(dict_with_items):
249 # Items on top level case
250 if "Items" in dict_with_items and isinstance(dict_with_items["Items"], list):
251 dict_with_items["Quantity"] = len(dict_with_items["Items"])
252
253 # Items on second level case
254 for k, v in dict_with_items.items():
255 if isinstance(v, dict) and "Items" in v:
256 v["Quantity"] = len(v["Items"])
257
258 return dict_with_items
259
260
261 def main():
262 argument_spec = dict(
263 name=dict(required=True, type="str"),
264 comment=dict(type="str"),
265 cors_config=dict(type="dict", default=dict()),
266 security_headers_config=dict(type="dict", default=dict()),
267 custom_headers_config=dict(type="dict", default=dict()),
268 state=dict(choices=["present", "absent"], type="str", default="present"),
269 )
270
271 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
272
273 name = module.params.get("name")
274 comment = module.params.get("comment", "")
275 cors_config = module.params.get("cors_config")
276 security_headers_config = module.params.get("security_headers_config")
277 custom_headers_config = module.params.get("custom_headers_config")
278 state = module.params.get("state")
279
280 service = CloudfrontResponseHeadersPolicyService(module)
281
282 if state == "absent":
283 service.delete_response_header_policy(name)
284 else:
285 service.create_response_header_policy(
286 name, comment, cors_config, security_headers_config, custom_headers_config
287 )
288
289
290 if __name__ == "__main__":
291 main()