aws-cdk-lib.Resource

class Resource

LanguageType name
.NETAmazon.CDK.Resource
Gogithub.com/aws/aws-cdk-go/awscdk/v2#Resource
Javasoftware.amazon.awscdk.Resource
Pythonaws_cdk.Resource
TypeScript (source)aws-cdk-lib » Resource

Implements IConstruct, IDependable, IResource

Extends Construct

Implemented by App, Branch, Domain, ApiMapping, DomainName, HttpApi, HttpAuthorizer, HttpIntegration, HttpRoute, HttpStage, VpcLink, WebSocketApi, WebSocketAuthorizer, WebSocketIntegration, WebSocketRoute, WebSocketStage, Service, VpcConnector, EcsJobDefinition, EksJobDefinition, FairshareSchedulingPolicy, FargateComputeEnvironment, JobQueue, ManagedEc2EcsComputeEnvironment, ManagedEc2EksComputeEnvironment, MultiNodeJobDefinition, UnmanagedComputeEnvironment, ApiKey, BasePathMapping, CognitoUserPoolsAuthorizer, Deployment, DomainName, GatewayResponse, LambdaRestApi, Method, Model, ProxyResource, RateLimitedApiKey, RequestAuthorizer, RequestValidator, Resource, RestApi, SpecRestApi, Stage, StepFunctionsRestApi, TokenAuthorizer, UsagePlan, VpcLink, ScalableTarget, GatewayRoute, Mesh, Route, VirtualGateway, VirtualNode, VirtualRouter, VirtualService, AppsyncFunction, GraphqlApi, AutoScalingGroup, LifecycleHook, ScheduledAction, WarmPool, BackupPlan, BackupSelection, BackupVault, Certificate, DnsValidatedCertificate, PrivateCertificate, SlackChannelConfiguration, EdgeFunction, CachePolicy, CloudFrontWebDistribution, Distribution, Function, KeyGroup, OriginAccessIdentity, OriginRequestPolicy, PublicKey, ResponseHeadersPolicy, Trail, Alarm, CompositeAlarm, Dashboard, BitBucketSourceCredentials, GitHubEnterpriseSourceCredentials, GitHubSourceCredentials, PipelineProject, Project, ReportGroup, UntrustedCodeBoundaryPolicy, Repository, CustomLambdaDeploymentConfig, EcsApplication, EcsDeploymentConfig, EcsDeploymentGroup, LambdaApplication, LambdaDeploymentConfig, LambdaDeploymentGroup, ServerApplication, ServerDeploymentConfig, ServerDeploymentGroup, ProfilingGroup, Pipeline, NotificationRule, UserPool, UserPoolClient, UserPoolDomain, UserPoolIdentityProviderAmazon, UserPoolIdentityProviderApple, UserPoolIdentityProviderFacebook, UserPoolIdentityProviderGoogle, UserPoolIdentityProviderOidc, UserPoolIdentityProviderSaml, UserPoolResourceServer, AccessKeysRotated, CloudFormationStackDriftDetectionCheck, CloudFormationStackNotificationCheck, CustomPolicy, CustomRule, ManagedRule, ClusterParameterGroup, DatabaseCluster, DatabaseInstance, DatabaseSecret, Table, BastionHostLinux, ClientVpnAuthorizationRule, ClientVpnEndpoint, ClientVpnRoute, FlowLog, GatewayVpcEndpoint, Instance, InterfaceVpcEndpoint, LaunchTemplate, NetworkAcl, NetworkAclEntry, PlacementGroup, PrefixList, PrivateSubnet, PublicSubnet, SecurityGroup, Subnet, SubnetNetworkAclAssociation, Volume, Vpc, VpcEndpointService, VpnConnection, VpnGateway, Repository, Cluster, Ec2Service, Ec2TaskDefinition, ExternalService, ExternalTaskDefinition, FargateService, FargateTaskDefinition, TaskDefinition, AccessPoint, FileSystem, Cluster, FargateCluster, Nodegroup, OpenIdConnectProvider, LoadBalancer, ApplicationListener, ApplicationLoadBalancer, NetworkListener, NetworkLoadBalancer, Domain, ApiDestination, Archive, Connection, EventBus, EventBusPolicy, Rule, LustreFileSystem, Accelerator, EndpointGroup, Listener, AccessKey, Group, LazyRole, ManagedPolicy, OpenIdConnectProvider, Policy, Role, SamlProvider, User, Stream, Alias, Key, Alias, CodeSigningConfig, DockerImageFunction, EventInvokeConfig, EventSourceMapping, Function, FunctionUrl, LayerVersion, SingletonFunction, Version, NodejsFunction, CrossAccountDestination, LogGroup, LogStream, MetricFilter, QueryDefinition, ResourcePolicy, SubscriptionFilter, Domain, DatabaseCluster, DatabaseClusterFromSnapshot, DatabaseInstance, DatabaseInstanceFromSnapshot, DatabaseInstanceReadReplica, DatabaseProxy, DatabaseSecret, OptionGroup, ParameterGroup, ServerlessCluster, ServerlessClusterFromSnapshot, SubnetGroup, ARecord, AaaaRecord, CaaAmazonRecord, CaaRecord, CnameRecord, DsRecord, HostedZone, MxRecord, NsRecord, PrivateHostedZone, PublicHostedZone, RecordSet, SrvRecord, TxtRecord, ZoneDelegationRecord, Bucket, BucketPolicy, ResourcePolicy, RotationSchedule, Secret, SecretTargetAttachment, CloudFormationProduct, Portfolio, TagOptions, AliasTargetInstance, CnameInstance, HttpNamespace, IpInstance, NonIpInstance, PrivateDnsNamespace, PublicDnsNamespace, Service, ConfigurationSet, ConfigurationSetEventDestination, DedicatedIpPool, EmailIdentity, ReceiptFilter, ReceiptRule, ReceiptRuleSet, VdmAttributes, SigningProfile, Subscription, Topic, TopicPolicy, Queue, QueuePolicy, StringListParameter, StringParameter, Activity, StateMachine, AwsCliLayer, KubectlLayer, NodeProxyAgentLayer, TriggerFunction, CustomResource, Ec2Environment, GitHubRepository, IdentityPool, IdentityPoolRoleAttachment, Alias, Build, BuildFleet, GameServerGroup, GameSessionQueue, MatchmakingRuleSet, QueuedMatchmakingConfiguration, Script, StandaloneMatchmakingConfiguration, Connection, Database, Job, SecurityConfiguration, Table, TopicRule, DetectorModel, Input, Channel, PlaybackKeyPair, StreamKey, Application, DeliveryStream, GoFunction, PythonFunction, PythonLayerVersion, PlaceIndex, Cluster, ClusterParameterGroup, DatabaseCluster, DatabaseInstance, ParameterGroup, SubnetGroup, Cluster, ClusterParameterGroup, ClusterSubnetGroup, DatabaseSecret, FirewallDomainList, FirewallRuleGroup, FirewallRuleGroupAssociation, AccessPoint, Endpoint, EndpointConfig, Model, Application, AttributeGroup, Canary

