Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
// Copyright 2016-2017, Pulumi Corporation. All rights reserved.
import * as aws from "@pulumi/aws";
import * as other from "./other/index"
// Validate that 'require'd packages are captured correctly.
function getContentType() {
let mime = require('mime-types');
return mime.contentType(".js");
}
const testFunc = new aws.serverless.Function("f", {
policies: [aws.iam.AWSLambdaFullAccess],
includePaths: ['./Pulumi.yaml'],
}, async (ev, ctx, cb) => {
var aws = await import('aws-sdk');
var express = await import('express');
var os = require('os');
var slack = require('@slack/client');
var answer = other.answer;
console.log(answer);
getContentType();
});
exports.functionARN = testFunc.lambda.arn;
let globalInfrastructureResource: InfrastructureResource | undefined;
export function getGlobalInfrastructureResource(): pulumi.Resource {
if (!globalInfrastructureResource) {
globalInfrastructureResource = new InfrastructureResource();
}
return globalInfrastructureResource;
}
// Whether or not we should run lamabda-based compute in the private network
export let runLambdaInVPC: boolean = config.usePrivateNetwork;
// The IAM Role Policies to apply to compute for both Lambda and ECS
const defaultComputePolicies = [
aws.iam.AWSLambdaFullAccess, // Provides wide access to "serverless" services (Dynamo, S3, etc.)
aws.iam.AmazonEC2ContainerServiceFullAccess, // Required for lambda compute to be able to run Tasks
];
let computePolicies: aws.ARN[] = config.computeIAMRolePolicyARNs
? config.computeIAMRolePolicyARNs.split(",")
: defaultComputePolicies;
let computePoliciesAccessed = false;
// Set the IAM policies to use for compute.
export function setComputeIAMRolePolicies(policyARNs: string[]) {
if (computePoliciesAccessed) {
throw new RunError(
"The compute policies have already been used, make sure you are setting IAM policies early enough.");
}
computePolicies = policyARNs;
}
instanceRoleMappings = pulumi.output(args.instanceRole).apply(instanceRole =>
[createInstanceRoleMapping(instanceRole.arn)],
);
} else {
const instanceRole = (new ServiceRole(`${name}-instanceRole`, {
service: "ec2.amazonaws.com",
managedPolicyArns: [
"arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy",
"arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy",
"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
],
}, { parent: parent })).role;
// Create a new policy for the role, if specified.
if (args.customInstanceRolePolicy) {
const customRolePolicy = new aws.iam.RolePolicy(`${name}-EKSWorkerCustomPolicy`, {
role: instanceRole,
policy: args.customInstanceRolePolicy,
});
}
// Create an instance profile if using a default node group
if (!args.skipDefaultNodeGroup) {
instanceProfile = new aws.iam.InstanceProfile(`${name}-instanceProfile`, {
role: instanceRole,
}, { parent: parent });
}
instanceRoleMappings = pulumi.output(instanceRole).apply(role =>
[createInstanceRoleMapping(role.arn)],
);
}
constructor(name: string, handler: aws.serverless.Handler, opts?: pulumi.ResourceOptions) {
super("cloud:function:Function", name, { handler: handler }, opts);
// First allocate a function.
const options: aws.serverless.FunctionOptions = {
policies: [...getComputeIAMRolePolicies()],
deadLetterConfig: {
targetArn: getUnhandledErrorTopic().arn,
},
memorySize: functionMemorySize,
};
if (runLambdaInVPC) {
const network: Network | undefined = getNetwork();
// TODO[terraform-providers/terraform-provider-aws#1507]: Updates which cause existing Lambdas to need to
// add VPC access will currently fail due to an issue in the Terraform provider.
options.policies.push(aws.iam.AWSLambdaVPCAccessExecutionRole);
options.vpcConfig = {
securityGroupIds: network!.securityGroupIds,
subnetIds: network!.subnetIds,
};
}
this.lambda = new aws.serverless.Function(name, options, handler, { parent: this }).lambda;
// And then a log group and subscription filter for that lambda.
const _ = new aws.cloudwatch.LogSubscriptionFilter(name, {
logGroup: new aws.cloudwatch.LogGroup(name, {
name: this.lambda.name.then((n: string | undefined) => n && ("/aws/lambda/" + n)),
retentionInDays: 1,
}, { parent: this }),
destinationArn: getLogDestinationArn(),
filterPattern: "",
}, { parent: this });
const adminsIamRolePolicy = new aws.iam.RolePolicy(`${adminsName}-eksClusterAdminPolicy`, {
role: adminsIamRole,
policy: {
Version: "2012-10-17",
Statement: [
{ Effect: "Allow", Action: ["eks:*", "ec2:DescribeImages"], Resource: "*", },
{ Effect: "Allow", Action: "iam:PassRole", Resource: "*"},
],
},
},
{ parent: adminsIamRole },
);
// Create the EKS cluster developers role.
const devName = "devs";
const devsIamRole = new aws.iam.Role(`${devName}-eksClusterDeveloper`, {
assumeRolePolicy: aws.getCallerIdentity().then(id =>
aws.iam.assumeRolePolicyForPrincipal({"AWS": `arn:aws:iam::${id.accountId}:root`}))
})
export const devsIamRoleArn = devsIamRole.arn;
// Create the standard node group worker role and attach the required policies.
const stdName = "standardNodeGroup";
const stdNodegroupIamRole = new aws.iam.Role(`${stdName}-eksClusterWorkerNode`, {
assumeRolePolicy: aws.iam.assumeRolePolicyForPrincipal({"Service": "ec2.amazonaws.com"})
})
attachPoliciesToRole(stdName, stdNodegroupIamRole, nodegroupManagedPolicyArns);
export const stdNodegroupIamRoleArn = stdNodegroupIamRole.arn;
// Create the performant node group worker role and attach the required policies.
const perfName = "performanceNodeGroup";
const perfNodegroupIamRole = new aws.iam.Role(`${perfName}-eksClusterWorkerNode`, {
args.defineDatabaseAdminsGroup === undefined ? true : args.defineDatabaseAdminsGroup;
args.defineBillingGroup =
args.defineBillingGroup === undefined ? true : args.defineBillingGroup;
args.defineSecurityAuditorsGroup =
args.defineSecurityAuditorsGroup === undefined
? true
: args.defineSecurityAuditorsGroup;
args.defineReadOnlyGroup =
args.defineReadOnlyGroup === undefined ? true : args.defineReadOnlyGroup;
//
// Administrators.
//
this.admins = this.defineGroup(args.defineAdminsGroup, "admins", {
administratorAccess: aws.iam.AdministratorAccess,
});
this.networkAdmins = this.defineGroup(args.defineNetworkAdminsGroup, "networkAdmins", {
networkAdministrator: aws.iam.NetworkAdministrator,
});
this.databaseAdmins = this.defineGroup(args.defineDatabaseAdminsGroup, "databaseAdmins", {
databaseAdministrator: aws.iam.DatabaseAdministrator,
});
this.eksAdmins = this.defineGroup(args.defineEksAdminsGroup, "eksAdmins", {
administratorAccess: aws.iam.AdministratorAccess,
});
//
// Billing and auditing.
constructor(name: string, opts?: pulumi.ResourceOptions) {
super("cloud:logCollector:LogCollector", name, opts);
const collector = new aws.serverless.Function(
name,
{ policies: [ aws.iam.AWSLambdaFullAccess ] },
async (ev: LogsPayload, ctx: aws.serverless.Context, cb: (error: any, result?: {}) => void) => {
try {
const zlib = await import("zlib");
const payload = new Buffer(ev.awslogs.data, "base64");
const result = zlib.gunzipSync(payload);
console.log(result.toString("utf8"));
cb(null, {});
} catch (err) {
cb(err);
}
},
{ parent: this },
);
this.lambda = collector.lambda;
const region = aws.config.requireRegion();
function getInstanceProfile(parent: mod.Cluster, args: ClusterAutoScalingLaunchConfigurationArgs) {
if (args.instanceProfile) {
return args.instanceProfile;
}
const parentOpts = { parent };
const instanceRole = new aws.iam.Role(name, {
assumeRolePolicy: JSON.stringify(defaultAssumeInstanceRolePolicyDoc),
}, parentOpts);
const policyARNs = [aws.iam.AmazonEC2ContainerServiceforEC2Role, aws.iam.AmazonEC2ReadOnlyAccess];
const instanceRolePolicies: aws.iam.RolePolicyAttachment[] = [];
for (let i = 0; i < policyARNs.length; i++) {
const policyARN = policyARNs[i];
instanceRolePolicies.push(new aws.iam.RolePolicyAttachment(`${name}-${sha1hash(policyARN)}`, {
role: instanceRole,
policyArn: policyARN,
}, parentOpts));
}
return new aws.iam.InstanceProfile(name, {
role: instanceRole,
export function createIamRole(name: string, table: aws.dynamodb.Table) {
const role = new aws.iam.Role(`${name}-role`, {
assumeRolePolicy: aws.iam.getPolicyDocument({
statements: [{
actions: ["sts:AssumeRole"],
principals: [{
identifiers: ["appsync.amazonaws.com"],
type: "Service",
}],
effect: "Allow",
}],
}, { async: true }).then(doc => doc.json),
});
const policy = new aws.iam.Policy(`${name}-policy`, {
policy: table.arn.apply(arn => aws.iam.getPolicyDocument({
statements: [{
actions: ["dynamodb:PutItem", "dynamodb:GetItem"],
resources: [arn],
export function createRoleAndPolicies(
name: string,
assumeRolePolicy: string | aws.iam.PolicyDocument,
policyArns: string[],
opts: pulumi.ComponentResourceOptions | undefined) {
if (typeof assumeRolePolicy !== "string") {
assumeRolePolicy = JSON.stringify(assumeRolePolicy);
}
const role = new aws.iam.Role(name, { assumeRolePolicy }, opts);
const policies: aws.iam.RolePolicyAttachment[] = [];
for (let i = 0; i < policyArns.length; i++) {
const policyArn = policyArns[i];
policies.push(new aws.iam.RolePolicyAttachment(
`${name}-${utils.sha1hash(policyArn)}`, { role, policyArn }, opts));
}
return { role, policies };
}