Exemplo n.º 1
0
 public MyStack()
 {
     var config   = new Config();
     var subnetId = config.RequireObject <dynamic>("subnetId");
     var selected = Output.Create(Aws.Ec2.GetSubnet.InvokeAsync(new Aws.Ec2.GetSubnetArgs
     {
         Id = subnetId,
     }));
     var subnet = new Aws.Ec2.SecurityGroup("subnet", new Aws.Ec2.SecurityGroupArgs
     {
         Ingress =
         {
             new Aws.Ec2.Inputs.SecurityGroupIngressArgs
             {
                 CidrBlocks =
                 {
                     selected.Apply(selected => selected.CidrBlock),
                 },
                 FromPort = 80,
                 Protocol = "tcp",
                 ToPort   = 80,
             },
         },
         VpcId = selected.Apply(selected => selected.VpcId),
     });
 }
Exemplo n.º 2
0
    public MyStack()
    {
        // Create a new security group for port 80.
        var securityGroup = new Aws.Ec2.SecurityGroup("securityGroup", new Aws.Ec2.SecurityGroupArgs
        {
            Ingress =
            {
                new Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks =
                    {
                        "0.0.0.0/0",
                    },
                },
            },
        });
        var ami = Output.Create(Aws.GetAmi.InvokeAsync(new Aws.GetAmiArgs
        {
            Filters =
            {
                new Aws.Inputs.GetAmiFilterArgs
                {
                    Name   = "name",
                    Values =
                    {
                        "amzn-ami-hvm-*-x86_64-ebs",
                    },
                },
            },
            Owners =
            {
                "137112412989",
            },
            MostRecent = true,
        }));
        // Create a simple web server using the startup script for the instance.
        var server = new Aws.Ec2.Instance("server", new Aws.Ec2.InstanceArgs
        {
            Tags =
            {
                { "Name", "web-server-www" },
            },
            InstanceType   = "t2.micro",
            SecurityGroups =
            {
                securityGroup.Name,
            },
            Ami      = ami.Apply(ami => ami.Id),
            UserData = @"#!/bin/bash
echo ""Hello, World!"" > index.html
nohup python -m SimpleHTTPServer 80 &
",
        });

        this.PublicIp       = server.PublicIp;
        this.PublicHostName = server.PublicDns;
    }
Exemplo n.º 3
0
    public ElastiGroupStack()
    {
        var sg = new Pulumi.Aws.Ec2.SecurityGroup("my-csharp-security-group");

        var azs = GetAvailabilityZones.InvokeAsync();

        var elastigroup = new Elastigroup("my-csharp-elastigroup", new ElastigroupArgs
        {
            FallbackToOndemand    = false,
            InstanceTypesOndemand = "m3.2xlarge",
            InstanceTypesSpots    =
            {
                "m3.xlarge",
                "m3.2xlarge",
            },
            Orientation    = "balanced",
            Product        = "Linux/UNIX",
            SecurityGroups =
            {
                sg.Id
            },
            Region            = "us-west-2",
            AvailabilityZones = azs.Result.Names,
            ImageId           = "ami-e251209a",
        });
    }
Exemplo n.º 4
0
 public MyStack()
 {
     var europeanEc2 = Output.Create(Aws.GetIpRanges.InvokeAsync(new Aws.GetIpRangesArgs
     {
         Regions =
         {
             "eu-west-1",
             "eu-central-1",
         },
         Services =
         {
             "ec2",
         },
     }));
     var fromEurope = new Aws.Ec2.SecurityGroup("fromEurope", new Aws.Ec2.SecurityGroupArgs
     {
         Ingress =
         {
             new Aws.Ec2.Inputs.SecurityGroupIngressArgs
             {
                 FromPort       = 443,
                 ToPort         = 443,
                 Protocol       = "tcp",
                 CidrBlocks     = europeanEc2.Apply(europeanEc2 => europeanEc2.CidrBlocks),
                 Ipv6CidrBlocks = europeanEc2.Apply(europeanEc2 => europeanEc2.Ipv6CidrBlocks),
             },
         },
         Tags =
         {
             { "CreateDate", europeanEc2.Apply(europeanEc2 => europeanEc2.CreateDate) },
             { "SyncToken",  europeanEc2.Apply(europeanEc2 => europeanEc2.SyncToken)  },
         },
     });
 }
