Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 # Based off of https://github.com/mmochan/ansible-aws-ec2-asg-scheduled-actions/blob/master/library/ec2_asg_scheduled_action.py
8 # (c) 2016, Mike Mochan <@mmochan>
9
10 DOCUMENTATION = r"""
11 ---
12 module: autoscaling_scheduled_action
13 version_added: 2.2.0
14 short_description: Create, modify and delete ASG scheduled scaling actions
15 description:
16 - The module will create a new scheduled action when I(state=present) and no given action is found.
17 - The module will update a new scheduled action when I(state=present) and the given action is found.
18 - The module will delete a new scheduled action when I(state=absent) and the given action is found.
19 - Prior to release 5.0.0 this module was called C(community.aws.ec2_asg_scheduled_action).
20 The usage did not change.
21 options:
22 autoscaling_group_name:
23 description:
24 - The name of the autoscaling group to add a scheduled action to.
25 type: str
26 required: true
27 scheduled_action_name:
28 description:
29 - The name of the scheduled action.
30 type: str
31 required: true
32 start_time:
33 description:
34 - Start time for the action.
35 type: str
36 end_time:
37 description:
38 - End time for the action.
39 type: str
40 time_zone:
41 description:
42 - Time zone to run against.
43 type: str
44 recurrence:
45 description:
46 - Cron style schedule to repeat the action on.
47 - Required when I(state=present).
48 type: str
49 min_size:
50 description:
51 - ASG min capacity.
52 type: int
53 max_size:
54 description:
55 - ASG max capacity.
56 type: int
57 desired_capacity:
58 description:
59 - ASG desired capacity.
60 type: int
61 state:
62 description:
63 - Create / update or delete scheduled action.
64 type: str
65 required: false
66 default: present
67 choices: ['present', 'absent']
68 author:
69 - Mark Woolley(@marknet15)
70 extends_documentation_fragment:
71 - amazon.aws.common.modules
72 - amazon.aws.region.modules
73 - amazon.aws.boto3
74 """
75
76 EXAMPLES = r"""
77 # Create a scheduled action for a autoscaling group.
78 - name: Create a minimal scheduled action for autoscaling group
79 community.aws.autoscaling_scheduled_action:
80 region: eu-west-1
81 autoscaling_group_name: test_asg
82 scheduled_action_name: test_scheduled_action
83 start_time: 2021 October 25 08:00 UTC
84 recurrence: 40 22 * * 1-5
85 desired_capacity: 10
86 state: present
87 register: scheduled_action
88
89 - name: Create a scheduled action for autoscaling group
90 community.aws.autoscaling_scheduled_action:
91 region: eu-west-1
92 autoscaling_group_name: test_asg
93 scheduled_action_name: test_scheduled_action
94 start_time: 2021 October 25 08:00 UTC
95 end_time: 2021 October 25 08:00 UTC
96 time_zone: Europe/London
97 recurrence: 40 22 * * 1-5
98 min_size: 10
99 max_size: 15
100 desired_capacity: 10
101 state: present
102 register: scheduled_action
103
104 - name: Delete scheduled action
105 community.aws.autoscaling_scheduled_action:
106 region: eu-west-1
107 autoscaling_group_name: test_asg
108 scheduled_action_name: test_scheduled_action
109 state: absent
110 """
111
112 RETURN = r"""
113 scheduled_action_name:
114 description: The name of the scheduled action.
115 returned: when I(state=present)
116 type: str
117 sample: test_scheduled_action
118 start_time:
119 description: Start time for the action.
120 returned: when I(state=present)
121 type: str
122 sample: '2021 October 25 08:00 UTC'
123 end_time:
124 description: End time for the action.
125 returned: when I(state=present)
126 type: str
127 sample: '2021 October 25 08:00 UTC'
128 time_zone:
129 description: The ID of the Amazon Machine Image used by the launch configuration.
130 returned: when I(state=present)
131 type: str
132 sample: Europe/London
133 recurrence:
134 description: Cron style schedule to repeat the action on.
135 returned: when I(state=present)
136 type: str
137 sample: '40 22 * * 1-5'
138 min_size:
139 description: ASG min capacity.
140 returned: when I(state=present)
141 type: int
142 sample: 1
143 max_size:
144 description: ASG max capacity.
145 returned: when I(state=present)
146 type: int
147 sample: 2
148 desired_capacity:
149 description: ASG desired capacity.
150 returned: when I(state=present)
151 type: int
152 sample: 1
153 """
154
155 try:
156 import botocore
157 except ImportError:
158 pass # caught by AnsibleAWSModule
159
160 try:
161 from dateutil.parser import parse as timedate_parse
162
163 HAS_DATEUTIL = True
164 except ImportError:
165 HAS_DATEUTIL = False
166
167 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
168
169 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
170
171
172 def format_request():
173 params = dict(
174 AutoScalingGroupName=module.params.get("autoscaling_group_name"),
175 ScheduledActionName=module.params.get("scheduled_action_name"),
176 Recurrence=module.params.get("recurrence"),
177 )
178
179 # Some of these params are optional
180 if module.params.get("desired_capacity") is not None:
181 params["DesiredCapacity"] = module.params.get("desired_capacity")
182
183 if module.params.get("min_size") is not None:
184 params["MinSize"] = module.params.get("min_size")
185
186 if module.params.get("max_size") is not None:
187 params["MaxSize"] = module.params.get("max_size")
188
189 if module.params.get("time_zone") is not None:
190 params["TimeZone"] = module.params.get("time_zone")
191
192 if module.params.get("start_time") is not None:
193 params["StartTime"] = module.params.get("start_time")
194
195 if module.params.get("end_time") is not None:
196 params["EndTime"] = module.params.get("end_time")
197
198 return params
199
200
201 def delete_scheduled_action(current_actions):
202 if current_actions == []:
203 return False
204
205 if module.check_mode:
206 return True
207
208 params = dict(
209 AutoScalingGroupName=module.params.get("autoscaling_group_name"),
210 ScheduledActionName=module.params.get("scheduled_action_name"),
211 )
212
213 try:
214 client.delete_scheduled_action(aws_retry=True, **params)
215 except botocore.exceptions.ClientError as e:
216 module.fail_json(msg=str(e))
217
218 return True
219
220
221 def get_scheduled_actions():
222 params = dict(
223 AutoScalingGroupName=module.params.get("autoscaling_group_name"),
224 ScheduledActionNames=[module.params.get("scheduled_action_name")],
225 )
226
227 try:
228 actions = client.describe_scheduled_actions(aws_retry=True, **params)
229 except botocore.exceptions.ClientError as e:
230 module.fail_json_aws(e)
231
232 current_actions = actions.get("ScheduledUpdateGroupActions")
233
234 return current_actions
235
236
237 def put_scheduled_update_group_action(current_actions):
238 changed = False
239 changes = dict()
240 params = format_request()
241
242 if len(current_actions) < 1:
243 changed = True
244 else:
245 # To correctly detect changes convert the start_time & end_time to datetime object
246 if "StartTime" in params:
247 params["StartTime"] = timedate_parse(params["StartTime"])
248 if "EndTime" in params:
249 params["EndTime"] = timedate_parse(params["EndTime"])
250
251 for k, v in params.items():
252 if current_actions[0].get(k) != v:
253 changes[k] = v
254
255 if changes:
256 changed = True
257
258 if module.check_mode:
259 return changed
260
261 try:
262 client.put_scheduled_update_group_action(aws_retry=True, **params)
263 except botocore.exceptions.ClientError as e:
264 module.fail_json_aws(e)
265
266 return changed
267
268
269 def main():
270 global module
271 global client
272
273 argument_spec = dict(
274 autoscaling_group_name=dict(required=True, type="str"),
275 scheduled_action_name=dict(required=True, type="str"),
276 start_time=dict(default=None, type="str"),
277 end_time=dict(default=None, type="str"),
278 time_zone=dict(default=None, type="str"),
279 recurrence=dict(type="str"),
280 min_size=dict(default=None, type="int"),
281 max_size=dict(default=None, type="int"),
282 desired_capacity=dict(default=None, type="int"),
283 state=dict(default="present", choices=["present", "absent"]),
284 )
285
286 module = AnsibleAWSModule(
287 argument_spec=argument_spec, required_if=[["state", "present", ["recurrence"]]], supports_check_mode=True
288 )
289
290 if not HAS_DATEUTIL:
291 module.fail_json(msg="dateutil is required for this module")
292
293 if not module.botocore_at_least("1.20.24"):
294 module.fail_json(msg="botocore version >= 1.20.24 is required for this module")
295
296 client = module.client("autoscaling", retry_decorator=AWSRetry.jittered_backoff())
297 current_actions = get_scheduled_actions()
298 state = module.params.get("state")
299 results = dict()
300
301 if state == "present":
302 changed = put_scheduled_update_group_action(current_actions)
303 if not module.check_mode:
304 updated_action = get_scheduled_actions()[0]
305 results = dict(
306 scheduled_action_name=updated_action.get("ScheduledActionName"),
307 start_time=updated_action.get("StartTime"),
308 end_time=updated_action.get("EndTime"),
309 time_zone=updated_action.get("TimeZone"),
310 recurrence=updated_action.get("Recurrence"),
311 min_size=updated_action.get("MinSize"),
312 max_size=updated_action.get("MaxSize"),
313 desired_capacity=updated_action.get("DesiredCapacity"),
314 )
315 else:
316 changed = delete_scheduled_action(current_actions)
317
318 results["changed"] = changed
319 module.exit_json(**results)
320
321
322 if __name__ == "__main__":
323 main()