Skip to content
v2.274.0

BastionHostLinux L2 construct ​

This creates a linux bastion host you can use to connect to other instances or services in your VPC.

The recommended way to connect to the bastion host is by using AWS Systems Manager Session Manager.

The operating system is Amazon Linux 2 with the latest SSM agent installed

You can also configure this bastion host to allow connections via SSH

Example ​

ts
const host = new ec2.BastionHostLinux(this, 'BastionHost', {
  vpc,
  blockDevices: [{
    deviceName: '/dev/sdh',
    volume: ec2.BlockDeviceVolume.ebs(10, {
      encrypted: true,
    }),
  }],
});
python
host = ec2.BastionHostLinux(self, "BastionHost",
    vpc=vpc,
    block_devices=[ec2.BlockDevice(
        device_name="/dev/sdh",
        volume=ec2.BlockDeviceVolume.ebs(10,
            encrypted=True
        )
    )]
)
java
BastionHostLinux host = BastionHostLinux.Builder.create(this, "BastionHost")
        .vpc(vpc)
        .blockDevices(List.of(BlockDevice.builder()
                .deviceName("/dev/sdh")
                .volume(BlockDeviceVolume.ebs(10, EbsDeviceOptions.builder()
                        .encrypted(true)
                        .build()))
                .build()))
        .build();
