How to integrate new cdk stack with existed aws EventBridge (EventTarget) - python

Since the resources on AWS have been created by manual on console. e.g.
Rule, EventBus, APIDestination (Target). Means these resource doesn't provide any cdk code.
Point is I want to add more Rule with existing EventBus and APIDestination (Target)**. Then customize input_transformer in targets within cdk code.
from aws_cdk import aws_events as events, aws_events_targets as targets
class TheDestinedLambdaStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
new_rule = events.Rule(
self,
"rule",
event_pattern=events.EventPattern(),
event_bus=events.from_event_bus_arn(), # imported
targets=#APIDestination with params and transformer, dont know method ???
)
It's possible to implement this?
or anyone know which method of EventTarget able to import existed resource to cdk?
Docs:
https://docs.aws.amazon.com/cdk/api/v2/python/aws_cdk.aws_events/EventBus.html

The L1 CfnRule construct can create a new Rule targeting an existing API Destination and custom bus. It can also optionally apply input transforms:
events.CfnRule(
self,
"Rule",
event_bus_name="my-bus-name",
event_pattern={"source": ["cdk-test"]},
targets=[
events.CfnRule.TargetProperty(
arn="arn:aws:events:us-east-1:xxxx:api-destination/xxxxxxxx",
id="foo_rule",
role_arn="arn:aws:iam::xxxxx:role/xxxxxxxxx",
input_transformer=events.CfnRule.InputTransformerProperty(
input_paths_map={"detail-type": "$.detail-type"},
input_template=json.dumps(
{
"transformed": '{"name": "DETAIL_TYPE", "value": <detail-type>}'
}
),
),
)
],
)

Related

list all compute instances in a specific region gcp with python

So, I can list my instances by zones using this API.
GET https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances.
I want now to filter my instances by region. Any idea how can I do this (using python)?
You can use aggregated_list(), to list all your instances on your project. Filtering via region could be done on the actual code. See code below where I used regex to mimic a filter using region variable.
from typing import Dict, Iterable
from google.cloud import compute_v1
import re
def list_all_instances(
project_id: str,
region: str
) -> Dict[str, Iterable[compute_v1.Instance]]:
instance_client = compute_v1.InstancesClient()
request = {
"project" : project_id,
}
agg_list = instance_client.aggregated_list(request=request)
all_instances = {}
print("Instances found:")
for zone, response in agg_list:
if response.instances:
if re.search(f"{region}*", zone):
all_instances[zone] = response.instances
print(f" {zone}:")
for instance in response.instances:
print(f" - {instance.name} ({instance.machine_type})")
return all_instances
list_all_instances(project_id="your-project-id",region="us-central1") #used us-central1 for testing
NOTE: Code above is from this code. I just modified it to apply the filtering above.
Actual instances on my GCP account:
Result from code above (only zones with prefix us-central1 were displayed):

can I access api gate-way of a lambda and extend it?

I have a lambda function like this :
my_executor = python_lambda.PythonFunction(
scope=self,
id="my-lambda-new",
runtime=_lambda.Runtime.PYTHON_3_8,
role=existing_role_for_lambda,
memory_size=512,
function_name="my-lambda-new",
description="This ",
entry="./logs/src/myfolder",
index='controller.py',
handler="lambda_handler",
timeout=core.Duration.minutes(5)
)
I have create api gate way like this :
my_api = _apigateway.LambdaRestApi(
scope=self,
id="my-api",
endpoint_configuration=_apigateway.EndpointConfiguration(
types=[_apigateway.EndpointType.EDGE]
),
handler=my_executor,
default_cors_preflight_options=shared_stack.cors_options,
deploy_options=api_stage,
proxy=True
)
and now In other file using lambda arn I am accessing lambda like this:
_lambda_arn = ssm.StringParameter.value_for_string_parameter(self, "my-executor-lambda-arn")
self.my_executor_lambda = _lambda.Function.from_function_arn(self, "my_executor",
_lambda_arn)
Now how I can extent it's api gateway . want to add new api end point in here
from CDK docs:
Import an existing RestApi that can be configured with additional Methods and Resources.
Take a look at fromRestApiAttributes

Object of type aws-cdk-lib.Resource is not convertible to aws-cdk-lib.aws_eks.Cluster when trying to update the aws-auth ConfigMap

