Refer/Import existing AutoScalingGroup Resource from CDK Stack

Viewed 575

I'm trying to referring an existing AutoScalingGroup from my CodeDeploy with AutoScalingGroup.from_auto_scaling_group_name static method in order to integrate with CodePipeline for automating EC2/On-premise deployment. I have the following code snippet for your reference.

# Refer existing AutoScaling Group
asg_1 = autoscaling.AutoScalingGroup.from_auto_scaling_group_name(self, "AutoScaleGroup", "WSAutoscaleStack-webServerAsgIdASG12345-XXXXXX")

# EC2 Deployment Groups
deployment_group = codedeploy.ServerDeploymentGroup(self, "CodeDeployDeploymentGroup", deployment_group_name="MyDeploymentGroup", install_agent=True, auto_scaling_groups=[asg_1])

After validating the stack with 'cdk ls', I got an error which says,

jsii.errors.JSIIError: Cannot get policy fragment of AMIPipelineStack/AutoScaleGroup, resource imported without a role

As far as I understand, the referenced resource should be imported as an object, so that I can use it all dependents including iam.role from the resource. Any ideas?

1 Answers

Looks like the fromAutoScalingGroupName method doesn't "Import" the role (see here)

One option you have is to implement that import by yourself. The above linked Import class would then look like (in Typescript):

public static fromAutoScalingGroupNameWithRole(scope: Construct, id: string, autoScalingGroupName: string, roleArn:string): IAutoScalingGroup {
class ImportWithRole extends AutoScalingGroupBase {
  public autoScalingGroupName = autoScalingGroupName;
  public autoScalingGroupArn = Stack.of(this).formatArn({
    service: 'autoscaling',
    resource: 'autoScalingGroup:*:autoScalingGroupName',
    resourceName: this.autoScalingGroupName,
  });
  public readonly osType = ec2.OperatingSystemType.UNKNOWN;
  public readonly grantPrincipal = iam.Role.fromRoleArn(this, `${id}-role`, roleArn)
}

return new ImportWithRole(scope, id);

}

Another maneuver you could do (if applicable to your use-case) is to really import the auto-scaling group and its role into the Cloudformation stack. The resources will then be managed with the CDK/Cloudformation stack and you could use the standard AutoScalingGroup constructor and provide your Role. The downside here is that it's currently quite a painful process (see link)

Related