def create_chart(self, *, gen_code_dir, values): self.__code_dir_prefix = os.path.join(gen_code_dir, self.blueprint_id, self.deployment_id) if not os.path.isdir(self.__code_dir_prefix): try: os.makedirs(self.__code_dir_prefix) except OSError: print("Creation of the directory %s failed" % self.__code_dir_prefix) exit(1) else: print("Successfully created the directory %s" % self.__code_dir_prefix) else: print("directory %s already exists" % self.__code_dir_prefix) app = App( outdir=os.path.join(self.__code_dir_prefix, 'kubectl_manifest')) HelloApplication(app, 'k8sresources', deployment_variables=values) app.synth() #Add Cert-manager manifest url = 'https://github.com/jetstack/cert-manager/releases/download/v1.1.0/cert-manager.yaml' urllib.request.urlretrieve( url, os.path.join(self.__code_dir_prefix, 'kubectl_manifest', 'cert-manager.yaml'))
def render(self) -> list: app = App() combined_resource_collection = ChartResourceCollection.combine( [self.service_collection, self.ingress_collection]) chart_json = self.__EasyChart(app, self.deployment, combined_resource_collection).to_json() yaml_manifest = "" for manifest in chart_json: yaml_manifest += f"---\n{yaml.dump(yaml.load(json.dumps(manifest), Loader=yaml.FullLoader))}" return yaml_manifest
#!/usr/bin/env python from constructs import Construct from cdk8s import App, Chart from imports import k8s from webservice import WebService class MyChart(Chart): def __init__(self, scope: Construct, ns: str): super().__init__(scope, ns) # define resources here WebService( self, 'todo-app', image= '<REPLACE_YOUR_ACCOUNT_NUMBER>.dkr.ecr.us-east-1.amazonaws.com/todo-app:latest', replicas=1) app = App() MyChart(app, "cdk8s") app.synth()
def __init__(self, scope: Construct, ns: str): super().__init__(scope, ns) # 定义标签 label = {"app": "guestbook-ui"} # 定义 Service 对象 k8s.Service(self, 'service', spec=k8s.ServiceSpec( type='NodePort', ports=[k8s.ServicePort(port=80, target_port=k8s.IntOrString.from_number(80))], selector=label) ) # 定义 Deployment 对象 k8s.Deployment(self, 'deployment', spec=k8s.DeploymentSpec( replicas=2, selector=k8s.LabelSelector(match_labels=label), template=k8s.PodTemplateSpec( metadata=k8s.ObjectMeta(labels=label), spec=k8s.PodSpec(containers=[ k8s.Container( name='guestbook-ui', image='cnych/ks-guestbook-demo:0.2', ports=[k8s.ContainerPort(container_port=80)])])))) app = App() MyChart(app, "cdk8s-guestbook") app.synth() # 该方法负责生成生成k8s资源清单文件
def build_chart(chart: EasyChart): app = App() combined_resource_collection = ChartResourceCollection.combine( [chart.service_collection, chart.ingress_collection]) return chart.__EasyChart(app, chart.deployment, combined_resource_collection).to_json()