Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";
import { Config } from "@pulumi/pulumi";
console.log("EC2: Update1");
const vpc = new awsx.ec2.Vpc("testing-1");
const cluster1 = new awsx.ecs.Cluster("testing-1", { vpc });
export const clusterId = cluster1.id;
const autoScalingGroup = cluster1.createAutoScalingGroup("testing-1", {
subnetIds: vpc.publicSubnetIds,
templateParameters: {
minSize: 10,
},
launchConfigurationArgs: {
instanceType: "t2.medium",
associatePublicIpAddress: true,
},
});
export const autoScalingGroupId = autoScalingGroup.stack.id;
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";
import { Config } from "@pulumi/pulumi";
console.log("EC2: Original");
const vpc = new awsx.ec2.Vpc("testing-1");
const cluster1 = new awsx.ecs.Cluster("testing-1", { vpc });
export const clusterId = cluster1.id;
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";
import { Config } from "@pulumi/pulumi";
console.log("EC2: Update1");
const vpc = new awsx.ec2.Vpc("testing-1");
const cluster1 = new awsx.ecs.Cluster("testing-1", { vpc });
export const clusterId = cluster1.id;
const autoScalingGroup = cluster1.createAutoScalingGroup("testing-1", {
subnetIds: vpc.publicSubnetIds,
templateParameters: {
minSize: 10,
},
launchConfigurationArgs: {
instanceType: "t2.medium",
associatePublicIpAddress: true,
},
});
export const autoScalingGroupId = autoScalingGroup.stack.id;
function errorJSON(err: any) {
const result: any = Object.create(null);
Object.getOwnPropertyNames(err).forEach(key => result[key] = err[key]);
return result;
}
function handleError(err: Error) {
console.error(errorJSON(err));
return {
statusCode: 500,
body: JSON.stringify(errorJSON(err)),
};
}
// expose some APIs meant for testing purposes.
const api = new awsx.apigateway.API("containers", {
routes: [{
path: "/test",
method: "GET",
eventHandler: async (req) => {
try {
return {
statusCode: 200,
body: JSON.stringify({
nginx: nginxListener.endpoint.get(),
nginx2: builtServiceListener.endpoint.get(),
}),
};
} catch (err) {
return handleError(err);
}
},
const result: any = Object.create(null);
Object.getOwnPropertyNames(err).forEach(key => result[key] = err[key]);
result.florp = "blopr";
return result;
}
function handleError(err: Error) {
console.error(errorJSON(err));
return {
statusCode: 500,
body: JSON.stringify(errorJSON(err)),
};
}
// expose some APIs meant for testing purposes.
const api = new awsx.apigateway.API("containers", {
routes: [{
path: "/test",
method: "GET",
eventHandler: async (req) => {
try {
return {
statusCode: 200,
body: JSON.stringify({
nginx: nginxListener.endpoint.get(),
nginx2: builtServiceListener.endpoint.get(),
}),
};
} catch (err) {
return handleError(err);
}
},
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";
// Create a mapping from 'route' to a count
const counterTable = new aws.dynamodb.Table("counterTable", {
attributes: [{
name: "id",
type: "S",
}],
hashKey: "id",
readCapacity: 5,
writeCapacity: 5,
});
// Create an API endpoint
const endpoint = new awsx.apigateway.API("hello-world", {
routes: [{
path: "/{route+}",
method: "GET",
eventHandler: async (event) => {
const route = event.pathParameters!["route"];
console.log(`Getting count for '${route}'`);
const client = new aws.sdk.DynamoDB.DocumentClient();
// get previous value and increment
// reference outer `counterTable` object
const tableData = await client.get({
TableName: counterTable.name.get(),
Key: { id: route },
ConsistentRead: true,
}).promise();
console.log(`${url}: Processing`);
// Fetch the contents at the URL
console.log(`${url}: Getting`);
try {
const res = await fetch.default(url);
} catch (err) {
console.log(`${url}: Failed to GET`);
return;
}
}
});
let alarmIndex = 0;
const funcMetric = awsx.lambda.metrics.duration({ function: subscription.func, unit: "Seconds" });
const funcAlarm = funcMetric.createAlarm("alarm" + alarmIndex++, { threshold: 120, evaluationPeriods: 2 });
const topicMetric = awsx.sns.metrics.numberOfMessagesPublished({ topic });
const topicAlarm = topicMetric.createAlarm("alarm" + alarmIndex++, { threshold: 1000, evaluationPeriods: 2 });
const queue = new aws.sqs.Queue("terraform_queue", {
delaySeconds: 90,
maxMessageSize: 2048,
messageRetentionSeconds: 86400,
receiveWaitTimeSeconds: 10,
tags: {
Environment: "production",
},
});
const queueMetric = awsx.sqs.metrics.sentMessageSize({ queue });
console.log(`${url}: Processing`);
// Fetch the contents at the URL
console.log(`${url}: Getting`);
try {
const res = await fetch.default(url);
} catch (err) {
console.log(`${url}: Failed to GET`);
return;
}
}
});
// Get the metric for the lambda that processing our topic requests.
const funcMetric = awsx.lambda.metrics.duration({ function: subscription.func });
// Create an alarm if this lambda takes more than 1000ms to complete in a period of 10 minutes over
// at least five periods in a row.
const funcAlarm1 = funcMetric.with({ unit: "Milliseconds", period: 600 })
.createAlarm("SlowUrlProcessing", { threshold: 1000, evaluationPeriods: 5 });
// Also create a dashboard to track this.
const dashboard = new awsx.cloudwatch.Dashboard("TopicData", {
widgets: [
new awsx.cloudwatch.SingleNumberMetricWidget({
title: "Requests in the last minute",
width: 10,
metrics: awsx.lambda.metrics.invocations({
function: subscription.func,
statistic: "Sum",
period: 60,
export function getCluster(): CloudCluster | undefined {
// If no ECS cluster has been initialized, see if we must lazily allocate one.
if (!cluster) {
if (config.ecsAutoCluster) {
// Translate the comma-seperated list into an array or undefined.
let instanceRolePolicyARNs;
if (config.ecsAutoClusterInstanceRolePolicyARNs) {
instanceRolePolicyARNs = (config.ecsAutoClusterInstanceRolePolicyARNs || "").split(",");
}
// If we are asked to provision a cluster, then we will have created a network
// above - create a cluster in that network.
cluster = new awsx.Cluster(createNameWithStackInfo("global"), {
network: getOrCreateNetwork(),
addEFS: config.ecsAutoClusterUseEFS,
instanceType: config.ecsAutoClusterInstanceType,
instanceRolePolicyARNs: instanceRolePolicyARNs,
instanceRootVolumeSize: config.ecsAutoClusterInstanceRootVolumeSize,
instanceDockerImageVolumeSize: config.ecsAutoClusterInstanceDockerImageVolumeSize,
instanceSwapVolumeSize: config.ecsAutoClusterInstanceSwapVolumeSize,
minSize: config.ecsAutoClusterMinSize,
maxSize: config.ecsAutoClusterMaxSize,
publicKey: config.ecsAutoClusterPublicKey,
});
} else if (config.ecsClusterARN) {
// Else if we have an externally provided cluster and can use that.
cluster = {
ecsClusterARN: pulumi.output(config.ecsClusterARN),
securityGroupId: config.ecsClusterSecurityGroup
const pulumi = require("@pulumi/pulumi");
const awsx = require("@pulumi/awsx");
// Create an elastic network listener to listen for requests and route them to the container.
// See https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html
// for more details.
let listener = new awsx.elasticloadbalancingv2.NetworkListener("nginx", { port: 80 });
// Define the service to run. We pass in the listener to hook up the network load balancer
// to the containers the service will launch.
let service = new awsx.ecs.FargateService("nginx", {
desiredCount: 2,
taskDefinitionArgs: {
containers: {
nginx: {
image: awsx.ecs.Image.fromPath("nginx", "./app"),
memory: 512,
portMappings: [listener],
},
},
},
});
exports.frontendURL = pulumi.interpolate `http://${listener.endpoint.hostname}/`;