Exemplo n.º 5
0
    public MyStack()
    {
        var config      = new Config();
        var vpc         = config.RequireObject <dynamic>("vpc");
        var domain      = config.Get("domain") ?? "tf-test";
        var selectedVpc = Output.Create(Aws.Ec2.GetVpc.InvokeAsync(new Aws.Ec2.GetVpcArgs
        {
            Tags =
            {
                { "Name", vpc },
            },
        }));
        var selectedSubnetIds = selectedVpc.Apply(selectedVpc => Output.Create(Aws.Ec2.GetSubnetIds.InvokeAsync(new Aws.Ec2.GetSubnetIdsArgs
        {
            Tags =
            {
                { "Tier", "private" },
            },
            VpcId = selectedVpc.Id,
        })));
        var currentRegion         = Output.Create(Aws.GetRegion.InvokeAsync());
        var currentCallerIdentity = Output.Create(Aws.GetCallerIdentity.InvokeAsync());
        var esSecurityGroup       = new Aws.Ec2.SecurityGroup("esSecurityGroup", new Aws.Ec2.SecurityGroupArgs
        {
            Description = "Managed by Pulumi",
            Ingress     =
            {
                new Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    CidrBlocks =
                    {
                        selectedVpc.Apply(selectedVpc => selectedVpc.CidrBlock),
                    },
                    FromPort = 443,
                    Protocol = "tcp",
                    ToPort   = 443,
                },
            },
            VpcId = selectedVpc.Apply(selectedVpc => selectedVpc.Id),
        });
        var esServiceLinkedRole = new Aws.Iam.ServiceLinkedRole("esServiceLinkedRole", new Aws.Iam.ServiceLinkedRoleArgs
        {
            AwsServiceName = "es.amazonaws.com",
        });
        var esDomain = new Aws.ElasticSearch.Domain("esDomain", new Aws.ElasticSearch.DomainArgs
        {
            AccessPolicies = Output.Tuple(currentRegion, currentCallerIdentity).Apply(values =>
            {
                var currentRegion         = values.Item1;
                var currentCallerIdentity = values.Item2;
                return(@$ "{{
	"     "Version" ": " "2012-10-17" ",
	"     "Statement" ": [
Exemplo n.º 6
0
 public MyStack()
 {
     var barSecurityGroup = new Aws.Ec2.SecurityGroup("barSecurityGroup", new Aws.Ec2.SecurityGroupArgs
     {
     });
     var barElasticache_securityGroupSecurityGroup = new Aws.ElastiCache.SecurityGroup("barElasticache/securityGroupSecurityGroup", new Aws.ElastiCache.SecurityGroupArgs
     {
         SecurityGroupNames =
         {
             barSecurityGroup.Name,
         },
     });
 }
Exemplo n.º 7
0
    public MyStack()
    {
        var ami = Output.Create(Pulumi.Aws.Invokes.GetAmi(new Pulumi.Aws.GetAmiArgs
        {
            MostRecent = true,
            Owners     = { "137112412989" },
            Filters    = { new Pulumi.Aws.Inputs.GetAmiFiltersArgs
                           {
                               Name = "name", Values = { "amzn-ami-hvm-*" }
                           } }
        }));

        var group = new Pulumi.Aws.Ec2.SecurityGroup("web-secgrp", new Pulumi.Aws.Ec2.SecurityGroupArgs
        {
            Description = "Enable HTTP access",
            Ingress     =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                },
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "icmp",
                    FromPort   = 8,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        var userData = @"
#!/bin/bash
echo ""Hello, World!"" > index.html
nohup python -m SimpleHTTPServer 80 &
";

        var server = new Pulumi.Aws.Ec2.Instance("web-server-www", new Pulumi.Aws.Ec2.InstanceArgs
        {
            InstanceType        = "t2.micro",
            VpcSecurityGroupIds = { group.Id },
            UserData            = userData,
            Ami = ami.Apply(a => a.Id)
        });

        this.PublicIp  = server.PublicIp;
        this.PublicDns = server.PublicDns;
    }
Exemplo n.º 8
0
 public MyStack()
 {
     var ami = Output.Create(Aws.GetAmi.InvokeAsync(new Aws.GetAmiArgs
     {
         Filters =
         {
             new Aws.Inputs.GetAmiFilterArgs
             {
                 Name   = "name",
                 Values =
                 {
                     "amzn-ami-hvm-*",
                 },
             },
         },
         MostRecent = true,
         Owners     =
         {
             "amazon",
         },
     }));
     var instance = new Aws.Ec2.Instance("instance", new Aws.Ec2.InstanceArgs
     {
         Ami          = ami.Apply(ami => ami.Id),
         InstanceType = "t2.micro",
         Tags         =
         {
             { "type", "test-instance" },
         },
     });
     var sg = new Aws.Ec2.SecurityGroup("sg", new Aws.Ec2.SecurityGroupArgs
     {
         Tags =
         {
             { "type", "test-security-group" },
         },
     });
     var sgAttachment = new Aws.Ec2.NetworkInterfaceSecurityGroupAttachment("sgAttachment", new Aws.Ec2.NetworkInterfaceSecurityGroupAttachmentArgs
     {
         NetworkInterfaceId = instance.PrimaryNetworkInterfaceId,
         SecurityGroupId    = sg.Id,
     });
 }
Exemplo n.º 9
0
    private async Task <redshift.Cluster> createRedshiftCluster(int port, ec2.SecurityGroup securityGroup, iam.Role role)
    {
        var password = await getRedshiftPassword();

        var cluster = new redshift.Cluster("dend-redshift-cluster", new redshift.ClusterArgs
        {
            NodeType          = "dc2.large",
            NumberOfNodes     = 2,
            ClusterIdentifier = "dend-redshift-cluster",
            DatabaseName      = "dev",
            Port                    = port,
            MasterUsername          = "******",
            MasterPassword          = password,
            VpcSecurityGroupIds     = { securityGroup.Id },
            IamRoles                = { "AWSServiceRoleForRedshift", role.Id },
            FinalSnapshotIdentifier = "dend-snapshot"
        }, this.CustomResourceOptions);

        return(cluster);
    }
Exemplo n.º 10
0
    private ec2.SecurityGroup createRedshiftSecurityGroup(string vpcId, string localPublicIp, int port)
    {
        var redshiftSG = new ec2.SecurityGroup("redshift_security_group", new ec2.SecurityGroupArgs
        {
            VpcId       = vpcId,
            Description = "Auth Redshift Cluster to connect",
            Ingress     =
            {
                new SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = port,
                    ToPort     = port,
                    CidrBlocks ={ localPublicIp                  }
                }
            }
        }, this.CustomResourceOptions);

        return(redshiftSG);
    }
Exemplo n.º 11
0
 public MyStack()
 {
     var allowTls = new Aws.Ec2.SecurityGroup("allowTls", new Aws.Ec2.SecurityGroupArgs
     {
         Description = "Allow TLS inbound traffic",
         VpcId       = aws_vpc.Main.Id,
         Ingress     =
         {
             new Aws.Ec2.Inputs.SecurityGroupIngressArgs
             {
                 Description = "TLS from VPC",
                 FromPort    = 443,
                 ToPort      = 443,
                 Protocol    = "tcp",
                 CidrBlocks  =
                 {
                     aws_vpc.Main.Cidr_block,
                 },
             },
         },
         Egress =
         {
             new Aws.Ec2.Inputs.SecurityGroupEgressArgs
             {
                 FromPort   = 0,
                 ToPort     = 0,
                 Protocol   = "-1",
                 CidrBlocks =
                 {
                     "0.0.0.0/0",
                 },
             },
         },
         Tags =
         {
             { "Name", "allow_tls" },
         },
     });
 }
Exemplo n.º 12
0
    public FargateStack()
    {
        // Read back the default VPC and public subnets, which we will use.
        var vpc = Output.Create(Ec2.GetVpc.InvokeAsync(new Ec2.GetVpcArgs {
            Default = true
        }));
        var vpcId  = vpc.Apply(vpc => vpc.Id);
        var subnet = vpcId.Apply(id => Ec2.GetSubnetIds.InvokeAsync(new Ec2.GetSubnetIdsArgs {
            VpcId = id
        }));
        var subnetIds = subnet.Apply(s => s.Ids);

        // Create a SecurityGroup that permits HTTP ingress and unrestricted egress.
        var webSg = new Ec2.SecurityGroup("web-sg", new Ec2.SecurityGroupArgs
        {
            VpcId  = vpcId,
            Egress =
            {
                new Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            },
            Ingress =
            {
                new Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        // Create an ECS cluster to run a container-based service.
        var cluster = new Ecs.Cluster("app-cluster");

        // Create an IAM role that can be used by our service's task.
        var taskExecRole = new Iam.Role("task-exec-role", new Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
    ""Sid"": """",
    ""Effect"": ""Allow"",
    ""Principal"": {
        ""Service"": ""ecs-tasks.amazonaws.com""
    },
    ""Action"": ""sts:AssumeRole""
}]
}"
        });
        var taskExecAttach = new Iam.RolePolicyAttachment("task-exec-policy", new Iam.RolePolicyAttachmentArgs
        {
            Role      = taskExecRole.Name,
            PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
        });

        // Create a load balancer to listen for HTTP traffic on port 80.
        var webLb = new Elb.LoadBalancer("web-lb", new Elb.LoadBalancerArgs
        {
            Subnets        = subnetIds,
            SecurityGroups = { webSg.Id }
        });
        var webTg = new Elb.TargetGroup("web-tg", new Elb.TargetGroupArgs
        {
            Port       = 80,
            Protocol   = "HTTP",
            TargetType = "ip",
            VpcId      = vpcId
        });
        var webListener = new Elb.Listener("web-listener", new Elb.ListenerArgs
        {
            LoadBalancerArn = webLb.Arn,
            Port            = 80,
            DefaultActions  =
            {
                new Elb.Inputs.ListenerDefaultActionArgs
                {
                    Type           = "forward",
                    TargetGroupArn = webTg.Arn,
                }
            }
        });

        // Create a private ECR registry and build and publish our app's container image to it.
        var appRepo            = new Ecr.Repository("app-repo");
        var appRepoCredentials = appRepo.RegistryId.Apply(async rid =>
        {
            var credentials = await Ecr.GetCredentials.InvokeAsync(new Ecr.GetCredentialsArgs {
                RegistryId = rid
            });
            var data = Convert.FromBase64String(credentials.AuthorizationToken);
            return(Encoding.UTF8.GetString(data).Split(":").ToImmutableArray());
        });
        var image = new Docker.Image("app-img", new Docker.ImageArgs
        {
            Build     = "../App",
            ImageName = appRepo.RepositoryUrl,
            Registry  = new Docker.ImageRegistry
            {
                Server   = appRepo.RepositoryUrl,
                Username = appRepoCredentials.GetAt(0),
                Password = appRepoCredentials.GetAt(1)
            }
        });

        // Spin up a load balanced service running our container image.
        var appTask = new Ecs.TaskDefinition("app-task", new Ecs.TaskDefinitionArgs
        {
            Family                  = "fargate-task-definition",
            Cpu                     = "256",
            Memory                  = "512",
            NetworkMode             = "awsvpc",
            RequiresCompatibilities = { "FARGATE" },
            ExecutionRoleArn        = taskExecRole.Arn,
            ContainerDefinitions    = image.ImageName.Apply(imageName => @"[{
""name"": ""my-app"",
""image"": """ + imageName + @""",
""portMappings"": [{
    ""containerPort"": 80,
    ""hostPort"": 80,
    ""protocol"": ""tcp""
}]
}]")
        });
        var appSvc = new Ecs.Service("app-svc", new Ecs.ServiceArgs
        {
            Cluster              = cluster.Arn,
            DesiredCount         = 3,
            LaunchType           = "FARGATE",
            TaskDefinition       = appTask.Arn,
            NetworkConfiguration = new Ecs.Inputs.ServiceNetworkConfigurationArgs
            {
                AssignPublicIp = true,
                Subnets        = subnetIds,
                SecurityGroups = { webSg.Id }
            },
            LoadBalancers =
            {
                new Ecs.Inputs.ServiceLoadBalancerArgs
                {
                    TargetGroupArn = webTg.Arn,
                    ContainerName  = "my-app",
                    ContainerPort  = 80
                }
            }
        }, new CustomResourceOptions {
            DependsOn = { webListener }
        });

        // Export the resulting web address.
        this.Url = Output.Format($"http://{webLb.DnsName}");
    }
Exemplo n.º 13
0
    public MyStack()
    {
        var vpc = Output.Create(Pulumi.Aws.Ec2.GetVpc.InvokeAsync(new Pulumi.Aws.Ec2.GetVpcArgs {
            Default = true
        }));
        var vpcId  = vpc.Apply(vpc => vpc.Id);
        var subnet = vpcId.Apply(id => Pulumi.Aws.Ec2.GetSubnetIds.InvokeAsync(new Pulumi.Aws.Ec2.GetSubnetIdsArgs {
            VpcId = id
        }));
        var subnetIds = subnet.Apply(s => s.Ids);

        var ami = Output.Create(Pulumi.Aws.GetAmi.InvokeAsync(new Pulumi.Aws.GetAmiArgs
        {
            MostRecent = true,
            Owners     = { "137112412989" },
            Filters    = { new Pulumi.Aws.Inputs.GetAmiFiltersArgs
                           {
                               Name = "name", Values = { "amzn-ami-hvm-*" }
                           } }
        }));

        var group = new Pulumi.Aws.Ec2.SecurityGroup("web-secgrp", new Pulumi.Aws.Ec2.SecurityGroupArgs
        {
            Description = "Enable HTTP access",
            Egress      =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                },
            },
            Ingress =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                },
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "icmp",
                    FromPort   = 8,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        var loadbalancer = new Pulumi.Aws.LB.LoadBalancer("external-loadbalancer", new Pulumi.Aws.LB.LoadBalancerArgs
        {
            Internal       = false,
            SecurityGroups =
            {
                group.Id
            },
            Subnets          = subnetIds,
            LoadBalancerType = "application",
        });

        this.Url = loadbalancer.DnsName;

        var targetGroup = new Pulumi.Aws.LB.TargetGroup("target-group", new Pulumi.Aws.LB.TargetGroupArgs
        {
            Port       = 80,
            Protocol   = "HTTP",
            TargetType = "ip",
            VpcId      = vpcId,
        });

        var listener = new Pulumi.Aws.LB.Listener("listener", new Pulumi.Aws.LB.ListenerArgs
        {
            LoadBalancerArn = loadbalancer.Arn,
            Port            = 80,
            DefaultActions  =
            {
                new Pulumi.Aws.LB.Inputs.ListenerDefaultActionsArgs
                {
                    Type           = "forward",
                    TargetGroupArn = targetGroup.Arn,
                }
            }
        });

        var userData = @"
#!/bin/bash
echo ""Hello, World!"" > index.html
nohup python -m SimpleHTTPServer 80 &
";

        var azs = Pulumi.Aws.GetAvailabilityZones.InvokeAsync(new Pulumi.Aws.GetAvailabilityZonesArgs()).Result;

        foreach (var az in azs.Names)
        {
            var server = new Pulumi.Aws.Ec2.Instance($"web-server-{az}", new Pulumi.Aws.Ec2.InstanceArgs
            {
                InstanceType        = "t2.micro",
                VpcSecurityGroupIds = { group.Id },
                UserData            = userData,
                Ami = ami.Apply(a => a.Id),
                AvailabilityZone = az,
            });

            var attachment = new Pulumi.Aws.LB.TargetGroupAttachment($"web-server-{az}", new Pulumi.Aws.LB.TargetGroupAttachmentArgs
            {
                Port           = 80,
                TargetGroupArn = targetGroup.Arn,
                TargetId       = server.PrivateIp,
            });
        }
    }
Exemplo n.º 14
0
    private static void ConfigureEcsCluster()
    {
        cluster = new Ecs.Cluster($"{baseName}-cluster", null, new CustomResourceOptions());

        // Create a SecurityGroup that permits HTTP ingress and unrestricted egress.
        var webSg = new Ec2.SecurityGroup($"{baseName}-web-sg", new Ec2.SecurityGroupArgs
        {
            VpcId  = vpcId,
            Egress =
            {
                new Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  },
                },
            },
            Ingress =
            {
                new Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  },
                },
            },
        });

        // Create an IAM role that can be used by our service's task.
        var taskExecRole = new Iam.Role($"{baseName}-task-exec-role", new Iam.RoleArgs
        {
            AssumeRolePolicy = File.ReadAllText("perm.json"),
        });

        var taskExecAttach = new Iam.RolePolicyAttachment($"{baseName}-task-exec-policy", new Iam.RolePolicyAttachmentArgs
        {
            Role      = taskExecRole.Name,
            PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
        });

        // Create a load balancer to listen for HTTP traffic on port 80.
        var webLb = new Elb.LoadBalancer($"{baseName}-web-lb", new Elb.LoadBalancerArgs
        {
            Subnets = new InputList <string>()
            {
                subnetId, subnetTwoId
            },
            SecurityGroups = { webSg.Id },
        });
        var webTg = new Elb.TargetGroup($"{baseName}-web-tg", new Elb.TargetGroupArgs
        {
            Port       = 80,
            Protocol   = "HTTP",
            TargetType = "ip",
            VpcId      = vpcId,
        });
        var webListener = new Elb.Listener($"{baseName}-web-listener", new Elb.ListenerArgs
        {
            LoadBalancerArn = webLb.Arn,
            Port            = 80,
            DefaultActions  =
            {
                new Elb.Inputs.ListenerDefaultActionsArgs
                {
                    Type           = "forward",
                    TargetGroupArn = webTg.Arn,
                },
            },
        });

        var launchConfig = new Ec2.LaunchConfiguration($"{baseName}-launchconfig", new Ec2.LaunchConfigurationArgs()
        {
            ImageId                  = "ami-a1491ad2",
            InstanceType             = "t2.nano",
            AssociatePublicIpAddress = true,
            SecurityGroups           = webSg.Id,
        });

        var scalingGroup = new Group($"{baseName}-autoscaling", new GroupArgs()
        {
            AvailabilityZones = new InputList <string>()
            {
                "eu-west-1a", "eu-west-1b"
            },
            VpcZoneIdentifiers = new InputList <string>()
            {
                subnetId, subnetTwoId
            },
            DesiredCapacity     = 1,
            LaunchConfiguration = launchConfig.Id,
            MaxSize             = 1,
            MinSize             = 0,
        });

        // Spin up a load balanced service running our container image.
        var appTask = new Ecs.TaskDefinition($"{baseName}-app-task", new Ecs.TaskDefinitionArgs
        {
            Family                  = "fargate-task-definition",
            Cpu                     = "256",
            Memory                  = "512",
            NetworkMode             = "awsvpc",
            RequiresCompatibilities = { "FARGATE", "EC2" },
            ExecutionRoleArn        = taskExecRole.Arn,
            ContainerDefinitions    = @"[{
    ""name"": ""my-app"",
    ""image"": ""nginx"",
    ""portMappings"": [{
        ""containerPort"": 80,
        ""hostPort"": 80,
        ""protocol"": ""tcp""
    }]
}]",
        });

        var ec2Svc = new Ecs.Service($"{baseName}-ec2-svc", new Ecs.ServiceArgs()
        {
            Cluster              = cluster.Arn,
            DesiredCount         = 1,
            LaunchType           = "EC2",
            TaskDefinition       = appTask.Arn,
            NetworkConfiguration = new Ecs.Inputs.ServiceNetworkConfigurationArgs
            {
                Subnets = new InputList <string>()
                {
                    subnetId, subnetTwoId
                },
                SecurityGroups = { webSg.Id },
            },
            LoadBalancers =
            {
                new Ecs.Inputs.ServiceLoadBalancersArgs
                {
                    TargetGroupArn = webTg.Arn,
                    ContainerName  = "my-app",
                    ContainerPort  = 80,
                },
            },
        }, new CustomResourceOptions {
            DependsOn = { webListener }
        });
    }
Exemplo n.º 15
0
    public MyStack()
    {
        var cluster = new Pulumi.Aws.Ecs.Cluster("app-cluster");

        // Read back the default VPC and public subnets, which we will use.
        var vpc = Output.Create(Pulumi.Aws.Ec2.GetVpc.InvokeAsync(new Pulumi.Aws.Ec2.GetVpcArgs {
            Default = true
        }));
        var vpcId  = vpc.Apply(vpc => vpc.Id);
        var subnet = vpcId.Apply(id => Pulumi.Aws.Ec2.GetSubnetIds.InvokeAsync(new Pulumi.Aws.Ec2.GetSubnetIdsArgs {
            VpcId = id
        }));
        var subnetIds = subnet.Apply(s => s.Ids);

        // Create a SecurityGroup that permits HTTP ingress and unrestricted egress.
        var webSg = new Pulumi.Aws.Ec2.SecurityGroup("web-sg", new Pulumi.Aws.Ec2.SecurityGroupArgs
        {
            VpcId  = vpcId,
            Egress =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            },
            Ingress =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        // Create a load balancer to listen for HTTP traffic on port 80.
        var webLb = new Pulumi.Aws.LB.LoadBalancer("web-lb", new Pulumi.Aws.LB.LoadBalancerArgs
        {
            Subnets        = subnetIds,
            SecurityGroups = { webSg.Id }
        });
        var webTg = new Pulumi.Aws.LB.TargetGroup("web-tg", new Pulumi.Aws.LB.TargetGroupArgs
        {
            Port       = 80,
            Protocol   = "HTTP",
            TargetType = "ip",
            VpcId      = vpcId
        });
        var webListener = new Pulumi.Aws.LB.Listener("web-listener", new Pulumi.Aws.LB.ListenerArgs
        {
            LoadBalancerArn = webLb.Arn,
            Port            = 80,
            DefaultActions  =
            {
                new Pulumi.Aws.LB.Inputs.ListenerDefaultActionArgs
                {
                    Type           = "forward",
                    TargetGroupArn = webTg.Arn,
                }
            }
        });
    }
Exemplo n.º 16
0
    public MyStack()
    {
        var vpc = Output.Create(Aws.Ec2.GetVpc.InvokeAsync(new Aws.Ec2.GetVpcArgs
        {
            Default = true,
        }));
        var subnets = vpc.Apply(vpc => Output.Create(Aws.Ec2.GetSubnetIds.InvokeAsync(new Aws.Ec2.GetSubnetIdsArgs
        {
            VpcId = vpc.Id,
        })));
        // Create a security group that permits HTTP ingress and unrestricted egress.
        var webSecurityGroup = new Aws.Ec2.SecurityGroup("webSecurityGroup", new Aws.Ec2.SecurityGroupArgs
        {
            VpcId  = vpc.Apply(vpc => vpc.Id),
            Egress =
            {
                new Aws.Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks =
                    {
                        "0.0.0.0/0",
                    },
                },
            },
            Ingress =
            {
                new Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks =
                    {
                        "0.0.0.0/0",
                    },
                },
            },
        });
        // Create an ECS cluster to run a container-based service.
        var cluster = new Aws.Ecs.Cluster("cluster", new Aws.Ecs.ClusterArgs
        {
        });
        // Create an IAM role that can be used by our service's task.
        var taskExecRole = new Aws.Iam.Role("taskExecRole", new Aws.Iam.RoleArgs
        {
            AssumeRolePolicy = JsonSerializer.Serialize(new Dictionary <string, object?>
            {
                { "Version", "2008-10-17" },
                { "Statement", new[]
                  {
                      new Dictionary <string, object?>
                      {
                          { "Sid", "" },
                          { "Effect", "Allow" },
                          { "Principal", new Dictionary <string, object?>
                            {
                                { "Service", "ecs-tasks.amazonaws.com" },
                            } },
                          { "Action", "sts:AssumeRole" },
                      },
                  } },
            }),
        });
        var taskExecRolePolicyAttachment = new Aws.Iam.RolePolicyAttachment("taskExecRolePolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = taskExecRole.Name,
            PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
        });
        // Create a load balancer to listen for HTTP traffic on port 80.
        var webLoadBalancer = new Aws.ElasticLoadBalancingV2.LoadBalancer("webLoadBalancer", new Aws.ElasticLoadBalancingV2.LoadBalancerArgs
        {
            Subnets        = subnets.Apply(subnets => subnets.Ids),
            SecurityGroups =
            {
                webSecurityGroup.Id,
            },
        });
        var webTargetGroup = new Aws.ElasticLoadBalancingV2.TargetGroup("webTargetGroup", new Aws.ElasticLoadBalancingV2.TargetGroupArgs
        {
            Port       = 80,
            Protocol   = "HTTP",
            TargetType = "ip",
            VpcId      = vpc.Apply(vpc => vpc.Id),
        });
        var webListener = new Aws.ElasticLoadBalancingV2.Listener("webListener", new Aws.ElasticLoadBalancingV2.ListenerArgs
        {
            LoadBalancerArn = webLoadBalancer.Arn,
            Port            = 80,
            DefaultActions  =
            {
                new Aws.ElasticLoadBalancingV2.Inputs.ListenerDefaultActionArgs
                {
                    Type           = "forward",
                    TargetGroupArn = webTargetGroup.Arn,
                },
            },
        });
        // Spin up a load balanced service running NGINX
        var appTask = new Aws.Ecs.TaskDefinition("appTask", new Aws.Ecs.TaskDefinitionArgs
        {
            Family                  = "fargate-task-definition",
            Cpu                     = "256",
            Memory                  = "512",
            NetworkMode             = "awsvpc",
            RequiresCompatibilities =
            {
                "FARGATE",
            },
            ExecutionRoleArn     = taskExecRole.Arn,
            ContainerDefinitions = JsonSerializer.Serialize(new[]
            {
                new Dictionary <string, object?>
                {
                    { "name", "my-app" },
                    { "image", "nginx" },
                    { "portMappings", new[]
                      {
                          new Dictionary <string, object?>
                          {
                              { "containerPort", 80 },
                              { "hostPort", 80 },
                              { "protocol", "tcp" },
                          },
                      } },
                },
            }
                                                            ),
        });
        var appService = new Aws.Ecs.Service("appService", new Aws.Ecs.ServiceArgs
        {
            Cluster              = cluster.Arn,
            DesiredCount         = 5,
            LaunchType           = "FARGATE",
            TaskDefinition       = appTask.Arn,
            NetworkConfiguration = new Aws.Ecs.Inputs.ServiceNetworkConfigurationArgs
            {
                AssignPublicIp = true,
                Subnets        = subnets.Apply(subnets => subnets.Ids),
                SecurityGroups =
                {
                    webSecurityGroup.Id,
                },
            },
            LoadBalancers =
            {
                new Aws.Ecs.Inputs.ServiceLoadBalancerArgs
                {
                    TargetGroupArn = webTargetGroup.Arn,
                    ContainerName  = "my-app",
                    ContainerPort  = 80,
                },
            },
        }, new CustomResourceOptions
        {
            DependsOn =
            {
                webListener,
            },
        });

        this.Url = webLoadBalancer.DnsName;
    }
Exemplo n.º 17
0
    public MyStack()
    {
        var ami = Output.Create(Pulumi.Aws.GetAmi.InvokeAsync(new Pulumi.Aws.GetAmiArgs
        {
            MostRecent = true,
            Owners     = { "137112412989" },
            Filters    = { new Pulumi.Aws.Inputs.GetAmiFiltersArgs
                           {
                               Name = "name", Values = { "amzn-ami-hvm-*" }
                           } }
        }));

        var group = new Pulumi.Aws.Ec2.SecurityGroup("web-secgrp", new Pulumi.Aws.Ec2.SecurityGroupArgs
        {
            Description = "Enable HTTP access",
            Ingress     =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                },
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "icmp",
                    FromPort   = 8,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        var userData = @"
#!/bin/bash
echo ""Hello, World!"" > index.html
nohup python -m SimpleHTTPServer 80 &
";

        var azs       = Pulumi.Aws.GetAvailabilityZones.InvokeAsync(new Pulumi.Aws.GetAvailabilityZonesArgs()).Result;
        var hostnames = new List <Input <string> >();
        var ips       = new List <Input <string> >();

        foreach (var az in azs.Names)
        {
            var server = new Pulumi.Aws.Ec2.Instance($"web-server-{az}", new Pulumi.Aws.Ec2.InstanceArgs
            {
                InstanceType        = "t2.micro",
                VpcSecurityGroupIds = { group.Id },
                UserData            = userData,
                Ami = ami.Apply(a => a.Id),
                AvailabilityZone = az,
            });

            hostnames.Add(server.PublicDns);
            ips.Add(server.PublicIp);
        }

        this.PublicIps = Output.All(ips.ToImmutableArray());
        this.PublicDns = Output.All(hostnames.ToImmutableArray());
    }
Exemplo n.º 18
0
    public MyStack()
    {
        var ecsInstanceRoleRole = new Aws.Iam.Role("ecsInstanceRoleRole", new Aws.Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
    ""Version"": ""2012-10-17"",
    ""Statement"": [
	{
	    ""Action"": ""sts:AssumeRole"",
	    ""Effect"": ""Allow"",
	    ""Principal"": {
		""Service"": ""ec2.amazonaws.com""
	    }
	}
    ]
}

",
        });
        var ecsInstanceRoleRolePolicyAttachment = new Aws.Iam.RolePolicyAttachment("ecsInstanceRoleRolePolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role",
            Role      = ecsInstanceRoleRole.Name,
        });
        var ecsInstanceRoleInstanceProfile = new Aws.Iam.InstanceProfile("ecsInstanceRoleInstanceProfile", new Aws.Iam.InstanceProfileArgs
        {
            Role = ecsInstanceRoleRole.Name,
        });
        var awsBatchServiceRoleRole = new Aws.Iam.Role("awsBatchServiceRoleRole", new Aws.Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
    ""Version"": ""2012-10-17"",
    ""Statement"": [
	{
	    ""Action"": ""sts:AssumeRole"",
	    ""Effect"": ""Allow"",
	    ""Principal"": {
		""Service"": ""batch.amazonaws.com""
	    }
	}
    ]
}

",
        });
        var awsBatchServiceRoleRolePolicyAttachment = new Aws.Iam.RolePolicyAttachment("awsBatchServiceRoleRolePolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            PolicyArn = "arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole",
            Role      = awsBatchServiceRoleRole.Name,
        });
        var sampleSecurityGroup = new Aws.Ec2.SecurityGroup("sampleSecurityGroup", new Aws.Ec2.SecurityGroupArgs
        {
            Egress =
            {
                new Aws.Ec2.Inputs.SecurityGroupEgressArgs
                {
                    CidrBlocks =
                    {
                        "0.0.0.0/0",
                    },
                    FromPort = 0,
                    Protocol = "-1",
                    ToPort   = 0,
                },
            },
        });
        var sampleVpc = new Aws.Ec2.Vpc("sampleVpc", new Aws.Ec2.VpcArgs
        {
            CidrBlock = "10.1.0.0/16",
        });
        var sampleSubnet = new Aws.Ec2.Subnet("sampleSubnet", new Aws.Ec2.SubnetArgs
        {
            CidrBlock = "10.1.1.0/24",
            VpcId     = sampleVpc.Id,
        });
        var sampleComputeEnvironment = new Aws.Batch.ComputeEnvironment("sampleComputeEnvironment", new Aws.Batch.ComputeEnvironmentArgs
        {
            ComputeEnvironmentName = "sample",
            ComputeResources       = new Aws.Batch.Inputs.ComputeEnvironmentComputeResourcesArgs
            {
                InstanceRole = ecsInstanceRoleInstanceProfile.Arn,
                InstanceType =
                {
                    "c4.large",
                },
                MaxVcpus         = 16,
                MinVcpus         = 0,
                SecurityGroupIds =
                {
                    sampleSecurityGroup.Id,
                },
                Subnets =
                {
                    sampleSubnet.Id,
                },
                Type = "EC2",
            },
            ServiceRole = awsBatchServiceRoleRole.Arn,
            Type        = "MANAGED",
        }, new CustomResourceOptions
        {
            DependsOn =
            {
                "aws_iam_role_policy_attachment.aws_batch_service_role",
            },
        });
    }
    public MyStack()
    {
        // Read back the default VPC and public subnets, which we will use.
        var vpc = Output.Create(Ec2.GetVpc.InvokeAsync(new Ec2.GetVpcArgs {
            Default = true
        }));
        var vpcId  = vpc.Apply(vpc => vpc.Id);
        var subnet = vpcId.Apply(id => Ec2.GetSubnetIds.InvokeAsync(new Ec2.GetSubnetIdsArgs {
            VpcId = id
        }));
        var subnetIds = subnet.Apply(s => s.Ids);

        // Create an IAM role that can be used by our service's task.
        var eksRole = new Iam.Role("eks-iam-eksRole", new Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
    ""Sid"": """",
    ""Effect"": ""Allow"",
    ""Principal"": {
        ""Service"": ""eks.amazonaws.com""
    },
    ""Action"": ""sts:AssumeRole""
}]
}"
        });

        var eksPolicies = new Dictionary <string, string>
        {
            { "service-policy", "arn:aws:iam::aws:policy/AmazonEKSServicePolicy" },
            { "cluster-policy", "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy" }
        };

        foreach (var(name, policy) in eksPolicies)
        {
            var taskExecAttach = new Iam.RolePolicyAttachment($"rpa-{name}",
                                                              new Iam.RolePolicyAttachmentArgs
            {
                Role      = eksRole.Name,
                PolicyArn = policy,
            });
        }

        // Create an IAM role that can be used by our service's task.
        var nodeGroupRole = new Iam.Role("nodegroup-iam-role", new Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
    ""Sid"": """",
    ""Effect"": ""Allow"",
    ""Principal"": {
        ""Service"": ""ec2.amazonaws.com""
    },
    ""Action"": ""sts:AssumeRole""
}]
}"
        });

        var nodeGroupPolicies = new Dictionary <string, string>
        {
            { "worker", "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy" },
            { "cni", "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy" },
            { "registry", "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly" }
        };

        foreach (var(name, policy) in nodeGroupPolicies)
        {
            var taskExecAttach = new Iam.RolePolicyAttachment($"ngpa-{name}",
                                                              new Iam.RolePolicyAttachmentArgs
            {
                Role      = nodeGroupRole.Name,
                PolicyArn = policy,
            });
        }

        var clusterSg = new Ec2.SecurityGroup("cluster-sg", new Ec2.SecurityGroupArgs
        {
            VpcId  = vpcId,
            Egress =
            {
                new Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            },
            Ingress =
            {
                new Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        var cluster = new Eks.Cluster("eks-cluster", new Eks.ClusterArgs
        {
            RoleArn   = eksRole.Arn,
            VpcConfig = new ClusterVpcConfigArgs
            {
                PublicAccessCidrs =
                {
                    "0.0.0.0/0",
                },
                SecurityGroupIds =
                {
                    clusterSg.Id,
                },
                SubnetIds = subnetIds,
            },
        });

        var nodeGroup = new Eks.NodeGroup("node-group", new Eks.NodeGroupArgs
        {
            ClusterName   = cluster.Name,
            NodeGroupName = "demo-eks-nodegroup",
            NodeRoleArn   = nodeGroupRole.Arn,
            SubnetIds     = subnetIds,
            ScalingConfig = new NodeGroupScalingConfigArgs
            {
                DesiredSize = 2,
                MaxSize     = 2,
                MinSize     = 2
            },
        });

        this.Kubeconfig = GenerateKubeconfig(cluster.Endpoint,
                                             cluster.CertificateAuthority.Apply(x => x.Data),
                                             cluster.Name);
    }
    public MyStack()
    {
        var cluster = new Pulumi.Aws.Ecs.Cluster("app-cluster");

        // Read back the default VPC and public subnets, which we will use.
        var vpc = Output.Create(Pulumi.Aws.Ec2.GetVpc.InvokeAsync(new Pulumi.Aws.Ec2.GetVpcArgs {
            Default = true
        }));
        var vpcId  = vpc.Apply(vpc => vpc.Id);
        var subnet = vpcId.Apply(id => Pulumi.Aws.Ec2.GetSubnetIds.InvokeAsync(new Pulumi.Aws.Ec2.GetSubnetIdsArgs {
            VpcId = id
        }));
        var subnetIds = subnet.Apply(s => s.Ids);

        // Create a SecurityGroup that permits HTTP ingress and unrestricted egress.
        var webSg = new Pulumi.Aws.Ec2.SecurityGroup("web-sg", new Pulumi.Aws.Ec2.SecurityGroupArgs
        {
            VpcId  = vpcId,
            Egress =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            },
            Ingress =
            {
                new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        // Create a load balancer to listen for HTTP traffic on port 80.
        var webLb = new Pulumi.Aws.LB.LoadBalancer("web-lb", new Pulumi.Aws.LB.LoadBalancerArgs
        {
            Subnets        = subnetIds,
            SecurityGroups = { webSg.Id }
        });
        var webTg = new Pulumi.Aws.LB.TargetGroup("web-tg", new Pulumi.Aws.LB.TargetGroupArgs
        {
            Port       = 80,
            Protocol   = "HTTP",
            TargetType = "ip",
            VpcId      = vpcId
        });
        var webListener = new Pulumi.Aws.LB.Listener("web-listener", new Pulumi.Aws.LB.ListenerArgs
        {
            LoadBalancerArn = webLb.Arn,
            Port            = 80,
            DefaultActions  =
            {
                new Pulumi.Aws.LB.Inputs.ListenerDefaultActionsArgs
                {
                    Type           = "forward",
                    TargetGroupArn = webTg.Arn,
                }
            }
        });

        // Create an IAM role that can be used by our service's task.
        var taskExecRole = new Pulumi.Aws.Iam.Role("task-exec-role", new Pulumi.Aws.Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
    ""Sid"": """",
    ""Effect"": ""Allow"",
    ""Principal"": {
        ""Service"": ""ecs-tasks.amazonaws.com""
    },
    ""Action"": ""sts:AssumeRole""
}]
}"
        });
        var taskExecAttach = new Pulumi.Aws.Iam.RolePolicyAttachment("task-exec-policy", new Pulumi.Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = taskExecRole.Name,
            PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
        });

        // Spin up a load balanced service running our container image.
        var appTask = new Pulumi.Aws.Ecs.TaskDefinition("app-task", new Pulumi.Aws.Ecs.TaskDefinitionArgs
        {
            Family                  = "fargate-task-definition",
            Cpu                     = "256",
            Memory                  = "512",
            NetworkMode             = "awsvpc",
            RequiresCompatibilities = { "FARGATE" },
            ExecutionRoleArn        = taskExecRole.Arn,
            ContainerDefinitions    = @"[{
""name"": ""my-app"",
""image"": ""nginx"",
""portMappings"": [{
    ""containerPort"": 80,
    ""hostPort"": 80,
    ""protocol"": ""tcp""
}]
}]",
        });
        var appSvc = new Pulumi.Aws.Ecs.Service("app-svc", new Pulumi.Aws.Ecs.ServiceArgs
        {
            Cluster              = cluster.Arn,
            DesiredCount         = 1,
            LaunchType           = "FARGATE",
            TaskDefinition       = appTask.Arn,
            NetworkConfiguration = new Pulumi.Aws.Ecs.Inputs.ServiceNetworkConfigurationArgs
            {
                AssignPublicIp = true,
                Subnets        = subnetIds,
                SecurityGroups = { webSg.Id }
            },
            LoadBalancers =
            {
                new Pulumi.Aws.Ecs.Inputs.ServiceLoadBalancersArgs
                {
                    TargetGroupArn = webTg.Arn,
                    ContainerName  = "my-app",
                    ContainerPort  = 80
                }
            }
        }, new CustomResourceOptions {
            DependsOn = { webListener }
        });

        // Export the resulting web address.
        this.Url = Output.Format($"http://{webLb.DnsName}");
    }
