public Role GetRole(Construct scope, string roleId, string[] ManagedPolicyArns, string[] PrincipalServices, string PolicyName) { var roleProps = new RoleProps { Path = "/", AssumedBy = new ServicePrincipal(PrincipalServices[0]) }; if (PrincipalServices.Length > 0) { List <PrincipalBase> principalBases = new List <PrincipalBase>(); foreach (string service in PrincipalServices) { PrincipalBase principalBase = new ServicePrincipal(service); principalBases.Add(principalBase); } var compositePrincipal = new CompositePrincipal(principalBases.ToArray()); roleProps = new RoleProps { Path = "/", AssumedBy = compositePrincipal }; } var iamRole = new Role(scope, roleId, roleProps); foreach (string arn in ManagedPolicyArns) { iamRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName(arn)); } return(iamRole); }
internal BastionStack(Construct scope, string id, Vpc vpc, string keyPairName, IStackProps props = null) : base(scope, id, props) { Role = new Role(this, "ec2-bastion-role", new RoleProps { AssumedBy = new ServicePrincipal("ec2.amazonaws.com") }); Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("SecretsManagerReadWrite")); Bastion = new Instance_(this, id, new InstanceProps { InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO), MachineImage = new WindowsImage(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE), Vpc = vpc, UserData = UserData.Custom(Utils.GetResource("bastion_user_data.ps1")), KeyName = keyPairName, Role = Role, VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PUBLIC } }); Bastion.Connections.AllowFromAnyIpv4(Port.Tcp(3389), "Internet access RDP"); new CfnOutput(this, "Bastion Host", new CfnOutputProps { Value = Bastion.InstancePublicDnsName }); }
private Role createLambdaRole() { Role role = new Role(this, "LambdaRole", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); role.AddManagedPolicy( ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole") ); role.AddManagedPolicy( ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaVPCAccessExecutionRole") ); return(role); }
internal MailBotStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { //Secrets Manager //IAM //IAM - Role - mailbot //IAM - Role - StepFunctions //IAM - Role - StepFunctions - CloudWatchFullAccess //IAM - Role - StepFunctions - AWS Lambda Role //IAM - Role - StepFunctions - TAGS Role role = new Role(this, "StepFunctions", new RoleProps { AssumedBy = new ServicePrincipal("ec2.amazonaws.com"), Description = "Role for Step Functions", }); role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchFullAccess")); //role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AWSLambdaRole")); //User user = new User(this, "MyUser", new UserProps { Password = SecretValue.PlainText("1234") }); //Group group = new Group(this, "MyGroup"); //Policy policy = new Policy(this, "MyPolicy"); //policy.AttachToUser(user); //group.AttachInlinePolicy(policy); ////Register domain ////Verify SES //Bucket emailsBucket = new Bucket(this, "emails", new BucketProps //{ //}); //Bucket updatesBucket = new Bucket(this, "updates", new BucketProps //{ //}); //Bucket attachmentsBucket = new Bucket(this, "attachments", new BucketProps //{ //}); //Bucket quarantineBucket = new Bucket(this, "quarantine", new BucketProps //{ //}); }
private void ConfigureIAMRoles(Configuration settings) { if (settings.ServiceAccessIAMRole.CreateNew) { ServiceAccessRole = new Role(this, nameof(ServiceAccessRole), InvokeCustomizeCDKPropsEvent(nameof(ServiceAccessRole), this, new RoleProps { AssumedBy = new ServicePrincipal("build.apprunner.amazonaws.com") })); ServiceAccessRole.AddManagedPolicy(ManagedPolicy.FromManagedPolicyArn(this, "ServiceAccessRoleManagedPolicy", "arn:aws:iam::aws:policy/service-role/AWSAppRunnerServicePolicyForECRAccess")); } else { if (string.IsNullOrEmpty(settings.ServiceAccessIAMRole.RoleArn)) { throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); } ServiceAccessRole = Role.FromRoleArn(this, nameof(ServiceAccessRole), settings.ServiceAccessIAMRole.RoleArn, new FromRoleArnOptions { Mutable = false }); } if (settings.ApplicationIAMRole.CreateNew) { TaskRole = new Role(this, nameof(TaskRole), InvokeCustomizeCDKPropsEvent(nameof(TaskRole), this, new RoleProps { AssumedBy = new ServicePrincipal("tasks.apprunner.amazonaws.com") })); } else { if (string.IsNullOrEmpty(settings.ApplicationIAMRole.RoleArn)) { throw new InvalidOrMissingConfigurationException("The provided Application IAM Role ARN is null or empty."); } TaskRole = Role.FromRoleArn(this, nameof(TaskRole), settings.ApplicationIAMRole.RoleArn, new FromRoleArnOptions { Mutable = false }); } }
public static Role GetRole(TodoInfraStack stack, string roleId, string[] ManagedPolicyArns, string[] PrincipalServices, string PolicyName, string[] Actions, string resources) { var roleProps = new RoleProps { Path = "/", AssumedBy = new ServicePrincipal(PrincipalServices[0]) }; if (PrincipalServices.Length > 0) { List <PrincipalBase> principalBases = new List <PrincipalBase>(); foreach (string service in PrincipalServices) { PrincipalBase principalBase = new ServicePrincipal(service); principalBases.Add(principalBase); } var compositePrincipal = new CompositePrincipal(principalBases.ToArray()); roleProps = new RoleProps { Path = "/", AssumedBy = compositePrincipal }; } var iamRole = new Role(stack, roleId, roleProps); foreach (string arn in ManagedPolicyArns) { iamRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName(arn)); } PolicyStatement policyStatement = new PolicyStatement(new PolicyStatementProps { Actions = Actions, Resources = new string[] { resources }, Effect = Effect.ALLOW }); iamRole.AddToPolicy(policyStatement); return(iamRole); }
internal TargetInstanceStack(Construct scope, string id, Vpc vpc, string keyPairName, IStackProps props = null) : base(scope, id, props) { SecurityGroup = new SecurityGroup(this, "TargetInstance-Security-Group", new SecurityGroupProps { Vpc = vpc, AllowAllOutbound = true, Description = "TargetInstance-Security-Group", SecurityGroupName = "secgroup-" + id }); Role = new Role(this, "ec2-targetinstance-role", new RoleProps { AssumedBy = new ServicePrincipal("ec2.amazonaws.com") }); Role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("SecretsManagerReadWrite")); TargetInstance = new Instance_(this, id, new InstanceProps { InstanceType = InstanceType.Of(InstanceClass.BURSTABLE3, InstanceSize.MICRO), MachineImage = new WindowsImage(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE), Vpc = vpc, UserData = UserData.Custom(Utils.GetResource("target_instance_user_data.ps1")), KeyName = keyPairName, Role = Role, VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE }, SecurityGroup = SecurityGroup }); SecurityGroup.AddIngressRule(Peer.AnyIpv4(), Port.AllTraffic(), "Allow all trafic in. In production - change this!"); new CfnOutput(this, "target-instance", new CfnOutputProps { Value = TargetInstance.InstancePrivateIp }); }
public AppsyncGraphqlDynamodbStack(Construct parent, string id, IStackProps props) : base(parent, id, props) { const string tableName = "items"; var itemsGraphQLApi = new CfnGraphQLApi(this, "Items", new CfnGraphQLApiProps { Name = "items-api", AuthenticationType = "API_KEY" }); new CfnApiKey(this, "ItemsApiKey", new CfnApiKeyProps { ApiId = itemsGraphQLApi.AttrApiId }); var apiSchema = new CfnGraphQLSchema(this, "ItemsSchema", new CfnGraphQLSchemaProps { ApiId = itemsGraphQLApi.AttrApiId, Definition = Definition(tableName) }); var itemsTable = new Table(this, "ItemsTable", new TableProps { TableName = tableName, PartitionKey = new Amazon.CDK.AWS.DynamoDB.Attribute { Name = String.Format("{0}Id", tableName), Type = AttributeType.STRING }, BillingMode = BillingMode.PAY_PER_REQUEST, Stream = StreamViewType.NEW_IMAGE, // The default removal policy is RETAIN, which means that cdk destroy will not attempt to delete // the new table, and it will remain in your account until manually deleted. By setting the policy to // DESTROY, cdk destroy will delete the table (even if it has data in it) RemovalPolicy = RemovalPolicy.DESTROY }); var itemsTableRole = new Role(this, "ItemsDynamoDBRole", new RoleProps { AssumedBy = new ServicePrincipal("appsync.amazonaws.com") }); itemsTableRole.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonDynamoDBFullAccess")); var dataSource = new CfnDataSource(this, "ItemsDataSource", new CfnDataSourceProps { ApiId = itemsGraphQLApi.AttrApiId, Name = "ItemsDynamoDataSource", Type = "AMAZON_DYNAMODB", DynamoDbConfig = new Dictionary <string, string>() { { "tableName", itemsTable.TableName }, { "awsRegion", this.Region } }, ServiceRoleArn = itemsTableRole.RoleArn }); var getOneResolver = new CfnResolver(this, "GetOneQueryResolver", new CfnResolverProps { ApiId = itemsGraphQLApi.AttrApiId, TypeName = "Query", FieldName = "getOne", DataSourceName = dataSource.Name, RequestMappingTemplate = String.Format(@"{{ ""version"": ""2017-02-28"", ""operation"": ""GetItem"", ""key"": {{ ""{0}"": $util.dynamodb.toDynamoDBJson($ctx.args.{0}Id) }} }}", tableName), ResponseMappingTemplate = "$util.toJson($ctx.result)" }); getOneResolver.AddDependsOn(apiSchema); var getAllResolver = new CfnResolver(this, "GetAllQueryResolver", new CfnResolverProps { ApiId = itemsGraphQLApi.AttrApiId, TypeName = "Query", FieldName = "all", DataSourceName = dataSource.Name, RequestMappingTemplate = String.Format(@"{{ ""version"": ""2017-02-28"", ""operation"": ""Scan"", ""limit"": $util.defaultIfNull($ctx.args.limit, 20), ""nextToken"": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null)) }}", tableName), ResponseMappingTemplate = "$util.toJson($ctx.result)" }); getAllResolver.AddDependsOn(apiSchema); var saveResolver = new CfnResolver(this, "SaveMutationResolver", new CfnResolverProps { ApiId = itemsGraphQLApi.AttrApiId, TypeName = "Mutation", FieldName = "save", DataSourceName = dataSource.Name, RequestMappingTemplate = String.Format(@"{{ ""version"": ""2017-02-28"", ""operation"": ""PutItem"", ""key"": {{ ""{0}Id"": {{ ""S"": ""$util.autoId()"" }} }}, ""attributeValues"": {{ ""name"": $util.dynamodb.toDynamoDBJson($ctx.args.name) }} }}", tableName), ResponseMappingTemplate = "$util.toJson($ctx.result)" }); saveResolver.AddDependsOn(apiSchema); var deleteResolver = new CfnResolver(this, "DeleteMutationResolver", new CfnResolverProps { ApiId = itemsGraphQLApi.AttrApiId, TypeName = "Mutation", FieldName = "delete", DataSourceName = dataSource.Name, RequestMappingTemplate = String.Format(@"{{ ""version"": ""2017-02-28"", ""operation"": ""Scan"", ""key"": {{ ""{0}Id"": $util.dynamodb.toDynamoDBJson($ctx.args.{0}Id) }} }}", tableName), ResponseMappingTemplate = "$util.toJson($ctx.result)" }); deleteResolver.AddDependsOn(apiSchema); }
internal GrpcBenchmarkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { var vpc = new Vpc(this, "vpc", new VpcProps { MaxAzs = 1, NatGateways = 0, SubnetConfiguration = new[] { new SubnetConfiguration { Name = "public", SubnetType = SubnetType.PUBLIC } }, }); var subnets = new SubnetSelection { Subnets = vpc.PublicSubnets }; var sg = new SecurityGroup(this, "MasterSg", new SecurityGroupProps { AllowAllOutbound = true, Vpc = vpc, }); var role = new Role(this, "MasterRole", new RoleProps { AssumedBy = new ServicePrincipal("ec2.amazonaws.com"), }); role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonSSMManagedInstanceCore")); var spot = new AutoScalingGroup(this, "instances", new AutoScalingGroupProps { // Monitoring is default DETAILED. SpotPrice = "1.0", // 0.0096 for spot price average for m3.medium Vpc = vpc, SecurityGroup = sg, VpcSubnets = subnets, InstanceType = InstanceType.Of(InstanceClass.COMPUTE5_AMD, InstanceSize.XLARGE4), DesiredCapacity = 1, MaxCapacity = 1, MinCapacity = 0, AssociatePublicIpAddress = true, MachineImage = new AmazonLinuxImage(new AmazonLinuxImageProps { CpuType = AmazonLinuxCpuType.X86_64, Generation = AmazonLinuxGeneration.AMAZON_LINUX_2, Storage = AmazonLinuxStorage.GENERAL_PURPOSE, Virtualization = AmazonLinuxVirt.HVM, }), AllowAllOutbound = true, GroupMetrics = new[] { GroupMetrics.All() }, Role = role, UpdatePolicy = UpdatePolicy.ReplacingUpdate(), }); // https://gist.github.com/npearce/6f3c7826c7499587f00957fee62f8ee9 spot.AddUserData(new[] { "amazon-linux-extras install docker -y", "service docker start", "chkconfig docker on", "usermod -a -G docker ec2-user", "curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose", "chmod +x /usr/local/bin/docker-compose", "yum install -y git", "reboot", }); }
internal DeploymentStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // role var role = new Role(this, "fixsecuritygroupslambdarole", new RoleProps { Description = "fix security groups lambda role", AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AmazonEC2FullAccess")); role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("AWSLambdaExecute")); role.AddManagedPolicy(ManagedPolicy.FromAwsManagedPolicyName("CloudWatchEventsFullAccess")); // lambda var code = @" import json import boto3 def lambda_handler(event, context): print(event) if event['detail']['eventSource'] == 'ec2.amazonaws.com' and event['detail']['eventName'] == 'CreateSecurityGroup': sgid = event['detail']['responseElements']['groupId'] elif event['detail']['eventSource'] == 'ec2.amazonaws.com' and event['detail']['eventName'] == 'DeleteTags': sgid = event['detail']['requestParameters']['resourcesSet']['items'][0]['resourceId'] ec2 = boto3.resource('ec2') sg = ec2.SecurityGroup(sgid) sg.create_tags(Tags=[{'Key': 'Name', 'Value': ""TAGGED!!!""}]) return { 'statusCode': 200, 'body': json.dumps(event) } "; var lambda = new Function(this, "fixsecuritygroupslambda", new FunctionProps { Runtime = Runtime.PYTHON_3_6, Code = Code.FromInline(code), Handler = "index.lambda_handler", Role = role }); // cloudwatch event // @"{ // ""source"": [ // ""aws.ec2"" // ], // ""detail-type"": [ // ""AWS API Call via CloudTrail"" // ], // ""detail"": { // ""eventSource"": [ // ""ec2.amazonaws.com"" // ], // ""eventName"": [ // ""CreateSecurityGroup"", // ""DeleteTags"" // ] // } // }"; var ed = new Dictionary <string, object>(); ed.Add("eventSource", new string[1] { "ec2.amazonaws.com" }); ed.Add("eventName", new string[2] { "CreateSecurityGroup", "DeleteTags" }); var rule = new Rule(this, "cloudwatchevent", new RuleProps { Enabled = true, EventPattern = new EventPattern() { Detail = ed, Source = new string[1] { "aws.ec2" }, DetailType = new string[1] { "AWS API Call via CloudTrail" } }, }); rule.AddTarget(new LambdaFunction(lambda)); }
internal CensusEtlStack(Construct scope, string id, CensusEtlStackProps props) : base(scope, id, props) { var securityGroup = SecurityGroup.FromSecurityGroupId(this, "aurora-sg", props.AuroraSeucrityGroupId); var censusBucket = Bucket.FromBucketName(this, "lambdaBucket", props.CensusArtifactBucket); var awsManagedLambdaPolicy = ManagedPolicy.FromAwsManagedPolicyName("service-role/AWSLambdaBasicExecutionRole"); var queue = new Queue(this, "queue", new QueueProps { QueueName = props.CensusEtlQueue }); new CfnOutput(this, "sqs-queue", new CfnOutputProps { ExportName = "enqueueSQS", Value = queue.QueueUrl }); var enqueueRole = new Role(this, "enqueue-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); enqueueRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { censusBucket.BucketArn }, Actions = new string[] { "s3:ListBucket" } })); enqueueRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { queue.QueueArn }, Actions = new string[] { "sqs:SendMessage" } })); enqueueRole.AddManagedPolicy(awsManagedLambdaPolicy); new Function(this, "census-etl", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "EtlEnqueue::EtlEnqueue.Function::FunctionHandler", Code = Code.FromAsset("EtlEnqueue/bin/Debug/netcoreapp3.1/publish"), SecurityGroups = new ISecurityGroup[] { securityGroup }, Role = enqueueRole }); var workerRole = new Role(this, "worker-role", new RoleProps { AssumedBy = new ServicePrincipal("lambda.amazonaws.com") }); workerRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { censusBucket.BucketArn }, Actions = new string[] { "s3:GetObject" } })); workerRole.AddManagedPolicy(awsManagedLambdaPolicy); workerRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps { Effect = Effect.ALLOW, Resources = new string[] { queue.QueueArn }, Actions = new string[] { "sqs:ReceiveMessage", "sqs:DeleteMessage", "sqs:GetQueueAttributes", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents" } })); var workerFunction = new Function(this, "worker-function", new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Handler = "something", Code = Code.FromAsset("EtlEnqueue/bin/Debug/netcoreapp3.1/publish"), SecurityGroups = new ISecurityGroup[] { securityGroup }, ReservedConcurrentExecutions = 2, Role = workerRole }); workerFunction.AddEventSource(new SqsEventSource(queue)); }