How to use the @aws-cdk/aws-ec2.SecurityGroup function in @aws-cdk/aws-ec2

To help you get started, we’ve selected a few @aws-cdk/aws-ec2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github aws / aws-cdk / packages / @aws-cdk / aws-stepfunctions-tasks / lib / sagemaker-train-task.ts View on Github external
]
                }),
            }
        });

        if (this.props.outputDataConfig.encryptionKey) {
            this.props.outputDataConfig.encryptionKey.grantEncrypt(this._role);
        }

        if (this.props.resourceConfig && this.props.resourceConfig.volumeEncryptionKey) {
            this.props.resourceConfig.volumeEncryptionKey.grant(this._role, 'kms:CreateGrant');
        }

        // create a security group if not defined
        if (this.vpc && this.securityGroup === undefined) {
            this.securityGroup = new ec2.SecurityGroup(task, 'TrainJobSecurityGroup', {
                vpc: this.vpc
            });
            this.connections.addSecurityGroup(this.securityGroup);
            this.securityGroups.push(this.securityGroup);
        }

        return {
          resourceArn: getResourceArn("sagemaker", "createTrainingJob", this.integrationPattern),
          parameters: this.renderParameters(),
          policyStatements: this.makePolicyStatements(task),
        };
    }
github aws-samples / aws-reinvent-2019-trivia-game / trivia-backend / infra / codedeploy-blue-green / infra-setup.ts View on Github external
constructor(parent: cdk.App, name: string, props: TriviaBackendStackProps) {
    super(parent, name, props);

    // Network infrastructure
    const vpc = new Vpc(this, 'VPC', { maxAzs: 2 });
    const serviceSG = new SecurityGroup(this, 'ServiceSecurityGroup', { vpc });

    // Lookup pre-existing TLS certificate
    const certificateArn = StringParameter.fromStringParameterAttributes(this, 'CertArnParameter', {
      parameterName: 'CertificateArn-' + props.domainName
    }).stringValue;

    // Load balancer
    const loadBalancer = new ApplicationLoadBalancer(this, 'ServiceLB', {
      vpc,
      internetFacing: true
    });
    serviceSG.connections.allowFrom(loadBalancer, Port.tcp(80));

    const domainZone = HostedZone.fromLookup(this, 'Zone', { domainName: props.domainZone });
    new ARecord(this, "DNS", {
      zone: domainZone,
github aws / aws-cdk / packages / @aws-cdk / aws-elasticloadbalancing / lib / load-balancer.ts View on Github external
constructor(scope: cdk.Construct, id: string, props: LoadBalancerProps) {
    super(scope, id);

    this.securityGroup = new SecurityGroup(this, 'SecurityGroup', { vpc: props.vpc, allowAllOutbound: false });
    this.connections = new Connections({ securityGroups: [this.securityGroup] });

    // Depending on whether the ELB has public or internal IPs, pick the right backend subnets
    const subnets: IVpcSubnet[] = props.internetFacing ? props.vpc.publicSubnets : props.vpc.privateSubnets;

    this.elb = new CfnLoadBalancer(this, 'Resource', {
      securityGroups: [ this.securityGroup.securityGroupId ],
      subnets: subnets.map(s => s.subnetId),
      listeners: new cdk.Token(() => this.listeners),
      scheme: props.internetFacing ? 'internet-facing' : 'internal',
      healthCheck: props.healthCheck && healthCheckToJSON(props.healthCheck),
    });
    if (props.internetFacing) {
      this.elb.node.addDependency(...subnets.map(s => s.internetConnectivityEstablished));
    }
github aws-samples / aws-cdk-changelogs-demo / custom-constructs / redis.js View on Github external
constructor(scope, id, props) {
    super(scope, id);

    const targetVpc = props.vpc;

    // Define a group for telling Elasticache which subnets to put cache nodes in.
    const subnetGroup = new elasticache.CfnSubnetGroup(this, `${id}-subnet-group`, {
      description: `List of subnets used for redis cache ${id}`,
      subnetIds: targetVpc.privateSubnets.map(function(subnet) {
        return subnet.subnetId;
      })
    });

    // The security group that defines network level access to the cluster
    this.securityGroup = new ec2.SecurityGroup(this, `${id}-security-group`, { vpc: targetVpc });

    this.connections = new ec2.Connections({
      securityGroups: [this.securityGroup],
      defaultPortRange: new ec2.TcpPort(6379)
    });

    // The cluster resource itself.
    this.cluster = new elasticache.CfnCacheCluster(this, `${id}-cluster`, {
      cacheNodeType: 'cache.t2.micro',
      engine: 'redis',
      numCacheNodes: 1,
      autoMinorVersionUpgrade: true,
      cacheSubnetGroupName: subnetGroup.subnetGroupName,
      vpcSecurityGroupIds: [
        this.securityGroup.securityGroupId
      ]
github aws / aws-cdk / packages / @aws-cdk / aws-stepfunctions-tasks / lib / run-ecs-task-base.ts View on Github external
public bind(task: sfn.Task): sfn.StepFunctionsTaskConfig {
    if (this.networkConfiguration !== undefined) {
      // Make sure we have a security group if we're using AWSVPC networking
      if (this.securityGroup === undefined) {
        this.securityGroup = new ec2.SecurityGroup(task, 'SecurityGroup', { vpc: this.props.cluster.vpc });
      }
      this.connections.addSecurityGroup(this.securityGroup);
    }

    return {
      resourceArn: getResourceArn("ecs", "runTask", this.integrationPattern),
      parameters: {
        Cluster: this.props.cluster.clusterArn,
        TaskDefinition: this.props.taskDefinition.taskDefinitionArn,
        NetworkConfiguration: this.networkConfiguration,
        Overrides: renderOverrides(this.props.containerOverrides),
        ...this.props.parameters,
      },
      policyStatements: this.makePolicyStatements(task),
    };
  }
github aws / aws-cdk / packages / @aws-cdk / aws-eks-legacy / lib / cluster.ts View on Github external
const stack = Stack.of(this);

    this.vpc = props.vpc || new ec2.Vpc(this, 'DefaultVpc');
    this.version = props.version;

    this.tagSubnets();

    this.role = props.role || new iam.Role(this, 'ClusterRole', {
      assumedBy: new iam.ServicePrincipal('eks.amazonaws.com'),
      managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEKSClusterPolicy'),
        iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonEKSServicePolicy'),
      ],
    });

    const securityGroup = props.securityGroup || new ec2.SecurityGroup(this, 'ControlPlaneSecurityGroup', {
      vpc: this.vpc,
      description: 'EKS Control Plane Security Group',
    });

    this.connections = new ec2.Connections({
      securityGroups: [securityGroup],
      defaultPort: ec2.Port.tcp(443), // Control Plane has an HTTPS API
    });

    // Get subnetIds for all selected subnets
    const placements = props.vpcSubnets || [{ subnetType: ec2.SubnetType.PUBLIC }, { subnetType: ec2.SubnetType.PRIVATE }];
    const subnetIds = [...new Set(Array().concat(...placements.map(s => this.vpc.selectSubnets(s).subnetIds)))];

    const clusterProps: CfnClusterProps = {
      name: this.physicalName,
      roleArn: this.role.roleArn,
github aws / aws-cdk / packages / @aws-cdk / aws-events-targets / lib / ecs-task.ts View on Github external
constructor(private readonly props: EcsTaskProps) {
    this.cluster = props.cluster;
    this.taskDefinition = props.taskDefinition;
    this.taskCount = props.taskCount !== undefined ? props.taskCount : 1;

    if (this.taskDefinition.networkMode === ecs.NetworkMode.AWS_VPC) {
      const securityGroup = props.securityGroup || this.taskDefinition.node.tryFindChild('SecurityGroup') as ec2.ISecurityGroup;
      this.securityGroup = securityGroup || new ec2.SecurityGroup(this.taskDefinition, 'SecurityGroup', { vpc: this.props.cluster.vpc });
    }
  }
github aws / aws-cdk / packages / @aws-cdk / aws-rds / lib / secret-rotation.ts View on Github external
constructor(scope: Construct, id: string, props: SecretRotationProps) {
    super(scope, id);

    if (!props.target.connections.defaultPort) {
      throw new Error('The `target` connections must have a default port range.');
    }

    const rotationFunctionName = this.node.uniqueId;

    const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
      vpc: props.vpc
    });

    const { subnetIds } = props.vpc.selectSubnets(props.vpcSubnets);

    props.target.connections.allowDefaultPortFrom(securityGroup);

    const application = new serverless.CfnApplication(this, 'Resource', {
      location: props.application,
      parameters: {
        endpoint: `https://secretsmanager.${Stack.of(this).region}.${Stack.of(this).urlSuffix}`,
        functionName: rotationFunctionName,
        vpcSecurityGroupIds: securityGroup.securityGroupId,
        vpcSubnetIds: subnetIds.join(',')
      }
    });
github aws / aws-cdk / packages / @aws-cdk / aws-elasticloadbalancingv2 / lib / alb / application-load-balancer.ts View on Github external
constructor(scope: Construct, id: string, props: ApplicationLoadBalancerProps) {
    super(scope, id, props, {
      type: "application",
      securityGroups: Lazy.listValue({ produce: () => [this.securityGroup.securityGroupId] }),
      ipAddressType: props.ipAddressType,
    });

    this.securityGroup = props.securityGroup || new ec2.SecurityGroup(this, 'SecurityGroup', {
      vpc: props.vpc,
      description: `Automatically created Security Group for ELB ${this.node.uniqueId}`,
      allowAllOutbound: false
    });
    this.connections = new ec2.Connections({ securityGroups: [this.securityGroup] });

    if (props.http2Enabled === false) { this.setAttribute('routing.http2.enabled', 'false'); }
    if (props.idleTimeout !== undefined) { this.setAttribute('idle_timeout.timeout_seconds', props.idleTimeout.toSeconds().toString()); }
  }
github aws / aws-cdk / packages / @aws-cdk / aws-codebuild / lib / project.ts View on Github external
private configureVpc(props: ProjectProps): CfnProject.VpcConfigProperty | undefined {
    if ((props.securityGroups || props.allowAllOutbound !== undefined) && !props.vpc) {
      throw new Error(`Cannot configure 'securityGroup' or 'allowAllOutbound' without configuring a VPC`);
    }

    if (!props.vpc) { return undefined; }

    if ((props.securityGroups && props.securityGroups.length > 0) && props.allowAllOutbound !== undefined) {
      throw new Error(`Configure 'allowAllOutbound' directly on the supplied SecurityGroup.`);
    }

    let securityGroups: ec2.ISecurityGroup[];
    if (props.securityGroups && props.securityGroups.length > 0) {
      securityGroups = props.securityGroups;
    } else {
      const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
        vpc: props.vpc,
        description: 'Automatic generated security group for CodeBuild ' + this.node.uniqueId,
        allowAllOutbound: props.allowAllOutbound
      });
      securityGroups = [securityGroup];
    }
    this._connections = new ec2.Connections({ securityGroups });

    return {
      vpcId: props.vpc.vpcId,
      subnets: props.vpc.selectSubnets(props.subnetSelection).subnetIds,
      securityGroupIds: this.connections.securityGroups.map(s => s.securityGroupId)
    };
  }