Optimaliseer mijn Pulumi infrastructuur met herbruikbare componenten
description
Met deze prompt kan de gebruiker zijn Pulumi code modulair en schaalbaar maken, waardoor onderhoud eenvoudiger wordt en hergebruik van infrastructuurelementen wordt gestimuleerd. Dit bespaart tijd en vermindert fouten in complexe infrastructuren, wat beter is dan eenvoudige, monolithische scripts.
prompt
Help me mijn Pulumi infrastructuur te herstructureren door herbruikbare componenten te ontwe ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Om je Pulumi-infrastructuur te herstructureren en herbruikbare componenten te creëren, kun je gebruikmaken van Pulumi's component resources. Hieronder vind je een voorbeeld van hoe je een herbruikbare VPC- en EC2-instantie component kunt ontwerpen en gebruiken in je Pulumi-script, geschreven in Python.
Stap 1: Maak een component voor de VPC
```python
import pulumi
import pulumi_aws as aws
class VpcComponent(pulumi.ComponentResource):
def __init__(self, name, cidr_block, opts=None):
super().__init__('custom:resource:VpcComponent', name, {}, opts)
# Maak een VPC
self.vpc = aws.ec2.Vpc(f"{name}-vpc",
cidr_block=cidr_block,
tags={"Name": f"{name}-vpc"},
opts=pulumi.ResourceOptions(parent=self)
)
# Subnet aanmaken (bijvoorbeeld een openbare subnet)
self.subnet = aws.ec2.Subnet(f"{name}-subnet",
vpc_id=self.vpc.id,
cidr_block=f"{cidr_block[:-1]}0/24", # voorbeeld subnet
tags={"Name": f"{name}-subnet"},
opts=pulumi.ResourceOptions(parent=self)
)
# Internet Gateway
self.igw = aws.ec2.InternetGateway(f"{name}-igw",
vpc_id=self.vpc.id,
tags={"Name": f"{name}-igw"},
opts=pulumi.ResourceOptions(parent=self)
)
# Route tabel
self.route_table = aws.ec2.RouteTable(f"{name}-rt",
vpc_id=self.vpc.id,
routes=[aws.ec2.RouteTableRouteArgs(
cidr_block="0.0.0.0/0",
gateway_id=self.igw.id
)],
opts=pulumi.ResourceOptions(parent=self)
)
# Associate route tabel met subnet
self.route_table_assoc = aws.ec2.RouteTableAssociation(f"{name}-rta",
subnet_id=self.subnet.id,
route_table_id=self.route_table.id,
opts=pulumi.ResourceOptions(parent=self)
)
self.register_outputs({
"vpc": self.vpc,
"subnet": self.subnet
})
```
Stap 2: Maak een component voor EC2-instanties
```python
class Ec2InstanceComponent(pulumi.ComponentResource):
def __init__(self, name, subnet_id, ami_id, instance_type, opts=None):
super().__init__('custom:resource:Ec2InstanceComponent', name, {}, opts)
self.instance = aws.ec2.Instance(f"{name}-instance",
ami=ami_id,
instance_type=instance_type,
subnet_id=subnet_id,
tags={"Name": name},
opts=pulumi.ResourceOptions(parent=self)
)
self.register_outputs({
"instance": self.instance
})
```
Stap 3: Gebruik de componenten in je hoofdscript
```python
import pulumi
import pulumi_aws as aws
# Creëer de VPC component
vpc = VpcComponent("mijnVPC", cidr_block="10.0.0.0/16")
# AMI ID voor Amazon Linux (bijvoorbeeld)
ami_id = "ami-0c94855ba95c71c99" # pas aan naar je regio
# Maak 3 EC2-instanties aan
instances = []
for i in range(3):
instance = Ec2InstanceComponent(
f"webserver-{i+1}",
subnet_id=vpc.subnet.id,
ami_id=ami_id,
instance_type="t2.micro"
)
instances.append(instance)
```
Door deze aanpak worden je infrastructuurcomponenten herbruikbaar en overzichtelijk. Je kunt nu eenvoudig nieuwe VPCs en EC2-instanties toevoegen of aanpassen zonder de basislogica te dupliceren.
provider: deepseek
model: deepseek-chat
Hier is een herstructuurde versie van je Pulumi-configuratie met herbruikbare componenten in TypeScript:
**1. Eerst maken we een herbruikbare VPC-component (`VpcComponent.ts`):**
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
export interface VpcComponentArgs {
cidrBlock: string;
vpcName: string;
enableDnsHostnames?: boolean;
enableDnsSupport?: boolean;
}
export class VpcComponent extends pulumi.ComponentResource {
public readonly vpc: aws.ec2.Vpc;
public readonly publicSubnet: aws.ec2.Subnet;
public readonly internetGateway: aws.ec2.InternetGateway;
public readonly routeTable: aws.ec2.RouteTable;
constructor(name: string, args: VpcComponentArgs, opts?: pulumi.ComponentResourceOptions) {
super("custom:component:VpcComponent", name, {}, opts);
// VPC aanmaken
this.vpc = new aws.ec2.Vpc(`${name}-vpc`, {
cidrBlock: args.cidrBlock,
enableDnsHostnames: args.enableDnsHostnames ?? true,
enableDnsSupport: args.enableDnsSupport ?? true,
tags: {
Name: args.vpcName,
},
}, { parent: this });
// Public subnet
this.publicSubnet = new aws.ec2.Subnet(`${name}-public-subnet`, {
vpcId: this.vpc.id,
cidrBlock: "10.0.1.0/24",
availabilityZone: "eu-west-1a",
mapPublicIpOnLaunch: true,
tags: {
Name: `${args.vpcName}-public-subnet`,
},
}, { parent: this });
// Internet Gateway
this.internetGateway = new aws.ec2.InternetGateway(`${name}-igw`, {
vpcId: this.vpc.id,
tags: {
Name: `${args.vpcName}-igw`,
},
}, { parent: this });
// Route Table
this.routeTable = new aws.ec2.RouteTable(`${name}-rt`, {
vpcId: this.vpc.id,
routes: [{
cidrBlock: "0.0.0.0/0",
gatewayId: this.internetGateway.id,
}],
tags: {
Name: `${args.vpcName}-public-rt`,
},
}, { parent: this });
// Route Table Association
new aws.ec2.RouteTableAssociation(`${name}-rta`, {
subnetId: this.publicSubnet.id,
routeTableId: this.routeTable.id,
}, { parent: this });
this.registerOutputs({
vpcId: this.vpc.id,
subnetId: this.publicSubnet.id,
vpcArn: this.vpc.arn,
});
}
}
```
**2. Een herbruikbare EC2-component (`Ec2Component.ts`):**
```typescript
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
export interface Ec2ComponentArgs {
instanceName: string;
instanceType: string;
subnetId: pulumi.Output<string>;
vpcId: pulumi.Output<string>;
amiId?: string;
keyName?: string;
tags?: { [key: string]: string };
}
export class Ec2Component extends pulumi.ComponentResource {
public readonly instance: aws.ec2.Instance;
public readonly securityGroup: aws.ec2.SecurityGroup;
constructor(name: string, args: Ec2ComponentArgs, opts?: pulumi.ComponentResourceOptions) {
super("custom:component:Ec2Component", name, {}, opts);
// Security Group
this.securityGroup = new aws.ec2.SecurityGroup(`${name}-sg`, {
vpcId: args.vpcId,
description: `Security group for ${args.instanceName}`,
ingress: [
{
protocol: "tcp",
fromPort: 22,
toPort: 22,
cidrBlocks: ["0.0.0.0/0"],
},
{
protocol: "tcp",
fromPort: 80,
toPort: 80,
cidrBlocks: ["0.0.0.0/0"],
},
],
egress: [{
protocol: "-1",
fromPort: 0,
toPort: 0,
cidrBlocks: ["0.0.0.0/0"],
}],
tags: {
Name: `${args.instanceName}-sg`,
},
}, { parent: this });
// EC2 Instance
this.instance = new aws.ec2.Instance(`${name}-instance`, {
instanceType: args.instanceType,
vpcSecurityGroupIds: [this.securityGroup.id],
subnetId: args.subnetId,
ami: args.amiId || "ami-0c55b159cbfafe1f0", // Ubuntu 20.04 LTS
keyName: args.keyName,
tags: {
Name: args.instanceName,
...args.tags,
},
}, { parent: this });
this.registerOutputs({
instanceId: this.instance.id,
publicIp: this.instance.publicIp,
privateIp: this.instance.privateIp,
securityGroupId: this.securityGroup.id,
});
}
}
```
**3. Hoofd Pulumi-programma (`index.ts`):**
```typescript
import * as pulumi from "@pulumi/pulumi";
import { VpcComponent } from "./VpcComponent";
import { Ec2Component } from "./Ec2Component";
// Configuratie
const config = new pulumi.Config();
const environment = config.require("environment");
// VPC aanmaken
const vpc = new VpcComponent("main-vpc", {
cidrBlock: "10.0.0.0/16",
vpcName: `main-vpc-${environment}`,
enableDnsHostnames: true,
enableDnsSupport: true,
});
// EC2 instances aanmaken
const instances = [
{ name: "web-server-1", type: "t3.micro" },
{ name: "web-server-2", type: "t3.micro" },
{ name: "app-server", type: "t3.small" },
];
const ec2Instances = instances.map((instance, index) =>
new Ec2Component(`instance-${index}`, {
instanceName: `${instance.name}-${environment}`,
instanceType: instance.type,
subnetId: vpc.publicSubnet.id,
vpcId: vpc.vpc.id,
amiId: "ami-0c55b159cbfafe1f0", // Ubuntu 20.04 LTS
keyName: "my-key-pair",
tags: {
Environment: environment,
Role: instance.name.includes("web") ? "web" : "app",
},
})
);
// Exports
export const vpcId = vpc.vpc.id;
export const subnetId = vpc.publicSubnet.id;
export const instancePublicIps = ec2Instances.map(instance => instance.instance.publicIp);
export const instanceIds = ec2Instances.map(instance => instance.instance.id);
```
**Voordelen van deze herstructurering:**
1. **Herbruikbaarheid**: Componenten kunnen eenvoudig worden hergebruikt in andere projecten
2. **Encapsulatie**: Complexe logica is verborgen in componenten
3. **Configureerbaarheid**: Duidelijke interfaces voor configuratie
4. **Onderhoudbaarheid**: Wijzigingen zijn geïsoleerd tot specifieke componenten
5. **Testbaarheid**: Componenten kunnen afzonderlijk worden getest
6. **Schaalbaarheid**: Eenvoudig meer instances toevoegen via configuratie
**Gebruik:**
```bash
pulumi config set environment dev
pulumi up
```
Deze structuur maakt je infrastructuurcode veel modulairder, beter onderhoudbaar en eenvoudiger uit te breiden.
error: Generation failed [deepseek] prompt_id=1890 locale=en err=DeepSeek connection/timeout