Exemplo n.º 21
0
    public EksStack()
    {
        // Read back the default VPC and public subnets, which we will use.
        var vpc = Output.Create(Ec2.GetVpc.InvokeAsync(new Ec2.GetVpcArgs {
            Default = true
        }));
        var vpcId  = vpc.Apply(vpc => vpc.Id);
        var subnet = vpcId.Apply(id => Ec2.GetSubnetIds.InvokeAsync(new Ec2.GetSubnetIdsArgs {
            VpcId = id
        }));
        var subnetIds = subnet.Apply(s => s.Ids);

        // Create an IAM role that can be used by our service's task.
        var eksRole = new Iam.Role("eks-iam-eksRole", new Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
    ""Sid"": """",
    ""Effect"": ""Allow"",
    ""Principal"": {
        ""Service"": ""eks.amazonaws.com""
    },
    ""Action"": ""sts:AssumeRole""
}]
}"
        });

        var eksPolicies = new Dictionary <string, string>
        {
            { "service-policy", "arn:aws:iam::aws:policy/AmazonEKSServicePolicy" },
            { "cluster-policy", "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy" }
        };

        foreach (var(name, policy) in eksPolicies)
        {
            var taskExecAttach = new Iam.RolePolicyAttachment($"rpa-{name}",
                                                              new Iam.RolePolicyAttachmentArgs
            {
                Role      = eksRole.Name,
                PolicyArn = policy,
            });
        }

        // Create an IAM role that can be used by our service's task.
        var nodeGroupRole = new Iam.Role("nodegroup-iam-role", new Iam.RoleArgs
        {
            AssumeRolePolicy = @"{
""Version"": ""2008-10-17"",
""Statement"": [{
    ""Sid"": """",
    ""Effect"": ""Allow"",
    ""Principal"": {
        ""Service"": ""ec2.amazonaws.com""
    },
    ""Action"": ""sts:AssumeRole""
}]
}"
        });

        var nodeGroupPolicies = new Dictionary <string, string>
        {
            { "worker", "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy" },
            { "cni", "arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy" },
            { "registry", "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly" }
        };

        foreach (var(name, policy) in nodeGroupPolicies)
        {
            var taskExecAttach = new Iam.RolePolicyAttachment($"ngpa-{name}",
                                                              new Iam.RolePolicyAttachmentArgs
            {
                Role      = nodeGroupRole.Name,
                PolicyArn = policy,
            });
        }

        var clusterSg = new Ec2.SecurityGroup("cluster-sg", new Ec2.SecurityGroupArgs
        {
            VpcId  = vpcId,
            Egress =
            {
                new Ec2.Inputs.SecurityGroupEgressArgs
                {
                    Protocol   = "-1",
                    FromPort   = 0,
                    ToPort     = 0,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            },
            Ingress =
            {
                new Ec2.Inputs.SecurityGroupIngressArgs
                {
                    Protocol   = "tcp",
                    FromPort   = 80,
                    ToPort     = 80,
                    CidrBlocks ={ "0.0.0.0/0"                  }
                }
            }
        });

        var cluster = new Eks.Cluster("eks-cluster", new Eks.ClusterArgs
        {
            RoleArn   = eksRole.Arn,
            VpcConfig = new ClusterVpcConfigArgs
            {
                PublicAccessCidrs =
                {
                    "0.0.0.0/0",
                },
                SecurityGroupIds =
                {
                    clusterSg.Id,
                },
                SubnetIds = subnetIds,
            },
        });

        var nodeGroup = new Eks.NodeGroup("node-group", new Eks.NodeGroupArgs
        {
            ClusterName   = cluster.Name,
            NodeGroupName = "demo-eks-nodegroup",
            NodeRoleArn   = nodeGroupRole.Arn,
            SubnetIds     = subnetIds,
            ScalingConfig = new NodeGroupScalingConfigArgs
            {
                DesiredSize = 2,
                MaxSize     = 2,
                MinSize     = 2
            },
        });

        this.Kubeconfig = GenerateKubeconfig(cluster.Endpoint,
                                             cluster.CertificateAuthority.Apply(x => x.Data),
                                             cluster.Name);

        var k8sProvider = new K8s.Provider("k8s-provider", new K8s.ProviderArgs
        {
            KubeConfig = this.Kubeconfig
        }, new CustomResourceOptions
        {
            DependsOn = { nodeGroup },
        });

        var appNamespace = new CoreV1.Namespace("app-ns", new NamespaceArgs
        {
            Metadata = new ObjectMetaArgs
            {
                Name = "joe-duffy",
            },
        }, new CustomResourceOptions
        {
            Provider = k8sProvider,
        });

        var appLabels = new InputMap <string>
        {
            { "app", "iac-workshop" }
        };
        var deployment = new AppsV1.Deployment("app-dep", new DeploymentArgs
        {
            Metadata = new ObjectMetaArgs
            {
                Namespace = appNamespace.Metadata.Apply(x => x.Name),
            },
            Spec = new DeploymentSpecArgs
            {
                Selector = new LabelSelectorArgs
                {
                    MatchLabels = appLabels
                },
                Replicas = 1,
                Template = new PodTemplateSpecArgs
                {
                    Metadata = new ObjectMetaArgs
                    {
                        Labels = appLabels
                    },
                    Spec = new PodSpecArgs
                    {
                        Containers =
                        {
                            new ContainerArgs
                            {
                                Name  = "iac-workshop",
                                Image = "jocatalin/kubernetes-bootcamp:v2",
                            }
                        }
                    }
                }
            },
        }, new CustomResourceOptions
        {
            Provider = k8sProvider,
        });

        var service = new CoreV1.Service("app-service", new ServiceArgs
        {
            Metadata = new ObjectMetaArgs
            {
                Namespace = appNamespace.Metadata.Apply(x => x.Name),
                Labels    = deployment.Spec.Apply(spec => spec.Template.Metadata.Labels),
            },
            Spec = new ServiceSpecArgs
            {
                Type  = "LoadBalancer",
                Ports =
                {
                    new ServicePortArgs
                    {
                        Port       = 80,
                        TargetPort = 8080
                    },
                },
                Selector = deployment.Spec.Apply(spec => spec.Template.Metadata.Labels)
            },
        }, new CustomResourceOptions
        {
            Provider = k8sProvider,
        });

        this.Url = service.Status.Apply(status => status.LoadBalancer.Ingress[0].Hostname);
    }
