PageRenderTime 55ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/idem_aws/states/aws/ec2/subnet.py

https://gitlab.com/pgeorgiev_vmw/idem-aws
Python | 320 lines | 314 code | 0 blank | 6 comment | 0 complexity | 3d89e043c3deb90ff977c994a4a1dae6 MD5 | raw file
  1. """
  2. Autogenerated state module using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__
  3. hub.exec.boto3.client.ec2.create_subnet
  4. hub.exec.boto3.client.ec2.delete_subnet
  5. hub.exec.boto3.client.ec2.describe_subnets
  6. resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", name)
  7. hub.tool.boto3.resource.exec(resource, create_instances, *args, **kwargs)
  8. hub.tool.boto3.resource.exec(resource, create_network_interface, *args, **kwargs)
  9. hub.tool.boto3.resource.exec(resource, create_tags, *args, **kwargs)
  10. hub.tool.boto3.resource.exec(resource, delete, *args, **kwargs)
  11. """
  12. import copy
  13. from typing import Any
  14. from typing import Dict
  15. from typing import List
  16. __contracts__ = ["resource"]
  17. TREQ = {
  18. "absent": {
  19. "require": [
  20. "aws.ec2.vpc.absent",
  21. ],
  22. },
  23. "present": {
  24. "require": [
  25. "aws.ec2.vpc.present",
  26. ],
  27. },
  28. }
  29. async def present(
  30. hub,
  31. ctx,
  32. name: str,
  33. vpc_id: str,
  34. cidr_block: str,
  35. resource_id: str = None,
  36. tags: List = None,
  37. availability_zone: str = None,
  38. availability_zone_id: str = None,
  39. ipv6_cidr_block: str = None,
  40. outpost_arn: str = None,
  41. ) -> Dict[str, Any]:
  42. r"""
  43. **Autogenerated function**
  44. Creates a subnet in a specified VPC. You must specify an IPv4 CIDR block for the subnet. After you create a
  45. subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses)
  46. and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in
  47. the VPC. If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block
  48. that uses a /64 prefix length. Amazon Web Services reserves both the first four and the last IPv4 address in
  49. each subnet's CIDR block. They're not available for use. If you add more than one subnet to a VPC, they're set
  50. up in a star topology with a logical router in the middle. When you stop an instance in a subnet, it retains its
  51. private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped),
  52. but no remaining IP addresses available. For more information about subnets, see Your VPC and subnets in the
  53. Amazon Virtual Private Cloud User Guide.
  54. Args:
  55. name(Text): An Idem name of the resource.
  56. vpc_id(Text): ID of the VPC.
  57. cidr_block(Text): The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24. We modify the
  58. specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18, we
  59. modify it to 100.68.0.0/18.
  60. resource_id(Text, optional): AWS Subnet ID
  61. tags(List, optional): The tags to assign to the subnet. Defaults to None.
  62. * Key (string) -- The key of the tag. Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: .
  63. * Value (string) -- The value of the tag. Tag values are case-sensitive and accept a maximum of 255 Unicode characters.
  64. availability_zone(Text, optional): The Availability Zone or Local Zone for the subnet. Default: Amazon Web Services selects one for
  65. you. If you create more than one subnet in your VPC, we do not necessarily select a different
  66. zone for each subnet. To create a subnet in a Local Zone, set this value to the Local Zone ID,
  67. for example us-west-2-lax-1a. For information about the Regions that support Local Zones, see
  68. Available Regions in the Amazon Elastic Compute Cloud User Guide. To create a subnet in an
  69. Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. Defaults to None.
  70. availability_zone_id(Text, optional): The AZ ID or the Local Zone ID of the subnet. Defaults to None.
  71. ipv6_cidr_block(Text, optional): The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix
  72. length. Defaults to None.
  73. outpost_arn(Text, optional): The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also
  74. specify the Availability Zone of the Outpost subnet. Defaults to None.
  75. Request Syntax:
  76. [subnet-resource-name]:
  77. aws.ec2.subnet.present:
  78. - resource_id: 'string'
  79. - cidr_block: 'string'
  80. - ipv6_cidr_block: 'string'
  81. - vpc_id: 'string'
  82. - availability_zone: 'string'
  83. - availability_zone_id: 'string'
  84. - outpost_arn: 'string'
  85. - tags:
  86. - Key: 'string'
  87. Value: 'string'
  88. Returns:
  89. Dict[str, Any]
  90. Examples:
  91. .. code-block:: sls
  92. my-subnet:
  93. aws.ec2.subnet.present:
  94. - vpc_id: vpc-07123af5a5zwqcc0
  95. - cidr_block: 10.10.10.0/28
  96. - availability_zone: eu-west-2c
  97. - tags:
  98. - Key: Name
  99. Value: Idem-test-subnet
  100. - ipv6_cidr_block: 2a05:d01c:74f:7200::/64
  101. """
  102. result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
  103. before = None
  104. resource_updated = False
  105. if resource_id:
  106. resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", resource_id)
  107. before = await hub.tool.boto3.resource.describe(resource)
  108. if before:
  109. try:
  110. result[
  111. "old_state"
  112. ] = hub.tool.aws.ec2.conversion_utils.convert_raw_subnet_to_present(
  113. raw_resource=before, idem_resource_name=name
  114. )
  115. plan_state = copy.deepcopy(result["old_state"])
  116. # Update ipv6 cidr block
  117. ipv6_cidr_block_association_set = (
  118. hub.tool.aws.network_utils.get_associated_ipv6_cidr_blocks(
  119. before.get("Ipv6CidrBlockAssociationSet")
  120. )
  121. )
  122. if ipv6_cidr_block != (
  123. None
  124. if not ipv6_cidr_block_association_set
  125. else ipv6_cidr_block_association_set[0]
  126. ):
  127. update_ret = await hub.exec.aws.ec2.subnet.update_ipv6_cidr_blocks(
  128. ctx=ctx,
  129. subnet_id=before.get("SubnetId"),
  130. old_ipv6_cidr_block=None
  131. if not ipv6_cidr_block_association_set
  132. else ipv6_cidr_block_association_set[0],
  133. new_ipv6_cidr_block={"Ipv6CidrBlock": ipv6_cidr_block}
  134. if ipv6_cidr_block
  135. else None,
  136. )
  137. result["result"] = result["result"] and update_ret["result"]
  138. result["comment"] = update_ret["comment"]
  139. resource_updated = True
  140. if ctx.get("test", False) and update_ret["ret"] is not None:
  141. plan_state["ipv6_cidr_block"] = update_ret["ret"].get(
  142. "ipv6_cidr_block"
  143. )
  144. if tags is not None:
  145. # Update tags
  146. update_ret = await hub.exec.aws.ec2.tag.update_tags(
  147. ctx=ctx,
  148. resource_id=before.get("SubnetId"),
  149. old_tags=before.get("Tags"),
  150. new_tags=tags,
  151. )
  152. result["comment"] = result["comment"] + update_ret["comment"]
  153. result["result"] = result["result"] and update_ret["result"]
  154. resource_updated = resource_updated or bool(update_ret["ret"])
  155. if ctx.get("test", False) and update_ret["ret"] is not None:
  156. plan_state["tags"] = update_ret["ret"].get("tags")
  157. if resource_updated:
  158. if ctx.get("test", False):
  159. result["comment"] = result["comment"] + (
  160. f"'Would update aws.ec2.subnet '{name}'",
  161. )
  162. else:
  163. result["comment"] = result["comment"] + (f"Updated '{name}'",)
  164. except hub.tool.boto3.exception.ClientError as e:
  165. result["comment"] = result["comment"] + (f"{e.__class__.__name__}: {e}",)
  166. result["result"] = False
  167. else:
  168. if ctx.get("test", False):
  169. result["new_state"] = hub.tool.aws.test_state_utils.generate_test_state(
  170. enforced_state={},
  171. desired_state={
  172. "name": name,
  173. "availability_zone": availability_zone,
  174. "availability_zone_id": availability_zone_id,
  175. "cidr_block": cidr_block,
  176. "ipv6_cidr_block": ipv6_cidr_block,
  177. "outpost_arn": outpost_arn,
  178. "vpc_id": vpc_id,
  179. "tags": tags,
  180. },
  181. )
  182. result["comment"] = (f"Would create aws.ec2.subnet '{name}'",)
  183. return result
  184. try:
  185. ret = await hub.exec.boto3.client.ec2.create_subnet(
  186. ctx,
  187. **{
  188. "TagSpecifications": [{"ResourceType": "subnet", "Tags": tags}]
  189. if tags
  190. else None,
  191. "AvailabilityZone": availability_zone,
  192. "AvailabilityZoneId": availability_zone_id,
  193. "Ipv6CidrBlock": ipv6_cidr_block,
  194. "OutpostArn": outpost_arn,
  195. "VpcId": vpc_id,
  196. "CidrBlock": cidr_block,
  197. },
  198. )
  199. result["result"] = ret["result"]
  200. if not result["result"]:
  201. result["comment"] = ret["comment"]
  202. return result
  203. result["comment"] = (f"Created '{name}'",)
  204. resource_id = ret["ret"]["Subnet"]["SubnetId"]
  205. except hub.tool.boto3.exception.ClientError as e:
  206. result["comment"] = result["comment"] + (f"{e.__class__.__name__}: {e}",)
  207. result["result"] = False
  208. try:
  209. if ctx.get("test", False):
  210. result["new_state"] = plan_state
  211. elif (not before) or resource_updated:
  212. resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", resource_id)
  213. after = await hub.tool.boto3.resource.describe(resource)
  214. result[
  215. "new_state"
  216. ] = hub.tool.aws.ec2.conversion_utils.convert_raw_subnet_to_present(
  217. raw_resource=after, idem_resource_name=name
  218. )
  219. else:
  220. result["new_state"] = copy.deepcopy(result["old_state"])
  221. except Exception as e:
  222. result["comment"] = result["comment"] + (str(e),)
  223. result["result"] = False
  224. return result
  225. async def absent(hub, ctx, name: str, resource_id: str) -> Dict[str, Any]:
  226. r"""
  227. **Autogenerated function**
  228. Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the
  229. subnet.
  230. Args:
  231. name(Text): The Idem name of the subnet.
  232. resource_id(Text): The AWS ID of the subnet.
  233. Returns:
  234. Dict[str, Any]
  235. Examples:
  236. .. code-block:: sls
  237. resource_is_absent:
  238. aws.ec2.subnet.absent:
  239. - name: value
  240. - resource_id: value
  241. """
  242. result = dict(comment="", old_state=None, new_state=None, name=name, result=True)
  243. resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", resource_id)
  244. before = await hub.tool.boto3.resource.describe(resource)
  245. if not before:
  246. result["comment"] = (f"'{name}' already absent",)
  247. elif ctx.get("test", False):
  248. result[
  249. "old_state"
  250. ] = hub.tool.aws.ec2.conversion_utils.convert_raw_subnet_to_present(
  251. raw_resource=before, idem_resource_name=name
  252. )
  253. result["comment"] = (f"Would delete aws.ec2.subnet '{name}'",)
  254. return result
  255. else:
  256. result[
  257. "old_state"
  258. ] = hub.tool.aws.ec2.conversion_utils.convert_raw_subnet_to_present(
  259. raw_resource=before, idem_resource_name=name
  260. )
  261. try:
  262. ret = await hub.exec.boto3.client.ec2.delete_subnet(
  263. ctx, SubnetId=resource_id
  264. )
  265. result["result"] = ret["result"]
  266. if not result["result"]:
  267. result["comment"] = ret["comment"]
  268. return result
  269. result["comment"] = (f"Deleted '{name}'",)
  270. except hub.tool.boto3.exception.ClientError as e:
  271. result["comment"] = result["comment"] + (f"{e.__class__.__name__}: {e}",)
  272. return result
  273. async def describe(hub, ctx) -> Dict[str, Dict[str, Any]]:
  274. result = {}
  275. ret = await hub.exec.boto3.client.ec2.describe_subnets(ctx)
  276. if not ret["result"]:
  277. hub.log.debug(f"Could not describe Subnets {ret['comment']}")
  278. return {}
  279. for subnet in ret["ret"]["Subnets"]:
  280. subnet_id = subnet.get("SubnetId")
  281. resource_translated = (
  282. hub.tool.aws.ec2.conversion_utils.convert_raw_subnet_to_present(
  283. raw_resource=subnet, idem_resource_name=subnet_id
  284. )
  285. )
  286. result[subnet_id] = {
  287. "aws.ec2.subnet.present": [
  288. {parameter_key: parameter_value}
  289. for parameter_key, parameter_value in resource_translated.items()
  290. ]
  291. }
  292. return result