name: pulumi-basics user-invocable: false description: 使用编程语言通过Pulumi编写基础设施即代码,用于云资源供应。 allowed-tools: []
Pulumi基础
使用真实编程语言通过Pulumi进行基础设施即代码开发。
项目结构
my-infrastructure/
├── Pulumi.yaml # 项目文件
├── Pulumi.dev.yaml # 堆栈配置
├── index.ts # 主程序
└── package.json
Pulumi.yaml
name: my-infrastructure
user-invocable: false
runtime: nodejs
description: 我的基础设施项目
TypeScript示例
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// 创建VPC
const vpc = new aws.ec2.Vpc("main", {
cidrBlock: "10.0.0.0/16",
enableDnsHostnames: true,
tags: {
Name: "main-vpc",
},
});
// 创建子网
const subnet = new aws.ec2.Subnet("public", {
vpcId: vpc.id,
cidrBlock: "10.0.1.0/24",
availabilityZone: "us-east-1a",
});
// 导出输出
export const vpcId = vpc.id;
export const subnetId = subnet.id;
常用命令
# 创建新项目
pulumi new aws-typescript
# 预览变更
pulumi preview
# 应用变更
pulumi up
# 销毁资源
pulumi destroy
# 查看堆栈输出
pulumi stack output
配置
# 设置配置
pulumi config set aws:region us-east-1
# 设置秘密
pulumi config set --secret dbPassword mySecret123
# 获取配置
pulumi config get aws:region
最佳实践
使用堆栈引用
const infraStack = new pulumi.StackReference("org/infra/prod");
const vpcId = infraStack.getOutput("vpcId");
组件资源
class MyApp extends pulumi.ComponentResource {
constructor(name: string, args: MyAppArgs, opts?: pulumi.ComponentResourceOptions) {
super("custom:app:MyApp", name, {}, opts);
// 创建资源
}
}