SSM 文档 CDK
该库为SSM文档的执行提供了基于代码的效用. SSM文档对象可用于打印YAML/JSON文档并模仿本地文档处理.
本图书馆对SSM文件进行高层次摘要,每一步骤及文件本身均为对象。 构建这些对象所需的属性与适用于这些对象的设置相关,使其制作简单. 此库可用于在本地测试您的文档, 然后再将其应用到 SSM 上 .
由于该图书馆用JSII写出,因此可以被导出到支持JSII的其他语言(Java,Python).
这就是你想用的东西:
- 在AWS上不部署资源或执行实际的SSM的能力.
- 通过重新使用现有项目使文件之间的步骤得以重复使用
- 创建可重复使用的步组( “ Patterns ” ) 的逻辑更高层次分组
- 用于编写文档的简单接口
- 从文件( 或字符串) 导入已有的文档, 并在当地模仿它们进行测试 .
使用量
文档创建
键入符使用 (Execute AWS API step)... 以下创建 AWS CDK 堆栈中的自动化文件 .
import { AutomationDocument } from './automation-document';
export class HelloWorld extends Stack {
constructor(app: Construct, id: string) {
super(app, id);
// Create AutomationDocument
const myDoc = new AutomationDocument(this, "MyDoc", {
documentFormat: DocumentFormat.JSON,
documentName: "MyDoc",
docInputs: [Input.ofTypeString('MyInput', { defaultValue: 'a' })],
});
// Define your steps...
myDoc.addStep(new PauseStep(this, "MyPauseStep", {
name: "MyPauseStep",
explicitNextStep: StepRef.fromName("step1") // Optional (will default to next added step)
}));
myDoc.addStep(new ExecuteScriptStep(this, "MyExecuteStep", {
name: "step1",
language: ScriptLanguage.python(PythonVersion.VERSION_3_11, 'my_func'),
code: ScriptCode.fromFile(resolve("test/test_file.py")),
// OR ScriptCode.inline("def my_func(args, context):\n return {'MyReturn': args['MyInput'] + '-suffix'}\n"),
outputs: [{
outputType: DataTypeEnum.STRING,
name: "MyFuncOut",
selector: "$.Payload.MyReturn"
}],
onFailure: OnFailure.abort(),
inputPayload: { MyInput: StringVariable.of('MyInput') },
}));
}
}
JSON/YAML 文档导出为 YAML/ JSON
您可以使用 CDK 来部署上述文档. 要将上述文档对象打印为JSON(或YAML),请做如下操作:
const myDocJson = myDoc.print(); // Print YAML by setting the documentFormat to YAML
文件模拟
要在模拟模式下运行文档对象,请使用以下操作. 模拟模式不会击中SSM API,而是模仿了在SSM执行中会发生的处决. 运行发生在本地并允许您对外部服务(例如AWS API)的调用进行嘲弄,或者使用您的本地证书引用这些服务.
import { Simulation } from './simulation';
const myDocJson = Simulation.ofAutomation(myDoc, {}).simulate({ MyInput: "FooBar" });
命令文档
下面是使用库创建命令文档的例子. 对于所有命令插件,尚不支持命令文档的模拟. 您可以使用 Docker 图像/ 容器作为游乐场, 用于测试 Command 文档执行 .
在这个例子中有一个完整的CDK堆栈. 注意到 CommandDocument 以字段保存,以便从测试代码中测试.
export class HelloCdkStack extends Stack {
readonly myCommandDoc: CommandDocument;
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
this.myCommandDoc = new CommandDocument(this, "MyCommandDoc", {
docInputs: [Input.ofTypeString('FirstCommand', { defaultValue: 'a' })],
})
const runScriptStep = new RunShellScriptStep(this, "MyShellScript", {
runCommand: [
StringVariable.of("FirstCommand"),
HardCodedString.of("mkdir asdf"),
],
});
this.myCommandDoc.addStep(runScriptStep);
}
}
下面是一个例子,你将如何运行 一个模拟上面 CommandDocument。 。 。 .
目前, bash 必须在容器中提供,否则对吊工的处决不会成功.
test('Test command doc', () => {
const app = new cdk.App();
const stack = new HelloCdk.HelloCdkStack(app, 'MyTestStack');
// 1. $ docker pull amazonlinux
// 2. $ docker run -di amazonlinux
const simulation = Simulation.ofCommand(stack.myCommandDoc, {
simulationPlatform: Platform.LINUX,
environment: DockerEnvironment.fromContainer('MY_CONTAINER_ID')
});
simulation.simulate({FirstCommand: 'mkdir foobar'})
// 3. The document should run the first command (create 'foobar') and create file 'asdf'
// 4. $ docker exec -it <container name> bash
// 5. Ensure that 'asdf' and 'foobar' were written to /tmp
});
模式( 高级构造)
在典型的CDK风格中,可以将经常被用过的步组组组组装入更高级的构造.
考虑是否通常创建自动文档, 开始记录时间, 结束记录全部时间 。 您可以创建高级自动化文档,并在实施自动化时扩展该文档.
见 TimedDocument (c) 要求执行《公约》.
或者考虑多个步骤的情况,这些步骤总是一起运行,例如重启和实例,并等待其活动.
以下示例来自 RebootInstanceAndWait 类 :
export class RebootInstanceAndWait extends CompositeAutomationStep {
readonly reboot: AwsApiStep;
readonly describe: WaitForResourceStep;
constructor(scope: Construct, id: string, instanceId: IStringVariable) {
super(scope, id);
this.reboot = new AwsApiStep(this, 'RebootInstances', {
service: AwsService.EC2,
pascalCaseApi: 'RebootInstances',
apiParams: { InstanceIds: [instanceId] },
outputs: [],
});
this.describe = new WaitForResourceStep(this, 'DescribeInstances', {
service: AwsService.EC2,
pascalCaseApi: 'DescribeInstances',
apiParams: { InstanceIds: [instanceId] },
selector: '$.Reservations[0].Instances[0].State.Name',
desiredValues: ['running'],
});
}
addToDocument(doc: AutomationDocumentBuilder): void {
doc.addStep(this.reboot);
doc.addStep(this.describe);
}
}
现在,你可以使用 RebootInstanceAndWait 作为文件中的一个步骤,将列入儿童步骤.
现有文件
您是否有一个可用模拟转换为代码和/或本地测试的现有文档 ?
导入已存在的文档
以下是您如何导入一个已有文档, 然后在本地模拟它, 使用被模拟的 AWS 资源的例子 :
// Initialize Mocks
const sleeper = new MockSleep();
const awsInvoker = new MockAwsInvoker();
awsInvoker.whenThen(
// when invoked with...
{awsApi: 'listBuckets', awsParams: {}, service: AwsService.S3},
// then response with...
{Owner: {ID: "BUCKET_ID"}})
// ======> Create document from file <=======
const stack: Stack = new Stack();
const myAutomationDoc = StringDocument.fromFile(stack, "MyAutomationDoc", 'test/myAutomation.json', {
// ======================
});
// Execute simulation
const simOutput = Simulation.ofAutomation(myAutomationDoc, {
sleepHook: sleeper,
awsInvoker: awsInvoker
}).simulate({});
// Assert simulation result
assert.deepEqual(awsInvoker.previousInvocations, [
{ awsApi: 'listBuckets', awsParams: {}, service: AwsService.S3 }]);
assert.deepEqual(sleeper.sleepMilliInvocations, [3000]);
assert.deepEqual(simOutput.outputs['simulationSteps'], ['MySleep', 'GetBucketId']);
导入已存在的步骤
也可以抓取字符串步骤(或步骤)并导入为 CDK 步骤构造. 这可用于将已有的文档转换为CDK,每个步骤都单独定义. 这将允许您修改步骤,并在其他文档中重复使用.
以下是一个简单的睡眠步骤副本的例子
StringStep.fromYaml(this, `
name: sleep
action: aws:sleep
inputs:
Duration: PT0M
`, {});
以上将返回 CDK 构造 SleepStep .
事件管理器
这个库为事件响应提供L2构造如下:
new IncidentResponse(this, "MyIncidentResponsePlan", {
incidentTemplate: IncidentTemplate.critical('EC2 Instance Utilization Impacted', {
summary: 'EC2 Instance Impacted'
}),
actions: [
IncidentResponseAction.ssmAutomation(myAutomationDoc, ec2CwAlarmRole, {
parameters: {
IncidentRecordArn: StringVariable.of('INCIDENT_RECORD_ARN'),
InvolvedResources: StringVariable.of('INVOLVED_RESOURCES'),
AutomationAssumeRole: HardCodedString.of(ec2CwAlarmRole.roleArn),
}
})
]
});
注意到如何 myAutomationDoc 指的是使用此库创建的自动化文件.
什么是计划?
此库目前包含自动化文档和命令文档步骤 . 完全支持自动化文件的模拟。 命令文件的模拟有限.
继续听!
相关项目
警卫
见 捐款 更多信息.
许可证
这个项目根据Apache-2.0许可证获得许可证.