csharp
// Install: dotnet add package Amazon.CDK.Lib
var host = new BastionHostLinux(this, "BastionHost", new BastionHostLinuxProps {
    Vpc = vpc,
    BlockDevices = new [] { new BlockDevice {
        DeviceName = "/dev/sdh",
        Volume = BlockDeviceVolume.Ebs(10, new EbsDeviceOptions {
            Encrypted = true
        })
    } }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
host := ec2.NewBastionHostLinux(this, jsii.String("BastionHost"), &BastionHostLinuxProps{
	Vpc: Vpc,
	BlockDevices: []BlockDevice{
		&BlockDevice{
			DeviceName: jsii.String("/dev/sdh"),
			Volume: ec2.BlockDeviceVolume_Ebs(jsii.Number(10), &EbsDeviceOptions{
				Encrypted: jsii.Boolean(true),
			}),
		},
	},
})

Initializer ​

ts
new BastionHostLinux(scope: Construct, id: string, props: BastionHostLinuxProps)
python
BastionHostLinux(scope: Construct, id: str, props: BastionHostLinuxProps)
java
new BastionHostLinux(Construct scope, String id, BastionHostLinuxProps props)
csharp
new BastionHostLinux(Construct scope, string id, BastionHostLinuxProps props)
go
NewBastionHostLinux(Scope Construct, Id *string, Props BastionHostLinuxProps)

Construct Props ​

availabilityZonestringavailability_zonestravailabilityZoneStringAvailabilityZonestringAvailabilityZone*string= Random zone.#
In which AZ to place the instance within the VPC.
blockDevicesBlockDevice[]block_devicestyping.List[BlockDevice]blockDevicesList<BlockDevice>BlockDevicesBlockDevice[]BlockDevices*[]BlockDevice= Uses the block device mapping of…#
Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
notes · default

Each instance that is launched has an associated root device volume, either an Amazon EBS volume or an instance store volume. You can use block device mappings to specify additional EBS volumes or instance store volumes to attach to an instance when it is launched.

Default: Uses the block device mapping of the AMI

Apply the given CloudFormation Init configuration to the instance at startup.
Use the given options for applying CloudFormation Init.

Describes the configsets to use and the timeout to wait

instanceNamestringinstance_namestrinstanceNameStringInstanceNamestringInstanceName*string= 'BastionHost'#
The name of the instance.
instanceTypeInstanceTypeinstance_typeInstanceTypeinstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceTypeInstanceType= 't3.nano'#
Type of instance to launch.
machineImageIMachineImagemachine_imageIMachineImagemachineImageIMachineImageMachineImageIMachineImageMachineImageIMachineImage= An Amazon Linux 2023 image if th…#
The machine image to use, assumed to have SSM Agent preinstalled.
default

Default: An Amazon Linux 2023 image if the @aws-cdk/aws-ec2:bastionHostUseAmazonLinux2023ByDefault feature flag is enabled. Otherwise, an Amazon Linux 2 image. In both cases, the image is kept up-to-date automatically (the instance may be replaced on every deployment) and already has SSM Agent installed.

requireImdsv2booleanrequire_imdsv2boolrequireImdsv2BooleanRequireImdsv2boolRequireImdsv2*bool= false#
Whether IMDSv2 should be required on this instance.
securityGroupISecurityGroupsecurity_groupISecurityGroupsecurityGroupISecurityGroupSecurityGroupISecurityGroupSecurityGroupISecurityGroup= create new security group with n…#
Security Group to assign to this instance.
default

Default: create new security group with no inbound and all outbound traffic allowed

subnetSelectionSubnetSelectionsubnet_selectionSubnetSelectionsubnetSelectionSubnetSelectionSubnetSelectionSubnetSelectionSubnetSelectionSubnetSelection= private subnets of the supplied …#
Select the subnets to run the bastion host in.

Set this to PUBLIC if you need to connect to this instance via the internet and cannot use SSM. You have to allow port 22 manually by using the connections field

default

Default: private subnets of the supplied VPC

userDataCausesReplacementbooleanuser_data_causes_replacementbooluserDataCausesReplacementBooleanUserDataCausesReplacementboolUserDataCausesReplacement*bool= `true` if `initOptions` is speci…#
Determines whether changes to the UserData will force instance replacement.
notes · default

Depending on the EC2 instance type, modifying the UserData may either restart or replace the instance:

  • Instance store-backed instances are replaced.
  • EBS-backed instances are restarted.

Note that by default, restarting does not execute the updated UserData, so an alternative mechanism is needed to ensure the instance re-executes the UserData.

When set to true, the instance's Logical ID will depend on the UserData, causing CloudFormation to replace the instance if the UserData changes.

Default: true if initOptions is specified, otherwise false.

vpcIVpcvpcIVpcvpcIVpcVpcIVpcVpcIVpcrequired#
VPC to launch the instance in.

Properties ​

connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Allows specify security group connections for the instance.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#
The principal to grant permissions to.
instanceInstanceinstanceInstanceinstanceInstanceInstanceInstanceInstanceInstancerequired#
The underlying instance resource.
instanceAvailabilityZonestringinstance_availability_zonestrinstanceAvailabilityZoneStringInstanceAvailabilityZonestringInstanceAvailabilityZone*stringrequired#
The availability zone the instance was launched in.
instanceIdstringinstance_idstrinstanceIdStringInstanceIdstringInstanceId*stringrequired#
The instance's ID.
instancePrivateDnsNamestringinstance_private_dns_namestrinstancePrivateDnsNameStringInstancePrivateDnsNamestringInstancePrivateDnsName*stringrequired#
Private DNS name for this instance.
instancePrivateIpstringinstance_private_ipstrinstancePrivateIpStringInstancePrivateIpstringInstancePrivateIp*stringrequired#
Private IP for this instance.
instancePublicDnsNamestringinstance_public_dns_namestrinstancePublicDnsNameStringInstancePublicDnsNamestringInstancePublicDnsName*stringrequired#
Publicly-routable DNS name for this instance.

(May be an empty string if the instance does not have a public name).

instancePublicIpstringinstance_public_ipstrinstancePublicIpStringInstancePublicIpstringInstancePublicIp*stringrequired#
Publicly-routable IP address for this instance.

(May be an empty string if the instance does not have a public IP).

instanceRefInstanceReferenceinstance_refInstanceReferenceinstanceRefInstanceReferenceInstanceRefInstanceReferenceInstanceRefInstanceReferencerequired#
A reference to a Instance resource.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
roleIRoleroleIRoleroleIRoleRoleIRoleRoleIRolerequired#
The IAM role assumed by the instance.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

allowSshAccessFrom(...peer: IPeer[]): voiddef allow_ssh_access_from(self, peer: IPeer) -> Nonepublic void allowSshAccessFrom(IPeer peer)public void AllowSshAccessFrom(IPeer peer)func AllowSshAccessFrom(Peer IPeer)#
Allow SSH access from the given peer or peers.

Necessary if you want to connect to the instance using ssh. If not called, you should use SSM Session Manager to connect to the instance.

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.