While trying to write a simple CDK script to update the aws-auth ConfigMap, I get the error Object of type aws-cdk-lib.Resource is not convertible to aws-cdk-lib.aws_eks.Cluster. The error seems to stem from the Cluster reference, but I'm not sure why since .from_cluster_attributes returns an ICluster interface.
class EksCdkStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
cluster = eks.Cluster.from_cluster_attributes(self, "Cluster", cluster_name="megaXL")
role = iam.Role.from_role_arn(self, "Role", "arn:aws:iam::123456789012:role/delete_me_role")
eks.AwsAuth(self, "Auth", cluster=cluster).add_role_mapping(role=role, groups="system:masters")
The error seems to stem from the Cluster reference, but I'm not sure why since .from_cluster_attributes returns an ICluster interface.
Almost. AwsAuth requires a Cluster, and you're passing ICluster. This means that you can't create an AwsAuth resource with an imported Cluster.

How do I construct DHCPOptionsAssociation in AWS CDK using Python

I have the following code:
from aws_cdk import (
aws_ec2 as ec2,
core,
)
class MyVpcStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# The code that defines your stack goes here
vpc = ec2.Vpc(
self, 'MyVpc',
cidr='10.10.10.0/23',
max_azs=2
)
dhcp_options = ec2.CfnDHCPOptions(
self, 'MyDhcpOptions',
domain_name='aws-prod.mydomain.com',
domain_name_servers=['10.1.1.5','10.2.1.5'],
ntp_servers=['10.1.1.250','10.2.1.250'],
)
dhcp_options_associations = ec2.CfnVPCDHCPOptionsAssociation(
self, 'MyDhcpOptionsAssociation',
dhcp_options_id=dhcp_options.logical_id,
vpc_id=vpc.vpc_id
)
It generates VPCDHCPOptionsAssociation property INCORRECTLY for this in CloudFormation template like this:
MyDhcpOptionsAssociation:
Type: AWS::EC2::VPCDHCPOptionsAssociation
Properties:
DhcpOptionsId: MyDhcpOptions
VpcId:
Ref: myvpcAB8B6A91
I need this section in CloudFormation template to be like this (CORRECT):
MyDhcpOptionsAssociation:
Type: AWS::EC2::VPCDHCPOptionsAssociation
Properties:
DhcpOptionsId:
Ref: MyDhcpOptions
VpcId:
Ref: myvpcAB8B6A91
If I use dhcp_options_id=dhcp_options.id, I get error AttributeError: 'CfnDHCPOptions' object has no attribute 'id'.
If I use dhcp_options_id=dhcp_options.dhcp_options_id, I get error AttributeError: 'CfnDHCPOptions' object has no attribute 'dhcp_options_id'.
Here is the CDK API reference for this: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnVPCDHCPOptionsAssociation.html
I found it. It has to be .ref, not consistent though with other resource properties.
dhcp_options_associations = ec2.CfnVPCDHCPOptionsAssociation(
self, 'MyDhcpOptionsAssociation',
dhcp_options_id=dhcp_options.ref,
vpc_id=vpc.vpc_id
)

Initializing an object using another object in Python

I have the following code:
import xmlrpc.client as xc
class AristaSwitch():
def __init__(self,devicename,user='admin',password='xxxxxx')
self.url="https://"+user+":"+password+"#"+devicename+"/command-api"
self.Server = xc.Server(self.url) **<----i know this is not correct**
more code below here
I would like to be able to write my code like below:
as = AristaSwitch("192.168.1.1")
as.runCmds(1, [ "show hostname" ] )
The way they do it is:
import xmlrpc.client as xc
switch = xc.Server( "https://admin:admin#172.16.130.16/command-api" )
response = switch.runCmds( 1, [ "show hostname" ] )
Update
I think that adding this to the init function should do it
self.InitializeRPCServer()
def InitializeRPCServer():
switch=xc.Server(self.url)
return switch
It seems you're just trying to wrap around xc.Server. Just use a function instead of a class.
import xmlrpc.client as xc
def AristaSwitch(devicename, user='admin', password='xxxxxx'):
url="https://"+user+":"+password+"#"+devicename+"/command-api"
Server = xc.Server(url)
return Server
Then just do your thing:
as = AristaSwitch("192.168.1.1")
as.runCmds(1, [ "show hostname" ] )
If you're talking about customizing the xc.Server object, you can just inherit it:
class AristaSwitch(xc.Server):
def __init__(self, devicename, user='admin', password='xxxxxx'):
self.url="https://"+user+":"+password+"#"+devicename+"/command-api"
super().__init__(self.url)
You will need to update the def __init__ to your customized url input, but you should be rather savvy about the original implementation since you might be inadvertently overwriting some attributes or implementation details from the super class xc.Server.
With this use case, AristaSwitch is basically xc.Server with a customized instantiation method, and you can compliment it with your own methods later if you wish.

Categories

Resources