Instance
- class aws_cdk.aws_ec2.Instance(scope, id, *, instance_type, machine_image, vpc, allow_all_ipv6_outbound=None, allow_all_outbound=None, associate_public_ip_address=None, availability_zone=None, block_devices=None, credit_specification=None, detailed_monitoring=None, disable_api_termination=None, ebs_optimized=None, enclave_enabled=None, hibernation_enabled=None, init=None, init_options=None, instance_initiated_shutdown_behavior=None, instance_name=None, ipv6_address_count=None, key_name=None, key_pair=None, placement_group=None, private_ip_address=None, propagate_tags_to_volume_on_creation=None, require_imdsv2=None, resource_signal_timeout=None, role=None, security_group=None, source_dest_check=None, ssm_session_permissions=None, user_data=None, user_data_causes_replacement=None, vpc_subnets=None)
Bases:
Resource
This represents a single EC2 instance.
- ExampleMetadata:
infused
Example:
# vpc: ec2.IVpc lb = elb.LoadBalancer(self, "LB", vpc=vpc, internet_facing=True ) # instance to add as the target for load balancer. instance = ec2.Instance(self, "targetInstance", vpc=vpc, instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO), machine_image=ec2.AmazonLinuxImage(generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2) ) lb.add_target(elb.InstanceTarget(instance))
- Parameters:
scope (
Construct
) –id (
str
) –instance_type (
InstanceType
) – Type of instance to launch.machine_image (
IMachineImage
) – AMI to launch.vpc (
IVpc
) – VPC to launch the instance in.allow_all_ipv6_outbound (
Optional
[bool
]) – Whether the instance could initiate IPv6 connections to anywhere by default. This property is only used when you do not provide a security group. Default: falseallow_all_outbound (
Optional
[bool
]) – Whether the instance could initiate connections to anywhere by default. This property is only used when you do not provide a security group. Default: trueassociate_public_ip_address (
Optional
[bool
]) – Whether to associate a public IP address to the primary network interface attached to this instance. You cannot specify this property andipv6AddressCount
at the same time. Default: - public IP address is automatically assigned based on default behavioravailability_zone (
Optional
[str
]) – In which AZ to place the instance within the VPC. Default: - Random zone.block_devices (
Optional
[Sequence
[Union
[BlockDevice
,Dict
[str
,Any
]]]]) – 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. Default: - Uses the block device mapping of the AMIcredit_specification (
Optional
[CpuCredits
]) – 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. Default: - T2 instances are standard, while T3, T4g, and T3a instances are unlimited.detailed_monitoring (
Optional
[bool
]) – Whether “Detailed Monitoring” is enabled for this instance Keep in mind that Detailed Monitoring results in extra charges. Default: - falsedisable_api_termination (
Optional
[bool
]) – 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. Default: falseebs_optimized (
Optional
[bool
]) – 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. Default: falseenclave_enabled (
Optional
[bool
]) – 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 bothenclaveEnabled
andhibernationEnabled
to true on the same instance. Default: - falsehibernation_enabled (
Optional
[bool
]) – Whether the instance is enabled for hibernation. You can’t set bothenclaveEnabled
andhibernationEnabled
to true on the same instance. Default: - falseinit (
Optional
[CloudFormationInit
]) – Apply the given CloudFormation Init configuration to the instance at startup. Default: - no CloudFormation initinit_options (
Union
[ApplyCloudFormationInitOptions
,Dict
[str
,Any
],None
]) – Use the given options for applying CloudFormation Init. Describes the configsets to use and the timeout to wait Default: - default optionsinstance_initiated_shutdown_behavior (
Optional
[InstanceInitiatedShutdownBehavior
]) – Indicates whether an instance stops or terminates when you initiate shutdown from the instance (using the operating system command for system shutdown). Default: InstanceInitiatedShutdownBehavior.STOPinstance_name (
Optional
[str
]) – The name of the instance. Default: - CDK generated nameipv6_address_count (
Union
[int
,float
,None
]) – 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 andassociatePublicIpAddress
at the same time. Default: - For instances associated with an IPv6 subnet, use 1; otherwise, use 0.key_name (
Optional
[str
]) – (deprecated) Name of SSH keypair to grant access to instance. Default: - No SSH access will be possible.key_pair (
Optional
[IKeyPair
]) – The SSH keypair to grant access to the instance. Default: - No SSH access will be possible.placement_group (
Optional
[IPlacementGroup
]) – The placement group that you want to launch the instance into. Default: - no placement group will be used for this instance.private_ip_address (
Optional
[str
]) – Defines a private IP address to associate with an instance. Private IP should be available within the VPC that the instance is build within. Default: - no associationpropagate_tags_to_volume_on_creation (
Optional
[bool
]) – Propagate the EC2 instance tags to the EBS volumes. Default: - falserequire_imdsv2 (
Optional
[bool
]) – Whether IMDSv2 should be required on this instance. Default: - falseresource_signal_timeout (
Optional
[Duration
]) – The length of time to wait for the resourceSignalCount. The maximum value is 43200 (12 hours). Default: Duration.minutes(5)role (
Optional
[IRole
]) – An IAM role to associate with the instance profile assigned to this Auto Scaling Group. The role must be assumable by the service principalec2.amazonaws.com
: Default: - A role will automatically be created, it can be accessed via therole
propertysecurity_group (
Optional
[ISecurityGroup
]) – Security Group to assign to this instance. Default: - create new security groupsource_dest_check (
Optional
[bool
]) – 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. Default: truessm_session_permissions (
Optional
[bool
]) – Add SSM session permissions to the instance role. Setting this totrue
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 totrue
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. Default: falseuser_data (
Optional
[UserData
]) – Specific UserData to use. The UserData may still be mutated after creation. Default: - A UserData object appropriate for the MachineImage’s Operating System is created.user_data_causes_replacement (
Optional
[bool
]) – 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 totrue
will make the instance’s Logical ID depend on the UserData, which will cause CloudFormation to replace it if the UserData changes. Default: - true ifinitOptions
is specified, false otherwise.vpc_subnets (
Union
[SubnetSelection
,Dict
[str
,Any
],None
]) – Where to place the instance within the VPC. Default: - Private subnets.
Methods
- add_security_group(security_group)
Add the security group to the instance.
- Parameters:
security_group (
ISecurityGroup
) – : The security group to add.- Return type:
None
- add_to_role_policy(statement)
Adds a statement to the IAM role assumed by the instance.
- Parameters:
statement (
PolicyStatement
) –- Return type:
None
- add_user_data(*commands)
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).
- Parameters:
commands (
str
) –- Return type:
None
- apply_cloud_formation_init(init, *, config_sets=None, embed_fingerprint=None, ignore_failures=None, include_role=None, include_url=None, print_log=None, timeout=None)
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.
- Parameters:
init (
CloudFormationInit
) –config_sets (
Optional
[Sequence
[str
]]) – ConfigSet to activate. Default: [‘default’]embed_fingerprint (
Optional
[bool
]) – Force instance replacement by embedding a config fingerprint. Iftrue
(the default), a hash of the config will be embedded into the UserData, so that if the config changes, the UserData changes. - If the EC2 instance is instance-store backed oruserDataCausesReplacement
is set, this will cause the instance to be replaced and the new configuration to be applied. - If the instance is EBS-backed anduserDataCausesReplacement
is not set, the change of UserData will make the instance restart but not be replaced, and the configuration will not be applied automatically. Iffalse
, no hash will be embedded, and if the CloudFormation Init config changes nothing will happen to the running instance. If a config update introduces errors, you will not notice until after the CloudFormation deployment successfully finishes and the next instance fails to launch. Default: trueignore_failures (
Optional
[bool
]) – Don’t fail the instance creation when cfn-init fails. You can use this to prevent CloudFormation from rolling back when instances fail to start up, to help in debugging. Default: falseinclude_role (
Optional
[bool
]) – Include –role argument when running cfn-init and cfn-signal commands. This will be the IAM instance profile attached to the EC2 instance Default: falseinclude_url (
Optional
[bool
]) – Include –url argument when running cfn-init and cfn-signal commands. This will be the cloudformation endpoint in the deployed region e.g. https://cloudformation.us-east-1.amazonaws.com Default: falseprint_log (
Optional
[bool
]) – Print the results of running cfn-init to the Instance System Log. By default, the output of running cfn-init is written to a log file on the instance. Set this totrue
to print it to the System Log (visible from the EC2 Console),false
to not print it. (Be aware that the system log is refreshed at certain points in time of the instance life cycle, and successful execution may not always show up). Default: truetimeout (
Optional
[Duration
]) – Timeout waiting for the configuration to be applied. Default: Duration.minutes(5)
- Return type:
None
- apply_removal_policy(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
).- Parameters:
policy (
RemovalPolicy
) –- Return type:
None
- to_string()
Returns a string representation of this construct.
- Return type:
str
Attributes
- connections
Allows specify security group connections for the instance.
- env
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.
- grant_principal
The principal to grant permissions to.
- instance
the underlying instance resource.
- instance_availability_zone
The availability zone the instance was launched in.
- Attribute:
true
- instance_id
The instance’s ID.
- Attribute:
true
- instance_private_dns_name
Private DNS name for this instance.
- Attribute:
true
- instance_private_ip
Private IP for this instance.
- Attribute:
true
- instance_public_dns_name
Publicly-routable DNS name for this instance.
(May be an empty string if the instance does not have a public name).
- Attribute:
true
- instance_public_ip
Publicly-routable IP address for this instance.
(May be an empty string if the instance does not have a public IP).
- Attribute:
true
- node
The tree node.
- os_type
The type of OS the instance is running.
- role
The IAM role assumed by the instance.
- stack
The stack in which this resource is defined.
- user_data
UserData for the instance.
Static Methods
- classmethod is_construct(x)
Checks if
x
is a construct.Use this method instead of
instanceof
to properly detectConstruct
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 classConstruct
in each copy of theconstructs
library is seen as a different class, and an instance of one class will not test asinstanceof
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 theconstructs
library can be accidentally installed, andinstanceof
will behave unpredictably. It is safest to avoid usinginstanceof
, and using this type-testing method instead.- Parameters:
x (
Any
) – Any object.- Return type:
bool
- Returns:
true if
x
is an object created from a class which extendsConstruct
.
- classmethod is_owned_resource(construct)
Returns true if the construct was created by CDK, and false otherwise.
- Parameters:
construct (
IConstruct
) –- Return type:
bool
- classmethod is_resource(construct)
Check whether the given construct is a Resource.
- Parameters:
construct (
IConstruct
) –- Return type:
bool