class Instance (construct)
Language | Type name |
---|---|
.NET | Amazon.CDK.AWS.EC2.Instance |
Go | github.com/aws/aws-cdk-go/awscdk/v2/awsec2#Instance |
Java | software.amazon.awscdk.services.ec2.Instance |
Python | aws_cdk.aws_ec2.Instance |
TypeScript (source) | aws-cdk-lib » aws_ec2 » Instance |
Implements
IConstruct
, IDependable
, IResource
, IInstance
, IConnectable
, IGrantable
This represents a single EC2 instance.
Example
declare const vpc: ec2.IVpc;
const lb = new elb.LoadBalancer(this, 'LB', {
vpc,
internetFacing: true,
});
// instance to add as the target for load balancer.
const instance = new ec2.Instance(this, 'targetInstance', {
vpc: vpc,
instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
machineImage: new ec2.AmazonLinuxImage({ generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2 }),
});
lb.addTarget(new elb.InstanceTarget(instance));
Initializer
new Instance(scope: Construct, id: string, props: InstanceProps)
Parameters
- scope
Construct
- id
string
- props
Instance
Props
Construct Props
Name | Type | Description |
---|---|---|
instance | Instance | Type of instance to launch. |
machine | IMachine | AMI to launch. |
vpc | IVpc | VPC to launch the instance in. |
allow | boolean | Whether the instance could initiate IPv6 connections to anywhere by default. |
allow | boolean | Whether the instance could initiate connections to anywhere by default. |
associate | boolean | Whether to associate a public IP address to the primary network interface attached to this instance. |
availability | string | In which AZ to place the instance within the VPC. |
block | Block [] | Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes. |
credit | Cpu | Specifying the CPU credit type for burstable EC2 instance types (T2, T3, T3a, etc). |
detailed | boolean | Whether "Detailed Monitoring" is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges. |
disable | boolean | If true, the instance will not be able to be terminated using the Amazon EC2 console, CLI, or API. |
ebs | boolean | Indicates whether the instance is optimized for Amazon EBS I/O. |
enclave | boolean | Whether the instance is enabled for AWS Nitro Enclaves. |
hibernation | boolean | Whether the instance is enabled for hibernation. |
init? | Cloud | Apply the given CloudFormation Init configuration to the instance at startup. |
init | Apply | Use the given options for applying CloudFormation Init. |
instance | Instance | Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). |
instance | string | The name of the instance. |
instance | IInstance | The instance profile used to pass role information to EC2 instances. |
ipv6 | number | The number of IPv6 addresses to associate with the primary network interface. |
key | string | Name of SSH keypair to grant access to instance. |
key | IKey | The SSH keypair to grant access to the instance. |
placement | IPlacement | The placement group that you want to launch the instance into. |
private | string | Defines a private IP address to associate with an instance. |
propagate | boolean | Propagate the EC2 instance tags to the EBS volumes. |
require | boolean | Whether IMDSv2 should be required on this instance. |
resource | Duration | The length of time to wait for the resourceSignalCount. |
role? | IRole | An IAM role to associate with the instance profile assigned to this Auto Scaling Group. |
security | ISecurity | Security Group to assign to this instance. |
source | boolean | Specifies whether to enable an instance launched in a VPC to perform NAT. |
ssm | boolean | Add SSM session permissions to the instance role. |
user | User | Specific UserData to use. |
user | boolean | Changes to the UserData force replacement. |
vpc | Subnet | Where to place the instance within the VPC. |
instanceType
Type:
Instance
Type of instance to launch.
machineImage
Type:
IMachine
AMI to launch.
vpc
Type:
IVpc
VPC to launch the instance in.
allowAllIpv6Outbound?
Type:
boolean
(optional, default: false)
Whether the instance could initiate IPv6 connections to anywhere by default.
This property is only used when you do not provide a security group.
allowAllOutbound?
Type:
boolean
(optional, default: true)
Whether the instance could initiate connections to anywhere by default.
This property is only used when you do not provide a security group.
associatePublicIpAddress?
Type:
boolean
(optional, default: public IP address is automatically assigned based on default behavior)
Whether to associate a public IP address to the primary network interface attached to this instance.
You cannot specify this property and ipv6AddressCount
at the same time.
availabilityZone?
Type:
string
(optional, default: Random zone.)
In which AZ to place the instance within the VPC.
blockDevices?
Type:
Block
[]
(optional, default: Uses the block device mapping of the AMI)
Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes.
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.
See also: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html
creditSpecification?
Type:
Cpu
(optional, default: T2 instances are standard, while T3, T4g, and T3a instances are unlimited.)
Specifying the CPU credit type for burstable EC2 instance types (T2, T3, T3a, etc).
The unlimited CPU credit option is not supported for T3 instances with a dedicated host.
detailedMonitoring?
Type:
boolean
(optional, default: false)
Whether "Detailed Monitoring" is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges.
See also: http://aws.amazon.com/cloudwatch/pricing/
disableApiTermination?
Type:
boolean
(optional, default: false)
If true, the instance will not be able to be terminated using the Amazon EC2 console, CLI, or API.
To change this attribute after launch, use ModifyInstanceAttribute. Alternatively, if you set InstanceInitiatedShutdownBehavior to terminate, you can terminate the instance by running the shutdown command from the instance.
ebsOptimized?
Type:
boolean
(optional, default: false)
Indicates whether the instance is optimized for Amazon EBS I/O.
This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal Amazon EBS I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS-optimized instance.
enclaveEnabled?
Type:
boolean
(optional, default: false)
Whether the instance is enabled for AWS Nitro Enclaves.
Nitro Enclaves requires a Nitro-based virtualized parent instance with specific Intel/AMD with at least 4 vCPUs or Graviton with at least 2 vCPUs instance types and Linux/Windows host OS, while the enclave itself supports only Linux OS.
You can't set both enclaveEnabled
and hibernationEnabled
to true on the same instance.
See also: https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html#nitro-enclave-reqs
hibernationEnabled?
Type:
boolean
(optional, default: false)
Whether the instance is enabled for hibernation.
You can't set both enclaveEnabled
and hibernationEnabled
to true on the same instance.
init?
Type:
Cloud
(optional, default: no CloudFormation init)
Apply the given CloudFormation Init configuration to the instance at startup.
initOptions?
Type:
Apply
(optional, default: default options)
Use the given options for applying CloudFormation Init.
Describes the configsets to use and the timeout to wait
instanceInitiatedShutdownBehavior?
Type:
Instance
(optional, default: InstanceInitiatedShutdownBehavior.STOP)
Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown).
instanceName?
Type:
string
(optional, default: CDK generated name)
The name of the instance.
instanceProfile?
Type:
IInstance
(optional, default: No instance profile)
The instance profile used to pass role information to EC2 instances.
Note: You can provide an instanceProfile or a role, but not both.
ipv6AddressCount?
Type:
number
(optional, default: For instances associated with an IPv6 subnet, use 1; otherwise, use 0.)
The number of IPv6 addresses to associate with the primary network interface.
Amazon EC2 chooses the IPv6 addresses from the range of your subnet.
You cannot specify this property and associatePublicIpAddress
at the same time.
keyName?
⚠️ Deprecated: - Use keyPair
instead - https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2-readme.html#using-an-existing-ec2-key-pair
Type:
string
(optional, default: No SSH access will be possible.)
Name of SSH keypair to grant access to instance.
keyPair?
Type:
IKey
(optional, default: No SSH access will be possible.)
The SSH keypair to grant access to the instance.
placementGroup?
Type:
IPlacement
(optional, default: no placement group will be used for this instance.)
The placement group that you want to launch the instance into.
privateIpAddress?
Type:
string
(optional, default: no association)
Defines a private IP address to associate with an instance.
Private IP should be available within the VPC that the instance is build within.
propagateTagsToVolumeOnCreation?
Type:
boolean
(optional, default: false)
Propagate the EC2 instance tags to the EBS volumes.
requireImdsv2?
Type:
boolean
(optional, default: false)
Whether IMDSv2 should be required on this instance.
resourceSignalTimeout?
Type:
Duration
(optional, default: Duration.minutes(5))
The length of time to wait for the resourceSignalCount.
The maximum value is 43200 (12 hours).
role?
Type:
IRole
(optional, default: A role will automatically be created, it can be accessed via the role
property)
An IAM role to associate with the instance profile assigned to this Auto Scaling Group.
The role must be assumable by the service principal ec2.amazonaws.com
:
Note: You can provide an instanceProfile or a role, but not both.
Example
const role = new iam.Role(this, 'MyRole', {
assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
});
securityGroup?
Type:
ISecurity
(optional, default: create new security group)
Security Group to assign to this instance.
sourceDestCheck?
Type:
boolean
(optional, default: true)
Specifies whether to enable an instance launched in a VPC to perform NAT.
This controls whether source/destination checking is enabled on the instance. A value of true means that checking is enabled, and false means that checking is disabled. The value must be false for the instance to perform NAT.
ssmSessionPermissions?
Type:
boolean
(optional, default: false)
Add SSM session permissions to the instance role.
Setting this to true
adds the necessary permissions to connect
to the instance using SSM Session Manager. You can do this
from the AWS Console.
NOTE: Setting this flag to true
may not be enough by itself.
You must also use an AMI that comes with the SSM Agent, or install
the SSM Agent yourself. See
Working with SSM Agent
in the SSM Developer Guide.
userData?
Type:
User
(optional, default: A UserData object appropriate for the MachineImage's
Operating System is created.)
Specific UserData to use.
The UserData may still be mutated after creation.
userDataCausesReplacement?
Type:
boolean
(optional, default: true if initOptions
is specified, false otherwise.)
Changes to the UserData force replacement.
Depending the EC2 instance type, changing UserData either restarts the instance or replaces the instance.
- Instance store-backed instances are replaced.
- EBS-backed instances are restarted.
By default, restarting does not execute the new UserData so you will need a different mechanism to ensure the instance is restarted.
Setting this to true
will make the instance's Logical ID depend on the
UserData, which will cause CloudFormation to replace it if the UserData
changes.
vpcSubnets?
Type:
Subnet
(optional, default: Private subnets.)
Where to place the instance within the VPC.
Properties
Name | Type | Description |
---|---|---|
connections | Connections | Allows specify security group connections for the instance. |
env | Resource | The environment this resource belongs to. |
grant | IPrincipal | The principal to grant permissions to. |
instance | Cfn | the underlying instance resource. |
instance | string | The availability zone the instance was launched in. |
instance | string | The instance's ID. |
instance | string | Private DNS name for this instance. |
instance | string | Private IP for this instance. |
instance | string | Publicly-routable DNS name for this instance. |
instance | string | Publicly-routable IP address for this instance. |
node | Node | The tree node. |
os | Operating | The type of OS the instance is running. |
role | IRole | The IAM role assumed by the instance. |
stack | Stack | The stack in which this resource is defined. |
user | User | UserData for the instance. |
connections
Type:
Connections
Allows specify security group connections for the instance.
env
Type:
Resource
The environment this resource belongs to.
For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.
grantPrincipal
Type:
IPrincipal
The principal to grant permissions to.
instance
Type:
Cfn
the underlying instance resource.
instanceAvailabilityZone
Type:
string
The availability zone the instance was launched in.
instanceId
Type:
string
The instance's ID.
instancePrivateDnsName
Type:
string
Private DNS name for this instance.
instancePrivateIp
Type:
string
Private IP for this instance.
instancePublicDnsName
Type:
string
Publicly-routable DNS name for this instance.
(May be an empty string if the instance does not have a public name).
instancePublicIp
Type:
string
Publicly-routable IP address for this instance.
(May be an empty string if the instance does not have a public IP).
node
Type:
Node
The tree node.
osType
Type:
Operating
The type of OS the instance is running.
role
Type:
IRole
The IAM role assumed by the instance.
stack
Type:
Stack
The stack in which this resource is defined.
userData
Type:
User
UserData for the instance.
Methods
Name | Description |
---|---|
add | Add the security group to the instance. |
add | Adds a statement to the IAM role assumed by the instance. |
add | Add command to the startup script of the instance. |
apply | Use a CloudFormation Init configuration at instance startup. |
apply | Apply the given removal policy to this resource. |
to | Returns a string representation of this construct. |
addSecurityGroup(securityGroup)
public addSecurityGroup(securityGroup: ISecurityGroup): void
Parameters
- securityGroup
ISecurity
— : The security group to add.Group
Add the security group to the instance.
addToRolePolicy(statement)
public addToRolePolicy(statement: PolicyStatement): void
Parameters
- statement
Policy
Statement
Adds a statement to the IAM role assumed by the instance.
addUserData(...commands)
public addUserData(...commands: string[]): void
Parameters
- commands
string
Add command to the startup script of the instance.
The command must be in the scripting language supported by the instance's OS (i.e. Linux/Windows).
applyCloudFormationInit(init, options?)
public applyCloudFormationInit(init: CloudFormationInit, options?: ApplyCloudFormationInitOptions): void
Parameters
- init
Cloud
Formation Init - options
Apply
Cloud Formation Init Options
Use a CloudFormation Init configuration at instance startup.
This does the following:
- Attaches the CloudFormation Init metadata to the Instance resource.
- Add commands to the instance UserData to run
cfn-init
andcfn-signal
. - Update the instance's CreationPolicy to wait for the
cfn-signal
commands.
applyRemovalPolicy(policy)
public applyRemovalPolicy(policy: RemovalPolicy): void
Parameters
- policy
Removal
Policy
Apply the given removal policy to this resource.
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
).
toString()
public toString(): string
Returns
string
Returns a string representation of this construct.