Exemplo n.º 22
0
    public MyStack()
    {
        var ami = Pulumi.Aws.GetAmi.InvokeAsync(new Pulumi.Aws.GetAmiArgs
        {
            Filters =
            {
                new GetAmiFilterArgs
                {
                    Name   = "name",
                    Values ={ "amzn-ami-hvm-*"              },
                },
            },
            Owners     = { "137112412989" }, // This owner ID is Amazon
            MostRecent = true,
        }).Result;

        var securityGroup = new Pulumi.Aws.Ec2.SecurityGroup($"webserver-secgrp-1", new SecurityGroupArgs
        {
            Ingress = new SecurityGroupIngressArgs {
                Protocol = "tcp", FromPort = 22, ToPort = 22, CidrBlocks = { "0.0.0.0/0" }
            }
        });

        var spotRequest = new Pulumi.Aws.Ec2.SpotInstanceRequest($"dev-request-1", new SpotInstanceRequestArgs
        {
            Ami                = ami.ImageId,
            InstanceType       = "t2.micro",
            SpotPrice          = "0.04",
            Tags               = { { "Name", "testing" }, { "env", "dev" }, },
            WaitForFulfillment = true
        });

        //What is the best way from here on out to add Tags to the resulting SpotInstance created from the resource above?

        //---------------- OPTION 1 ----------------
        //Do some sort of wait in a for loop to check for the spotRequest.SpotInstanceId?
        //If I could get access to the SpotInstanceId, I can leverage the AWS SDK probably to tag the instances.
        //The problem is, I can never get the value of the SpotInstanceId, everything I try just returns: Pulumi.Output`1[System.String]

        //if (!Deployment.Instance.IsDryRun)
        //{
        //    Console.WriteLine($"SpotInstanceId: {spotRequest.SpotInstanceId}");
        //    Console.WriteLine($"SpotInstanceId: {spotRequest.SpotInstanceId.ToString()}");
        //    Console.WriteLine($"SpotInstanceId: {spotRequest.SpotInstanceId.Apply(x => x)}");
        //    Console.WriteLine($"SpotInstanceId: {spotRequest.SpotInstanceId.Apply(x => x.ToString())}");
        //    Console.WriteLine($"SpotInstanceId: {spotRequest.SpotInstanceId.Apply(x => x).ToString()}");

        //    WaitAndTry(spotRequest).Wait();
        //}

        //---------------- END OPTION 1 ---------------



        //---------------- OPTION 2 --------------------
        //Do I have to do a multi-step process to import the resulting instance ID, and then update the tags on the instance that I import?

        //Output the SpotInstanceId
        SpotInstanceId = spotRequest.SpotInstanceId;

        //Run this THE SECOND TIME you run the `pulumi up` command
        ////var stackReference = new StackReference($"replace/with-your/stack");
        ////var instanceId = stackReference.GetValueAsync("SpotInstanceId").Result.ToString();

        ////var ec2Instance = new Pulumi.Aws.Ec2.Instance($"imported-instance", new InstanceArgs
        ////{
        ////    Ami = ami.ImageId,
        ////    InstanceType = "t2.micro",
        ////}, new CustomResourceOptions
        ////{
        ////    DependsOn = spotRequest,
        ////    ImportId = instanceId
        ////});


        //Run this THE THIRD TIME you run the `pulumi up` command
        //////var ec2Instance = new Pulumi.Aws.Ec2.Instance($"imported-instance", new InstanceArgs
        //////{
        //////    Ami = ami.ImageId,
        //////    InstanceType = "t2.micro",
        //////    Tags = { { "Name", "testing" }, { "env", "dev" }, },
        //////}, new CustomResourceOptions
        //////{
        //////    DependsOn = spotRequest,
        //////});


        //---------------- END OPTION 2 ---------------------
    }
Exemplo n.º 23
0
    private async Task <IDictionary <string, Output <string> > > Initialize()
    {
        // VPC
        var eksVpc = new Aws.Ec2.Vpc("eksVpc", new Aws.Ec2.VpcArgs
        {
            CidrBlock          = "10.100.0.0/16",
            InstanceTenancy    = "default",
            EnableDnsHostnames = true,
            EnableDnsSupport   = true,
            Tags =
            {
                { "Name", "pulumi-eks-vpc" },
            },
        });
        var eksIgw = new Aws.Ec2.InternetGateway("eksIgw", new Aws.Ec2.InternetGatewayArgs
        {
            VpcId = eksVpc.Id,
            Tags  =
            {
                { "Name", "pulumi-vpc-ig" },
            },
        });
        var eksRouteTable = new Aws.Ec2.RouteTable("eksRouteTable", new Aws.Ec2.RouteTableArgs
        {
            VpcId  = eksVpc.Id,
            Routes =
            {
                new Aws.Ec2.Inputs.RouteTableRouteArgs
                {
                    CidrBlock = "0.0.0.0/0",
                    GatewayId = eksIgw.Id,
                },
            },
            Tags =
            {
                { "Name", "pulumi-vpc-rt" },
            },
        });
        // Subnets, one for each AZ in a region
        var zones = await Aws.GetAvailabilityZones.InvokeAsync();

        var vpcSubnet = new List <Aws.Ec2.Subnet>();

        foreach (var range in zones.Names.Select((v, k) => new { Key = k, Value = v }))
        {
            vpcSubnet.Add(new Aws.Ec2.Subnet($"vpcSubnet-{range.Key}", new Aws.Ec2.SubnetArgs
            {
                AssignIpv6AddressOnCreation = false,
                VpcId = eksVpc.Id,
                MapPublicIpOnLaunch = true,
                CidrBlock           = $"10.100.{range.Key}.0/24",
                AvailabilityZone    = range.Value,
                Tags =
                {
                    { "Name", $"pulumi-sn-{range.Value}" },
                },
            }));
        }
        var rta = new List <Aws.Ec2.RouteTableAssociation>();

        foreach (var range in zones.Names.Select((v, k) => new { Key = k, Value = v }))
        {
            rta.Add(new Aws.Ec2.RouteTableAssociation($"rta-{range.Key}", new Aws.Ec2.RouteTableAssociationArgs
            {
                RouteTableId = eksRouteTable.Id,
                SubnetId     = vpcSubnet[range.Key].Id,
            }));
        }
        var subnetIds        = vpcSubnet.Select(__item => __item.Id).ToList();
        var eksSecurityGroup = new Aws.Ec2.SecurityGroup("eksSecurityGroup", new Aws.Ec2.SecurityGroupArgs
        {
            VpcId       = eksVpc.Id,
            Description = "Allow all HTTP(s) traffic to EKS Cluster",
            Tags        =
            {
                { "Name", "pulumi-cluster-sg" },
            },
            Ingress =
            {
                new Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    CidrBlocks =
                    {
                        "0.0.0.0/0",
                    },
                    FromPort    = 443,
                    ToPort      = 443,
                    Protocol    = "tcp",
                    Description = "Allow pods to communicate with the cluster API Server.",
                },
                new Aws.Ec2.Inputs.SecurityGroupIngressArgs
                {
                    CidrBlocks =
                    {
                        "0.0.0.0/0",
                    },
                    FromPort    = 80,
                    ToPort      = 80,
                    Protocol    = "tcp",
                    Description = "Allow internet access to pods",
                },
            },
        });
        // EKS Cluster Role
        var eksRole = new Aws.Iam.Role("eksRole", new Aws.Iam.RoleArgs
        {
            AssumeRolePolicy = JsonSerializer.Serialize(new Dictionary <string, object?>
            {
                { "Version", "2012-10-17" },
                { "Statement", new[]
                  {
                      new Dictionary <string, object?>
                      {
                          { "Action", "sts:AssumeRole" },
                          { "Principal", new Dictionary <string, object?>
                            {
                                { "Service", "eks.amazonaws.com" },
                            } },
                          { "Effect", "Allow" },
                          { "Sid", "" },
                      },
                  } },
            }),
        });
        var servicePolicyAttachment = new Aws.Iam.RolePolicyAttachment("servicePolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = eksRole.Id,
            PolicyArn = "arn:aws:iam::aws:policy/AmazonEKSServicePolicy",
        });
        var clusterPolicyAttachment = new Aws.Iam.RolePolicyAttachment("clusterPolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = eksRole.Id,
            PolicyArn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy",
        });
        // EC2 NodeGroup Role
        var ec2Role = new Aws.Iam.Role("ec2Role", new Aws.Iam.RoleArgs
        {
            AssumeRolePolicy = JsonSerializer.Serialize(new Dictionary <string, object?>
            {
                { "Version", "2012-10-17" },
                { "Statement", new[]
                  {
                      new Dictionary <string, object?>
                      {
                          { "Action", "sts:AssumeRole" },
                          { "Principal", new Dictionary <string, object?>
                            {
                                { "Service", "ec2.amazonaws.com" },
                            } },
                          { "Effect", "Allow" },
                          { "Sid", "" },
                      },
                  } },
            }),
        });
        var workerNodePolicyAttachment = new Aws.Iam.RolePolicyAttachment("workerNodePolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = ec2Role.Id,
            PolicyArn = "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy",
        });
        var cniPolicyAttachment = new Aws.Iam.RolePolicyAttachment("cniPolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = ec2Role.Id,
            PolicyArn = "arn:aws:iam::aws:policy/AmazonEKSCNIPolicy",
        });
        var registryPolicyAttachment = new Aws.Iam.RolePolicyAttachment("registryPolicyAttachment", new Aws.Iam.RolePolicyAttachmentArgs
        {
            Role      = ec2Role.Id,
            PolicyArn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
        });
        // EKS Cluster
        var eksCluster = new Aws.Eks.Cluster("eksCluster", new Aws.Eks.ClusterArgs
        {
            RoleArn = eksRole.Arn,
            Tags    =
            {
                { "Name", "pulumi-eks-cluster" },
            },
            VpcConfig = new Aws.Eks.Inputs.ClusterVpcConfigArgs
            {
                PublicAccessCidrs =
                {
                    "0.0.0.0/0",
                },
                SecurityGroupIds =
                {
                    eksSecurityGroup.Id,
                },
                SubnetIds = subnetIds,
            },
        });
        var nodeGroup = new Aws.Eks.NodeGroup("nodeGroup", new Aws.Eks.NodeGroupArgs
        {
            ClusterName   = eksCluster.Name,
            NodeGroupName = "pulumi-eks-nodegroup",
            NodeRoleArn   = ec2Role.Arn,
            SubnetIds     = subnetIds,
            Tags          =
            {
                { "Name", "pulumi-cluster-nodeGroup" },
            },
            ScalingConfig = new Aws.Eks.Inputs.NodeGroupScalingConfigArgs
            {
                DesiredSize = 2,
                MaxSize     = 2,
                MinSize     = 1,
            },
        });
        var clusterName = eksCluster.Name;
        var kubeconfig  = Output.Tuple(eksCluster.Endpoint, eksCluster.CertificateAuthority, eksCluster.Name).Apply(values =>
        {
            var endpoint             = values.Item1;
            var certificateAuthority = values.Item2;
            var name = values.Item3;
            return(JsonSerializer.Serialize(new Dictionary <string, object?>
            {
                { "apiVersion", "v1" },
                { "clusters", new[]
                  {
                      new Dictionary <string, object?>
                      {
                          { "cluster", new Dictionary <string, object?>
                            {
                                { "server", endpoint },
                                { "certificate-authority-data", certificateAuthority.Data },
                            } },
                          { "name", "kubernetes" },
                      },
                  } },
                { "contexts", new[]
                  {
                      new Dictionary <string, object?>
                      {
                          { "contest", new Dictionary <string, object?>
                            {
                                { "cluster", "kubernetes" },
                                { "user", "aws" },
                            } },
                      },
                  } },
                { "current-context", "aws" },
                { "kind", "Config" },
                { "users", new[]
                  {
                      new Dictionary <string, object?>
                      {
                          { "name", "aws" },
                          { "user", new Dictionary <string, object?>
                            {
                                { "exec", new Dictionary <string, object?>
                                    {
                                        { "apiVersion", "client.authentication.k8s.io/v1alpha1" },
                                        { "command", "aws-iam-authenticator" },
                                    } },
                                { "args", new[]
                                    {
                                        "token",
                                        "-i",
                                        name,
                                    } },
                            } },
                      },
                  } },
            }));
        });

        return(new Dictionary <string, Output <string> >
        {
            { "clusterName", clusterName },
            { "kubeconfig", kubeconfig },
        });
    }