I am creating a EC2 instance using CfnInstance in CDK and I would like to use the ARN later in an IAM role, so I can give permission to that specific resource and to avoid to use *. How can I access the ARN of the EC2 instance just created. The code is as follows:
instance_profile = self.create_instance_profile()
self.instance = ec2.CfnInstance(self, 'Client',
image_id = image_id,
instance_type = instance_type,
subnet_id = subnet_id,
iam_instance_profile = instance_profile.ref,
security_group_ids = [cluster_security_group_id],
user_data = core.Fn.base64('\n'.join(self.user_data_commands)),
tags = [{ 'key': 'Name', 'value': 'MskEc2Client' }],
)
def create_instance_profile(self):
role = iam.Role(self, 'Role', assumed_by = iam.ServicePrincipal('ec2.amazonaws.com'))
ssm_policy_statement = iam.PolicyStatement(
resources = ['*'], #TODO GIVE PERMISSION TO THE SPECIFIC RESOURCE (EC2)
actions = [
'ssm:UpdateInstanceInformation', 'ssmmessages:CreateControlChannel',
'ssmmessages:CreateDataChannel', 'ssmmessages:OpenControlChannel', 'ssmmessages:OpenDataChannel'])
ssm_policy = iam.Policy(self, 'SessionManagerPolicy', statements = [ssm_policy_statement])
self.add_w12_suppression(ssm_policy, 'Session Manager actions do not support resource level permissions')
ssm_policy.attach_to_role(role)
msk_policy = iam.Policy(self, 'MskPolicy', #TODO GIVE PERMISSION TO SPECIFIC RESOURCES (EC2)
statements = [iam.PolicyStatement(resources = ['*'], actions = ['kafka:DescribeCluster', 'kafka:GetBootstrapBrokers'])]
)
self.add_w12_suppression(msk_policy, 'MSK actions do not support resource level permissions')
msk_policy.attach_to_role(role)
cfn_role = role.node.default_child
return iam.CfnInstanceProfile(self, 'InstanceProfile', roles = [cfn_role.ref])