Debian Codegraph @

ansible_collections/community/aws/plugins/modules/eks_cluster.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 module: eks_cluster
10 version_added: 1.0.0
11 short_description: Manage Elastic Kubernetes Service (EKS) Clusters
12 description:
13 - Manage Elastic Kubernetes Service (EKS) Clusters.
14 - Prior to release 5.0.0 this module was called C(community.aws.aws_eks_cluster).
15 The usage did not change.
16 author:
17 - Will Thames (@willthames)
18 options:
19 name:
20 description: Name of the EKS cluster.
21 required: True
22 type: str
23 version:
24 description:
25 - Kubernetes version.
26 - Defaults to C(latest).
27 type: str
28 role_arn:
29 description: ARN of IAM role used by the EKS cluster.
30 type: str
31 subnets:
32 description: List of subnet IDs for the Kubernetes cluster.
33 type: list
34 elements: str
35 security_groups:
36 description: List of security group names or IDs.
37 type: list
38 elements: str
39 state:
40 description: Desired state of the EKS cluster.
41 choices:
42 - absent
43 - present
44 default: present
45 type: str
46 tags:
47 description:
48 - A dictionary of tags to add the EKS cluster.
49 type: dict
50 version_added: 5.3.0
51 wait:
52 description: >-
53 Specifies whether the module waits until the cluster is active or deleted
54 before moving on. It takes "usually less than 10 minutes" per AWS documentation.
55 type: bool
56 default: false
57 wait_timeout:
58 description: >-
59 The duration in seconds to wait for the cluster to become active. Defaults
60 to 1200 seconds (20 minutes).
61 default: 1200
62 type: int
63 extends_documentation_fragment:
64 - amazon.aws.common.modules
65 - amazon.aws.region.modules
66 - amazon.aws.boto3
67 """
68
69 EXAMPLES = r"""
70 # Note: These examples do not set authentication details, see the AWS Guide for details.
71
72 - name: Create an EKS cluster
73 community.aws.eks_cluster:
74 name: my_cluster
75 version: 1.14
76 role_arn: my_eks_role
77 subnets:
78 - subnet-aaaa1111
79 security_groups:
80 - my_eks_sg
81 - sg-abcd1234
82 register: caller_facts
83
84 - name: Remove an EKS cluster
85 community.aws.eks_cluster:
86 name: my_cluster
87 wait: true
88 state: absent
89 """
90
91 RETURN = r"""
92 arn:
93 description: ARN of the EKS cluster
94 returned: when state is present
95 type: str
96 sample: arn:aws:eks:us-west-2:123456789012:cluster/my-eks-cluster
97 certificate_authority:
98 description: Dictionary containing Certificate Authority Data for cluster
99 returned: after creation
100 type: complex
101 contains:
102 data:
103 description: Base-64 encoded Certificate Authority Data for cluster
104 returned: when the cluster has been created and is active
105 type: str
106 endpoint:
107 description: Kubernetes API server endpoint
108 returned: when the cluster has been created and is active
109 type: str
110 sample: https://API_SERVER_ENDPOINT.yl4.us-west-2.eks.amazonaws.com
111 created_at:
112 description: Cluster creation date and time
113 returned: when state is present
114 type: str
115 sample: '2018-06-06T11:56:56.242000+00:00'
116 name:
117 description: EKS cluster name
118 returned: when state is present
119 type: str
120 sample: my-eks-cluster
121 resources_vpc_config:
122 description: VPC configuration of the cluster
123 returned: when state is present
124 type: complex
125 contains:
126 security_group_ids:
127 description: List of security group IDs
128 returned: always
129 type: list
130 sample:
131 - sg-abcd1234
132 - sg-aaaa1111
133 subnet_ids:
134 description: List of subnet IDs
135 returned: always
136 type: list
137 sample:
138 - subnet-abcdef12
139 - subnet-345678ab
140 - subnet-cdef1234
141 vpc_id:
142 description: VPC id
143 returned: always
144 type: str
145 sample: vpc-a1b2c3d4
146 role_arn:
147 description: ARN of the IAM role used by the cluster
148 returned: when state is present
149 type: str
150 sample: arn:aws:iam::123456789012:role/eks_cluster_role
151 status:
152 description: status of the EKS cluster
153 returned: when state is present
154 type: str
155 sample:
156 - CREATING
157 - ACTIVE
158 version:
159 description: Kubernetes version of the cluster
160 returned: when state is present
161 type: str
162 sample: '1.10'
163 """
164
165 try:
166 import botocore
167 except ImportError:
168 pass # caught by AnsibleAWSModule
169
170 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
171
172 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
173 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import get_ec2_security_group_ids_from_names
174 from ansible_collections.amazon.aws.plugins.module_utils.waiters import get_waiter
175
176 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
177
178
179 def ensure_present(client, module):
180 name = module.params.get("name")
181 subnets = module.params["subnets"]
182 groups = module.params["security_groups"]
183 wait = module.params.get("wait")
184 cluster = get_cluster(client, module)
185 try:
186 ec2 = module.client("ec2")
187 vpc_id = ec2.describe_subnets(SubnetIds=[subnets[0]])["Subnets"][0]["VpcId"]
188 groups = get_ec2_security_group_ids_from_names(groups, ec2, vpc_id)
189 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
190 module.fail_json_aws(e, msg="Couldn't lookup security groups")
191
192 if cluster:
193 if set(cluster["resourcesVpcConfig"]["subnetIds"]) != set(subnets):
194 module.fail_json(msg="Cannot modify subnets of existing cluster")
195 if set(cluster["resourcesVpcConfig"]["securityGroupIds"]) != set(groups):
196 module.fail_json(msg="Cannot modify security groups of existing cluster")
197 if module.params.get("version") and module.params.get("version") != cluster["version"]:
198 module.fail_json(msg="Cannot modify version of existing cluster")
199
200 if wait:
201 wait_until(client, module, "cluster_active")
202 # Ensure that fields that are only available for active clusters are
203 # included in the returned value
204 cluster = get_cluster(client, module)
205
206 module.exit_json(changed=False, **camel_dict_to_snake_dict(cluster))
207
208 if module.check_mode:
209 module.exit_json(changed=True)
210 try:
211 params = dict(
212 name=name,
213 roleArn=module.params["role_arn"],
214 resourcesVpcConfig=dict(subnetIds=subnets, securityGroupIds=groups),
215 )
216 if module.params["version"]:
217 params["version"] = module.params["version"]
218 if module.params["tags"]:
219 params["tags"] = module.params["tags"]
220 cluster = client.create_cluster(**params)["cluster"]
221 except botocore.exceptions.EndpointConnectionError:
222 module.fail_json(msg=f"Region {client.meta.region_name} is not supported by EKS")
223 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
224 module.fail_json_aws(e, msg=f"Couldn't create cluster {name}")
225
226 if wait:
227 wait_until(client, module, "cluster_active")
228 # Ensure that fields that are only available for active clusters are
229 # included in the returned value
230 cluster = get_cluster(client, module)
231
232 module.exit_json(changed=True, **camel_dict_to_snake_dict(cluster))
233
234
235 def ensure_absent(client, module):
236 name = module.params.get("name")
237 existing = get_cluster(client, module)
238 wait = module.params.get("wait")
239 if not existing:
240 module.exit_json(changed=False)
241 if not module.check_mode:
242 try:
243 client.delete_cluster(name=module.params["name"])
244 except botocore.exceptions.EndpointConnectionError:
245 module.fail_json(msg=f"Region {client.meta.region_name} is not supported by EKS")
246 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
247 module.fail_json_aws(e, msg=f"Couldn't delete cluster {name}")
248
249 if wait:
250 wait_until(client, module, "cluster_deleted")
251
252 module.exit_json(changed=True)
253
254
255 def get_cluster(client, module):
256 name = module.params.get("name")
257 try:
258 return client.describe_cluster(name=name)["cluster"]
259 except is_boto3_error_code("ResourceNotFoundException"):
260 return None
261 except botocore.exceptions.EndpointConnectionError: # pylint: disable=duplicate-except
262 module.fail_json(msg=f"Region {client.meta.region_name} is not supported by EKS")
263 except (
264 botocore.exceptions.BotoCoreError,
265 botocore.exceptions.ClientError,
266 ) as e: # pylint: disable=duplicate-except
267 module.fail_json_aws(e, msg=f"Couldn't get cluster {name}")
268
269
270 def wait_until(client, module, waiter_name="cluster_active"):
271 name = module.params.get("name")
272 wait_timeout = module.params.get("wait_timeout")
273
274 waiter = get_waiter(client, waiter_name)
275 attempts = 1 + int(wait_timeout / waiter.config.delay)
276 waiter.wait(name=name, WaiterConfig={"MaxAttempts": attempts})
277
278
279 def main():
280 argument_spec = dict(
281 name=dict(required=True),
282 version=dict(),
283 role_arn=dict(),
284 subnets=dict(type="list", elements="str"),
285 security_groups=dict(type="list", elements="str"),
286 state=dict(choices=["absent", "present"], default="present"),
287 tags=dict(type="dict", required=False),
288 wait=dict(default=False, type="bool"),
289 wait_timeout=dict(default=1200, type="int"),
290 )
291
292 module = AnsibleAWSModule(
293 argument_spec=argument_spec,
294 required_if=[["state", "present", ["role_arn", "subnets", "security_groups"]]],
295 supports_check_mode=True,
296 )
297
298 client = module.client("eks")
299
300 if module.params.get("state") == "present":
301 ensure_present(client, module)
302 else:
303 ensure_absent(client, module)
304
305
306 if __name__ == "__main__":
307 main()