Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: 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: dms_replication_subnet_group
10 version_added: 1.0.0
11 short_description: creates or destroys a data migration services subnet group
12 description:
13 - Creates or destroys a data migration services subnet group.
14 options:
15 state:
16 description:
17 - State of the subnet group.
18 default: present
19 choices: ['present', 'absent']
20 type: str
21 identifier:
22 description:
23 - The name for the replication subnet group.
24 This value is stored as a lowercase string.
25 Must contain no more than 255 alphanumeric characters,
26 periods, spaces, underscores, or hyphens. Must not be "default".
27 type: str
28 required: true
29 description:
30 description:
31 - The description for the subnet group.
32 type: str
33 required: true
34 subnet_ids:
35 description:
36 - A list containing the subnet ids for the replication subnet group,
37 needs to be at least 2 items in the list.
38 type: list
39 elements: str
40 required: true
41 author:
42 - "Rui Moreira (@ruimoreira)"
43 extends_documentation_fragment:
44 - amazon.aws.common.modules
45 - amazon.aws.region.modules
46 - amazon.aws.boto3
47 """
48
49 EXAMPLES = r"""
50 - community.aws.dms_replication_subnet_group:
51 state: present
52 identifier: "dev-sngroup"
53 description: "Development Subnet Group asdasdas"
54 subnet_ids: ['subnet-id1', 'subnet-id2']
55 """
56
57 RETURN = r""" # """
58
59 try:
60 import botocore
61 except ImportError:
62 pass # caught by AnsibleAWSModule
63
64 from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
65
66 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
67
68 backoff_params = dict(retries=5, delay=1, backoff=1.5)
69
70
71 @AWSRetry.jittered_backoff(**backoff_params)
72 def describe_subnet_group(connection, subnet_group):
73 """checks if instance exists"""
74 try:
75 subnet_group_filter = dict(Name="replication-subnet-group-id", Values=[subnet_group])
76 return connection.describe_replication_subnet_groups(Filters=[subnet_group_filter])
77 except botocore.exceptions.ClientError:
78 return {"ReplicationSubnetGroups": []}
79
80
81 @AWSRetry.jittered_backoff(**backoff_params)
82 def replication_subnet_group_create(connection, **params):
83 """creates the replication subnet group"""
84 return connection.create_replication_subnet_group(**params)
85
86
87 @AWSRetry.jittered_backoff(**backoff_params)
88 def replication_subnet_group_modify(connection, **modify_params):
89 return connection.modify_replication_subnet_group(**modify_params)
90
91
92 @AWSRetry.jittered_backoff(**backoff_params)
93 def replication_subnet_group_delete(module, connection):
94 subnetid = module.params.get("identifier")
95 delete_parameters = dict(ReplicationSubnetGroupIdentifier=subnetid)
96 return connection.delete_replication_subnet_group(**delete_parameters)
97
98
99 def replication_subnet_exists(subnet):
100 """Returns boolean based on the existence of the endpoint
101 :param endpoint: dict containing the described endpoint
102 :return: bool
103 """
104 return bool(len(subnet["ReplicationSubnetGroups"]))
105
106
107 def create_module_params(module):
108 """
109 Reads the module parameters and returns a dict
110 :return: dict
111 """
112 instance_parameters = dict(
113 # ReplicationSubnetGroupIdentifier gets translated to lower case anyway by the API
114 ReplicationSubnetGroupIdentifier=module.params.get("identifier").lower(),
115 ReplicationSubnetGroupDescription=module.params.get("description"),
116 SubnetIds=module.params.get("subnet_ids"),
117 )
118
119 return instance_parameters
120
121
122 def compare_params(module, param_described):
123 """
124 Compares the dict obtained from the describe function and
125 what we are reading from the values in the template We can
126 never compare passwords as boto3's method for describing
127 a DMS endpoint does not return the value for
128 the password for security reasons ( I assume )
129 """
130 modparams = create_module_params(module)
131 changed = False
132 # need to sanitize values that get returned from the API
133 if "VpcId" in param_described.keys():
134 param_described.pop("VpcId")
135 if "SubnetGroupStatus" in param_described.keys():
136 param_described.pop("SubnetGroupStatus")
137 for param_name, param_value in modparams.items():
138 if param_name in param_described and param_described.get(param_name) == param_value:
139 pass
140 elif param_name == "SubnetIds":
141 subnets = []
142 for subnet in param_described.get("Subnets"):
143 subnets.append(subnet.get("SubnetIdentifier"))
144 for modulesubnet in modparams["SubnetIds"]:
145 if modulesubnet in subnets:
146 pass
147 else:
148 changed = True
149 return changed
150
151
152 def create_replication_subnet_group(module, connection):
153 try:
154 params = create_module_params(module)
155 return replication_subnet_group_create(connection, **params)
156 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
157 module.fail_json_aws(e, msg="Failed to create DMS replication subnet group.")
158
159
160 def modify_replication_subnet_group(module, connection):
161 try:
162 modify_params = create_module_params(module)
163 return replication_subnet_group_modify(connection, **modify_params)
164 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
165 module.fail_json_aws(e, msg="Failed to Modify the DMS replication subnet group.")
166
167
168 def main():
169 argument_spec = dict(
170 state=dict(type="str", choices=["present", "absent"], default="present"),
171 identifier=dict(type="str", required=True),
172 description=dict(type="str", required=True),
173 subnet_ids=dict(type="list", elements="str", required=True),
174 )
175 module = AnsibleAWSModule(argument_spec=argument_spec, supports_check_mode=True)
176 exit_message = None
177 changed = False
178
179 state = module.params.get("state")
180 dmsclient = module.client("dms")
181 subnet_group = describe_subnet_group(dmsclient, module.params.get("identifier"))
182 if state == "present":
183 if replication_subnet_exists(subnet_group):
184 if compare_params(module, subnet_group["ReplicationSubnetGroups"][0]):
185 if not module.check_mode:
186 exit_message = modify_replication_subnet_group(module, dmsclient)
187 else:
188 exit_message = dmsclient
189 changed = True
190 else:
191 exit_message = "No changes to Subnet group"
192 else:
193 if not module.check_mode:
194 exit_message = create_replication_subnet_group(module, dmsclient)
195 changed = True
196 else:
197 exit_message = "Check mode enabled"
198
199 elif state == "absent":
200 if replication_subnet_exists(subnet_group):
201 if not module.check_mode:
202 replication_subnet_group_delete(module, dmsclient)
203 changed = True
204 exit_message = "Replication subnet group Deleted"
205 else:
206 exit_message = dmsclient
207 changed = True
208
209 else:
210 changed = False
211 exit_message = "Replication subnet group does not exist"
212
213 module.exit_json(changed=changed, msg=exit_message)
214
215
216 if __name__ == "__main__":
217 main()