简体   繁体   English

如何在 AWS-CDK 中获取 EC2 实例的 ARN

[英]How to get the ARN of an EC2 instance in AWS-CDK

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 *.我正在使用 CDK 中的 CfnInstance 创建一个 EC2 实例,并且我想稍后在 IAM 角色中使用 ARN,因此我可以授予该特定资源的权限并避免使用 *. How can I access the ARN of the EC2 instance just created.如何访问刚刚创建的 EC2 实例的 ARN。 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])

You can use the default return value of the instance to construct the arn to populate the resources您可以使用实例的默认返回值来构造 arn 以填充资源

ssm_policy_statement = iam.PolicyStatement(
    resources = [f'arn:{self.partition}:ec2:{self.region}:{self.account}:instance/{self.instance.ref}'],
    actions = [
        'ssm:UpdateInstanceInformation', 'ssmmessages:CreateControlChannel', 
        'ssmmessages:CreateDataChannel', 'ssmmessages:OpenControlChannel', 'ssmmessages:OpenDataChannel'
    ]
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM