aws / aws-cdk

The AWS Cloud Development Kit is a framework for defining cloud infrastructure in code

Home Page:https://aws.amazon.com/cdk

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

aws_ec2.Instance: Generates dependency on role even after removal

abstractalchemist opened this issue · comments

Describe the bug

I'm trying to prevent the Instance class from generating a new role because the environment I'm deploying to prevents me from creating the cloudformation service-role which can create IAM roles/instance profiles. I'm able to remove the instance profile and role ( which is very hacky, and honestly I'm not sure why it is generated by default, and why there is no way to just say don't remove it ), but even after doing so, the instance class still generates the dependency, This causes a dependency error when the changeset is deployed.

Expected Behavior

I expect there to be no dependency generated when I remove the instance profile and role. And I know I can sort of prevent this behavior with customize_roles, but that still demands a role.

Current Behavior

Generates a "depends-on" entry in the instance resource in the cloudformation template.

Reproduction Steps

My code for testing this is here: rke2-testing

Possible Solution

No response

Additional Information/Context

No response

CDK CLI Version

2.147.0 (build 3338fc0)

Framework Version

No response

Node.js Version

v20.10.0

OS

Fedora 30

Language

Python

Language Version

3.12.3

Other information

No response

Hey @abstractalchemist , thanks for reaching out.

The repro code is not accessible. Could you please check and share again?

This issue has not received a response in a while. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.

Sorry the url was incorrect apparently.
https://github.com/abstractalchemist/rke2-testing.git

Hi @abstractalchemist , thanks for keeping patience,and apologies, it skipped out of my radar for investigation.
To answer your question about default role creation, I dived deeper into the code and found that the role is created by default -


  /**
   * 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`:
   *
   * @example
   * const role = new iam.Role(this, 'MyRole', {
   *   assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com')
   * });
   *
   * @default - A role will automatically be created, it can be accessed via the `role` property
   */
  readonly role?: iam.IRole;

or you could pass it through the props -

this.role = props.role || new iam.Role(this, 'InstanceRole', {

RoleProfile gets created for the role further -

const iamProfile = new iam.CfnInstanceProfile(this, 'InstanceProfile', {

    const iamProfile = new iam.CfnInstanceProfile(this, 'InstanceProfile', {
      roles: [this.role.roleName],
    });

and later on dependency is generated on the default role -

this.instance.node.addDependency(this.role);

With that being said, the code you linked is quite descriptive. I synthesized a simple snippet for EC2 instance to check the role which is created by default and this role can be customised as well -

       ec2_instance =  ec2.Instance(self, "ec2-instance", 
           instance_type=ec2.InstanceType("t3.nano"),
           machine_image=ec2.AmazonLinuxImage(),
           vpc=ec2.Vpc.from_vpc_attributes(self, "vpc",
               vpc_id="vpc-0f20ad41a83843b59", 
               availability_zones=["us-east-1a"],
               public_subnet_ids=["subnet-0ba065a371ffaef4a"],
               private_subnet_ids=["subnet-0a0b9d4b7f3f7e9d9"]
               ),
           role=None
           )

The synthesized template shows the default role and depends-on with role profile as -

{
 "Resources": {
  "ec2instanceInstanceSecurityGroupAE914F6C": {
   "Type": "AWS::EC2::SecurityGroup",
   "Properties": {
    "GroupDescription": "Ec2InstanceRoleRemovalIssueStack/ec2-instance/InstanceSecurityGroup",
    "SecurityGroupEgress": [
     {
      "CidrIp": "0.0.0.0/0",
      "Description": "Allow all outbound traffic by default",
      "IpProtocol": "-1"
     }
    ],
    "Tags": [
     {
      "Key": "Name",
      "Value": "Ec2InstanceRoleRemovalIssueStack/ec2-instance"
     }
    ],
    "VpcId": "vpc-0f20ad41a83843b59"
   },
   "Metadata": {
    "aws:cdk:path": "Ec2InstanceRoleRemovalIssueStack/ec2-instance/InstanceSecurityGroup/Resource"
   }
  },
  **"ec2instanceInstanceRoleCA97C688": {
   "Type": "AWS::IAM::Role",
   "Properties": {
    "AssumeRolePolicyDocument": {
     "Statement": [
      {
       "Action": "sts:AssumeRole",
       "Effect": "Allow",
       "Principal": {
        "Service": "ec2.amazonaws.com"
       }
      }
     ],**
     "Version": "2012-10-17"
    },
    "Tags": [
     {
      "Key": "Name",
      "Value": "Ec2InstanceRoleRemovalIssueStack/ec2-instance"
     }
    ]
   },
   "Metadata": {
    "aws:cdk:path": "Ec2InstanceRoleRemovalIssueStack/ec2-instance/InstanceRole/Resource"
   }
  },
  **"ec2instanceInstanceProfile9BCE9015": {
   "Type": "AWS::IAM::InstanceProfile",
   "Properties": {
    "Roles": [
     {
      "Ref": "ec2instanceInstanceRoleCA97C688"
     }
    ]**
   },
   "Metadata": {
    "aws:cdk:path": "Ec2InstanceRoleRemovalIssueStack/ec2-instance/InstanceProfile"
   }
  },
  "ec2instance42082E81": {
   "Type": "AWS::EC2::Instance",
   "Properties": {
    "AvailabilityZone": "us-east-1a",
    "IamInstanceProfile": {
     "Ref": "ec2instanceInstanceProfile9BCE9015"
    },
    "ImageId": {
     "Ref": "SsmParameterValueawsserviceamiamazonlinuxlatestamznamihvmx8664gp2C96584B6F00A464EAD1953AFF4B05118Parameter"
    },
    "InstanceType": "t3.nano",
    "SecurityGroupIds": [
     {
      "Fn::GetAtt": [
       "ec2instanceInstanceSecurityGroupAE914F6C",
       "GroupId"
      ]
     }
    ],
    "SubnetId": "subnet-0a0b9d4b7f3f7e9d9",
    "Tags": [
     {
      "Key": "Name",
      "Value": "Ec2InstanceRoleRemovalIssueStack/ec2-instance"
     }
    ],
    "UserData": {
     "Fn::Base64": "#!/bin/bash"
    }
   },
   **"DependsOn": [
    "ec2instanceInstanceRoleCA97C688"
   ],**
   "Metadata": {
    "aws:cdk:path": "Ec2InstanceRoleRemovalIssueStack/ec2-instance/Resource"
   }
  },
  "CDKMetadata": {
   "Type": "AWS::CDK::Metadata",
   "Properties": {
    "Analytics": "v2:deflate64:H4sIAAAAAAAA/2WNzQ6CMBCEn4V7WQW5eOZgvJHyAKaWJa5A1/QnhjR9d0HTk6eZfN8kU0PVnOFYqLcr9TCVM90h9l7pSUh0HKxGsblbRF1DvBrnldlQjzpY8uvFcniJdjR/IE+TILVAlDzjjnNm3VkeacaUdtgpqxb0aL/LfL/1ls1Antgk0a3+weZwgqqGpng6otIG42lBkL/8AOMlmnfTAAAA"
   },
   "Metadata": {
    "aws:cdk:path": "Ec2InstanceRoleRemovalIssueStack/CDKMetadata/Default"
   },
   "Condition": "CDKMetadataAvailable"
  }
 },
 "Parameters": {
  "SsmParameterValueawsserviceamiamazonlinuxlatestamznamihvmx8664gp2C96584B6F00A464EAD1953AFF4B05118Parameter": {
   "Type": "AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>",
   "Default": "/aws/service/ami-amazon-linux-latest/amzn-ami-hvm-x86_64-gp2"
  },
  "BootstrapVersion": {
   "Type": "AWS::SSM::Parameter::Value<String>",
   "Default": "/cdk-bootstrap/hnb659fds/version",
   "Description": "Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip]"
  }
 },

Since the code adds dependsOn by default, I don't see any way how depend-on entry can be removed but found this doc . But I am looking for ways . Will share updates if I find any.