|
| 1 | +apiVersion: apiextensions.crossplane.io/v1 |
| 2 | +kind: Composition |
| 3 | +metadata: |
| 4 | + name: networks.caleb.pythonic.com |
| 5 | +spec: |
| 6 | + compositeTypeRef: |
| 7 | + apiVersion: caleb.pythonic.com/v1alpha1 |
| 8 | + kind: Network |
| 9 | + mode: Pipeline |
| 10 | + pipeline: |
| 11 | + |
| 12 | + - step: render-templates |
| 13 | + functionRef: |
| 14 | + name: function-pythonic |
| 15 | + input: |
| 16 | + apiVersion: pythonic.fn.fortra.com/v1alpha1 |
| 17 | + kind: Composite |
| 18 | + composite: | |
| 19 | + from crossplane.pythonic import BaseComposite |
| 20 | + from aiobotocore.session import get_session |
| 21 | +
|
| 22 | + class NetworkComposite(BaseComposite): |
| 23 | + async def compose(self): |
| 24 | + # Only create the AWS Session if needed |
| 25 | + self._aws_session = None |
| 26 | + # Create/Get VPC |
| 27 | + vpc = await self.compose_vpc() |
| 28 | +
|
| 29 | + async def compose_vpc(self): |
| 30 | + vpc = self.resources.VPC('ec2.aws.m.upbound.io/v1beta1', 'VPC') |
| 31 | + vpc.spec.forProvider( |
| 32 | + region = self.spec.region, |
| 33 | + cidrBlock = self.spec.cidr, |
| 34 | + enableDnsHostnames = True, |
| 35 | + enableDnsSupport = True, |
| 36 | + tags = self.tags(Name=self.metadata.name), |
| 37 | + ) |
| 38 | + if not vpc.externalName: |
| 39 | + async with self.aws_client('ec2') as ec2: |
| 40 | + vpcs = (await ec2.describe_vpcs( |
| 41 | + Filters=[{ |
| 42 | + 'Name': 'tag:Name', |
| 43 | + 'Values': [str(self.metadata.name)], |
| 44 | + }], |
| 45 | + ))['Vpcs'] |
| 46 | + if vpcs: |
| 47 | + if len(vpcs) == 1: |
| 48 | + vpc.externalName = vpcs[0]['VpcId'] |
| 49 | + else: |
| 50 | + self.events.fatal('MultipleResources', f"More than one vpc found for: {self.metadata.name}") |
| 51 | + self.status.vpcId = vpc.status.atProvider.vpcId |
| 52 | + return vpc |
| 53 | +
|
| 54 | + def aws_client(self, service): |
| 55 | + if not self._aws_session: |
| 56 | + self._aws_session = get_session() |
| 57 | + self._aws_clients = {} |
| 58 | + client = self._aws_clients.get(service) |
| 59 | + if not client: |
| 60 | + client = self._aws_session.create_client(service, str(self.spec.region)) |
| 61 | + self._aws_clients[service] = client |
| 62 | + return client |
| 63 | +
|
| 64 | + def tags(self, *args, **kwargs): |
| 65 | + tags = {} |
| 66 | + for arg in args: |
| 67 | + arg = arg.split('=', 1) |
| 68 | + tags[arg[0].strip()] = arg[1].lstrip() |
| 69 | + tags.update(kwargs) |
| 70 | + if self.spec.tags: |
| 71 | + for key, value in self.spec.tags: |
| 72 | + tags[key] = value |
| 73 | + return tags |
0 commit comments