A construct which represents an AWS resource.

Example

class MyConstruct extends Resource implements ITaggable {
  public readonly tags = new TagManager(TagType.KEY_VALUE, 'Whatever::The::Type');

  constructor(scope: Construct, id: string) {
    super(scope, id);

    new CfnResource(this, 'Resource', {
      type: 'Whatever::The::Type',
      properties: {
        // ...
        Tags: this.tags.renderedTags,
      },
    });
  }
}

Initializer

new Resource(scope: Construct, id: string, props?: ResourceProps)

Parameters

  • scope Construct
  • id string
  • props ResourceProps

Properties

NameTypeDescription
envResourceEnvironmentThe environment this resource belongs to.
nodeNodeThe tree node.
physicalNamestringReturns a string-encoded token that resolves to the physical name that should be passed to the CloudFormation resource.
stackStackThe stack in which this resource is defined.

env

Type: ResourceEnvironment

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.


node

Type: Node

The tree node.


physicalName

Type: string

Returns a string-encoded token that resolves to the physical name that should be passed to the CloudFormation resource.

This value will resolve to one of the following:

  • a concrete value (e.g. "my-awesome-bucket")
  • undefined, when a name should be generated by CloudFormation
  • a concrete name generated automatically during synthesis, in cross-environment scenarios.

stack

Type: Stack

The stack in which this resource is defined.

Methods

NameDescription
applyRemovalPolicy(policy)Apply the given removal policy to this resource.
toString()Returns a string representation of this construct.
protected generatePhysicalName()
protected getResourceArnAttribute(arnAttr, arnComponents)Returns an environment-sensitive token that should be used for the resource's "ARN" attribute (e.g. bucket.bucketArn).
protected getResourceNameAttribute(nameAttr)Returns an environment-sensitive token that should be used for the resource's "name" attribute (e.g. bucket.bucketName).
static isOwnedResource(construct)Returns true if the construct was created by CDK, and false otherwise.
static isResource(construct)Check whether the given construct is a Resource.

applyRemovalPolicy(policy)

public applyRemovalPolicy(policy: RemovalPolicy): void

Parameters

  • policy RemovalPolicy

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.


protected generatePhysicalName()

protected generatePhysicalName(): string

Returns

  • string

protected getResourceArnAttribute(arnAttr, arnComponents)

protected getResourceArnAttribute(arnAttr: string, arnComponents: ArnComponents): string

Parameters

  • arnAttr string — The CFN attribute which resolves to the ARN of the resource.
  • arnComponents ArnComponents — The format of the ARN of this resource.

Returns

  • string

Returns an environment-sensitive token that should be used for the resource's "ARN" attribute (e.g. bucket.bucketArn).

Normally, this token will resolve to arnAttr, but if the resource is referenced across environments, arnComponents will be used to synthesize a concrete ARN with the resource's physical name. Make sure to reference this.physicalName in arnComponents.


protected getResourceNameAttribute(nameAttr)

protected getResourceNameAttribute(nameAttr: string): string

Parameters

  • nameAttr string — The CFN attribute which resolves to the resource's name.

Returns

  • string

Returns an environment-sensitive token that should be used for the resource's "name" attribute (e.g. bucket.bucketName).

Normally, this token will resolve to nameAttr, but if the resource is referenced across environments, it will be resolved to this.physicalName, which will be a concrete name.


static isOwnedResource(construct)

public static isOwnedResource(construct: IConstruct): boolean

Parameters

  • construct IConstruct

Returns

  • boolean

Returns true if the construct was created by CDK, and false otherwise.


static isResource(construct)

public static isResource(construct: IConstruct): boolean

Parameters

  • construct IConstruct

Returns

  • boolean

Check whether the given construct is a Resource.