aws-sdk#EC2 TypeScript Examples
The following examples show how to use
aws-sdk#EC2.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Create)
@commonAws({ serviceName: 'EC2', debug: true })
public async create(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<ResourceModel> {
model.resourceId = 'region-defaults'; // there can only be one
if (model.defaultEbsEncryptionKeyId !== undefined || model.enableEbsEncryptionByDefault !== undefined) {
if (model.enableEbsEncryptionByDefault === true) {
await service.enableEbsEncryptionByDefault().promise();
} else if (model.enableEbsEncryptionByDefault === false) {
await service.disableEbsEncryptionByDefault().promise();
}
if (typeof model.defaultEbsEncryptionKeyId === 'string') {
await service
.modifyEbsDefaultKmsKeyId({
KmsKeyId: model.defaultEbsEncryptionKeyId,
})
.promise();
}
}
return Promise.resolve(model);
}
Example #2
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Update)
@commonAws({ serviceName: 'EC2', debug: true })
public async update(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<ResourceModel> {
const prevModel = new ResourceModel(args.request.previousResourceState);
if (model.enableEbsEncryptionByDefault !== prevModel.enableEbsEncryptionByDefault) {
if (model.enableEbsEncryptionByDefault === true) {
await service.enableEbsEncryptionByDefault().promise();
} else {
await service.disableEbsEncryptionByDefault().promise();
}
}
if (model.defaultEbsEncryptionKeyId !== prevModel.defaultEbsEncryptionKeyId) {
if (typeof model.defaultEbsEncryptionKeyId === 'string') {
await service
.modifyEbsDefaultKmsKeyId({
KmsKeyId: model.defaultEbsEncryptionKeyId,
})
.promise();
} else {
await service.resetEbsDefaultKmsKeyId().promise();
}
}
return Promise.resolve(model);
}
Example #3
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Delete)
@commonAws({ serviceName: 'EC2', debug: true })
public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<null> {
if (model.enableEbsEncryptionByDefault === true) {
await service.disableEbsEncryptionByDefault().promise();
}
if (typeof model.defaultEbsEncryptionKeyId === 'string') {
await service.resetEbsDefaultKmsKeyId().promise();
}
return Promise.resolve(null);
}
Example #4
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
/**
* CloudFormation invokes this handler when the resource is initially created
* during stack create operations.
*/
@handlerEvent(Action.Create)
@commonAws({ serviceName: 'EC2', debug: true })
public async create(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<ResourceModel> {
const { desiredResourceState, logicalResourceIdentifier, awsAccountId, region } = args.request;
args.logger.log({ method: 'before create handler', desiredResourceState, logicalResourceIdentifier, awsAccountId, region });
if (model.resourceId) {
throw new exceptions.InvalidRequest('Resource identifier cannot be provided during creation.');
}
model.resourceId = `arn:community:${region}:${awsAccountId}:ec2:no-default-vpc/${uuidv4()}`;
const accountAttributes = await service.describeAccountAttributes({ AttributeNames: ['default-vpc'] }).promise();
args.logger.log({ method: 'create handler', accountAttributes });
const defaultVpcAttribute = accountAttributes.AccountAttributes.find((x) => x.AttributeName === 'default-vpc');
if (defaultVpcAttribute) {
for (const valueContainer of defaultVpcAttribute.AttributeValues) {
const vpcId = valueContainer.AttributeValue;
if (vpcId === 'none') {
// This will be set to none whenever another resource exists
// or when there is no default VPC.
throw new exceptions.AlreadyExists(this.typeName, awsAccountId);
}
args.logger.log({ method: 'before deleteVpc', vpcId });
await deleteVpc(service, args.logger, vpcId);
}
}
args.logger.log({ method: 'done create handler', model });
return Promise.resolve(model);
}
Example #5
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
@handlerEvent(Action.Delete)
@commonAws({ serviceName: 'EC2', debug: true })
public async delete(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<null> {
const { desiredResourceState, logicalResourceIdentifier } = args.request;
try {
args.logger.log({ method: 'before delete handler', desiredResourceState, logicalResourceIdentifier });
await service.createDefaultVpc({}).promise();
args.logger.log({ method: 'after delete handler' });
return Promise.resolve(null);
} catch (err) {
if (err && err.code === 'DefaultVpcAlreadyExists') {
throw new exceptions.NotFound(this.typeName, model.resourceId || logicalResourceIdentifier);
} else {
throw err;
}
}
}
Example #6
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
deleteInternetGateways = async (service: EC2, logger: Logger, vpcId: string) => {
try {
const filters: FilterList = [
{
Name: 'attachment.vpc-id',
Values: [vpcId],
},
];
logger.log({ method: 'before deleteInternetGateways', vpcId });
const internetGateways = await service.describeInternetGateways({ Filters: filters }).promise();
for (const ig of internetGateways.InternetGateways) {
logger.log({ method: 'before detachInternetGateway', vpcId, ig });
await service.detachInternetGateway({ InternetGatewayId: ig.InternetGatewayId, VpcId: vpcId }).promise();
logger.log({ method: 'before deleteInternetGateway', vpcId, ig });
await service.deleteInternetGateway({ InternetGatewayId: ig.InternetGatewayId }).promise();
}
logger.log({ method: 'after deleteInternetGateways', vpcId });
} catch (err) {
logger.log({ method: 'catch deleteInternetGateways', vpcId, err });
throw err;
}
}
Example #7
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
deleteRouteTables = async (service: EC2, logger: Logger, filters: FilterList) => {
try {
logger.log({ method: 'before deleteRouteTables', filters });
const routeTables = await service.describeRouteTables({ Filters: filters }).promise();
for (const rt of routeTables.RouteTables) {
const main = rt.Associations.findIndex((x) => x.Main);
if (main != -1) continue;
logger.log({ method: 'before deleteRouteTable', rt });
await service.deleteRouteTable({ RouteTableId: rt.RouteTableId }).promise();
}
logger.log({ method: 'after deleteRouteTables', filters });
} catch (err) {
logger.log({ method: 'catch deleteRouteTables', filters, err });
throw err;
}
}
Example #8
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
deleteNetworkAcls = async (service: EC2, logger: Logger, filters: FilterList) => {
try {
logger.log({ method: 'before deleteNetworkAcls', filters });
const networkAcls = await service.describeNetworkAcls({ Filters: filters }).promise();
for (const na of networkAcls.NetworkAcls) {
if (na.IsDefault) continue;
logger.log({ method: 'before deleteNetworkAcl', na });
await service.deleteNetworkAcl({ NetworkAclId: na.NetworkAclId }).promise();
}
logger.log({ method: 'after deleteNetworkAcls', filters });
} catch (err) {
logger.log({ method: 'catch deleteNetworkAcls', filters, err });
throw err;
}
}
Example #9
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
deleteSubnets = async (service: EC2, logger: Logger, filters: FilterList) => {
try {
logger.log({ method: 'before deleteSubnets', filters });
const subnets = await service.describeSubnets({ Filters: filters }).promise();
for (const sn of subnets.Subnets) {
logger.log({ method: 'before deleteSubnet', sn });
await service.deleteSubnet({ SubnetId: sn.SubnetId }).promise();
}
logger.log({ method: 'after deleteSubnets', filters });
} catch (err) {
logger.log({ method: 'catch deleteSubnets', filters, err });
throw err;
}
}
Example #10
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
deleteSecurityGroups = async (service: EC2, logger: Logger, filters: FilterList) => {
try {
logger.log({ method: 'before deleteSecurityGroups', filters });
const securityGroups = await service.describeSecurityGroups({ Filters: filters }).promise();
for (const sg of securityGroups.SecurityGroups) {
if (sg.GroupName === 'default') continue;
logger.log({ method: 'before deleteSecurityGroup', sg });
await service.deleteSecurityGroup({ GroupId: sg.GroupId }).promise();
}
logger.log({ method: 'after deleteSecurityGroups', filters });
} catch (err) {
logger.log({ method: 'catch deleteSecurityGroups', filters, err });
throw err;
}
}
Example #11
Source File: handlers.ts From aws-resource-providers with MIT License | 6 votes |
deleteVpc = async (service: EC2, logger: Logger, vpcId: string) => {
try {
logger.log({ method: 'before deleteVpc', vpcId });
const filters: FilterList = [
{
Name: 'vpc-id',
Values: [vpcId],
},
];
logger.log({ method: 'before describeNetworkInterfaces', filters });
const response = await service.describeNetworkInterfaces({ Filters: filters }).promise();
if (response.NetworkInterfaces.length > 0) {
logger.log({ method: 'before throw in use exception', networkInterfaces: response.NetworkInterfaces });
const list = response.NetworkInterfaces.join(', ');
throw new exceptions.InvalidRequest(`Unable to delete default VPC, there is network interfaces attached (${list})`);
}
await deleteInternetGateways(service, logger, vpcId);
await deleteSubnets(service, logger, filters);
await deleteRouteTables(service, logger, filters);
await deleteNetworkAcls(service, logger, filters);
await deleteSecurityGroups(service, logger, filters);
logger.log({ method: 'before actual deleteVpc', vpcId });
await service.deleteVpc({ VpcId: vpcId }).promise();
logger.log({ method: 'after deleteVpc', vpcId });
} catch (err) {
logger.log({ method: 'catch deleteVpc', vpcId, err });
throw err;
}
}
Example #12
Source File: handlers.test.ts From aws-resource-providers with MIT License | 5 votes |
describe('when calling handler', () => {
let testEntrypointPayload: any;
let spySession: jest.SpyInstance;
let spySessionClient: jest.SpyInstance;
let ec2: AwsServiceMockBuilder<EC2>;
let fixtureMap: Map<Action, Record<string, any>>;
beforeAll(() => {
fixtureMap = new Map<Action, Record<string, any>>();
fixtureMap.set(Action.Create, createFixture);
fixtureMap.set(Action.Read, readFixture);
fixtureMap.set(Action.Update, updateFixture);
fixtureMap.set(Action.Delete, deleteFixture);
});
beforeEach(async () => {
ec2 = on(EC2, { snapshot: false });
ec2.mock('enableEbsEncryptionByDefault').resolve({});
ec2.mock('disableEbsEncryptionByDefault').resolve({});
ec2.mock('modifyEbsDefaultKmsKeyId').resolve({});
ec2.mock('resetEbsDefaultKmsKeyId').resolve({});
spySession = jest.spyOn(SessionProxy, 'getSession');
spySessionClient = jest.spyOn<any, any>(SessionProxy.prototype, 'client');
spySessionClient.mockReturnValue(ec2.instance);
testEntrypointPayload = {
credentials: { accessKeyId: '', secretAccessKey: '', sessionToken: '' },
region: 'us-east-1',
action: 'CREATE',
};
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
test('create operation successful - ec2 ebs encryption defaults', async () => {
const request = fixtureMap.get(Action.Create);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('update operation successful - ec2 ebs encryption defaults', async () => {
const request = fixtureMap.get(Action.Update);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Update, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('delete operation successful - ec2 ebs encryption defaults', async () => {
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel).toBeNull();
});
test('read operation successful - ec2 ebs encryption defaults', async () => {
const request = fixtureMap.get(Action.Read);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('all operations fail without session - ec2 ebs encryption defaults', async () => {
expect.assertions(fixtureMap.size);
spySession.mockReturnValue(null);
for (const [action, request] of fixtureMap) {
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action, request }, null);
expect(progress.errorCode).toBe(exceptions.InvalidCredentials.name);
}
});
});
Example #13
Source File: handlers.ts From aws-resource-providers with MIT License | 5 votes |
@handlerEvent(Action.Read)
@commonAws({ serviceName: 'EC2', debug: true })
public async read(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<ResourceModel> {
return Promise.resolve(model);
}
Example #14
Source File: handlers.ts From aws-resource-providers with MIT License | 5 votes |
@handlerEvent(Action.Read)
@commonAws({ serviceName: 'EC2', debug: true })
public async read(action: Action, args: HandlerArgs<ResourceModel>, service: EC2, model: ResourceModel): Promise<ResourceModel> {
return Promise.resolve(model);
}
Example #15
Source File: handlers.test.ts From aws-resource-providers with MIT License | 4 votes |
describe('when calling handler', () => {
let testEntrypointPayload: any;
let spySession: jest.SpyInstance;
let spySessionClient: jest.SpyInstance;
let ec2: AwsServiceMockBuilder<EC2>;
let fixtureMap: Map<Action, Record<string, any>>;
beforeAll(() => {
fixtureMap = new Map<Action, Record<string, any>>();
fixtureMap.set(Action.Create, createFixture);
fixtureMap.set(Action.Read, readFixture);
fixtureMap.set(Action.Delete, deleteFixture);
});
beforeEach(async () => {
ec2 = on(EC2, { snapshot: false });
ec2.mock('createDefaultVpc').resolve({});
ec2.mock('describeAccountAttributes').resolve({
AccountAttributes: [
{
AttributeName: 'default-vpc',
AttributeValues: [
{
AttributeValue: 'vpc-1a2b3c4d',
},
],
},
],
});
ec2.mock('describeNetworkInterfaces').resolve({ NetworkInterfaces: [] });
ec2.mock('describeInternetGateways').resolve({ InternetGateways: [] });
ec2.mock('describeRouteTables').resolve({ RouteTables: [] });
ec2.mock('describeNetworkAcls').resolve({ NetworkAcls: [] });
ec2.mock('describeSubnets').resolve({ Subnets: [] });
ec2.mock('describeSecurityGroups').resolve({ SecurityGroups: [] });
ec2.mock('deleteVpc').resolve({});
spySession = jest.spyOn(SessionProxy, 'getSession');
spySessionClient = jest.spyOn<any, any>(SessionProxy.prototype, 'client');
spySessionClient.mockReturnValue(ec2.instance);
testEntrypointPayload = {
credentials: { accessKeyId: '', secretAccessKey: '', sessionToken: '' },
region: 'us-east-1',
action: 'CREATE',
};
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
test('create operation successful - ec2 no default vpc', async () => {
const request = fixtureMap.get(Action.Create);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
const resourceId = `arn:community:us-east-1:123456789012:ec2:no-default-vpc/${IDENTIFIER}`;
expect(progress.resourceModel.serialize()).toMatchObject({ ...request.desiredResourceState, ResourceId: resourceId });
});
test('create operation fail already exists - ec2 no default vpc', async () => {
const mockDescribe = ec2.mock('describeAccountAttributes').resolve({
AccountAttributes: [
{
AttributeName: 'default-vpc',
AttributeValues: [
{
AttributeValue: 'none',
},
],
},
],
});
const request = fixtureMap.get(Action.Create);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Create, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.AlreadyExists.name });
expect(mockDescribe.mock).toHaveBeenCalledTimes(1);
});
test('read operation successful - ec2 no default vpc', async () => {
const request = fixtureMap.get(Action.Read);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Read, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel.serialize()).toMatchObject(request.desiredResourceState);
});
test('delete operation successful - ec2 no default vpc', async () => {
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Success, message: '', callbackDelaySeconds: 0 });
expect(progress.resourceModel).toBeNull();
});
test('delete operation fail not found - ec2 no default vpc', async () => {
const mockCreate = ec2.mock('createDefaultVpc').reject({
...new Error(),
code: 'DefaultVpcAlreadyExists',
});
const request = fixtureMap.get(Action.Delete);
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action: Action.Delete, request }, null);
expect(progress).toMatchObject({ status: OperationStatus.Failed, errorCode: exceptions.NotFound.name });
expect(mockCreate.mock).toHaveBeenCalledTimes(1);
});
test('all operations fail without session - ec2 no default vpc', async () => {
expect.assertions(fixtureMap.size);
spySession.mockReturnValue(null);
for (const [action, request] of fixtureMap) {
const progress = await resource.testEntrypoint({ ...testEntrypointPayload, action, request }, null);
expect(progress.errorCode).toBe(exceptions.InvalidCredentials.name);
}
});
});