Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get public DNS after creating AWS EC2 instance with CDK?

Tags:

aws-cdk

Is there a way how to obtain either public IP or public DNS (or both) of a new (or existing) instance created by AWS CDK?

I'd like to SSH or run ansible scripts against the new instance and don't want to go to AWS Console every time.

Here's what I have:

class WebsiteStack(core.Stack):

    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.vpc = aws_ec2.Vpc.from_lookup(self, 'default_vpc', is_default=True)

        self.sg_ssh = aws_ec2.SecurityGroup(
            self,
            'ssh',
            vpc=self.vpc,
            description="Allow SSH from anywhere",
            security_group_name="SSH from anywhere"
        )
        self.sg_ssh.add_ingress_rule(aws_ec2.Peer.any_ipv4(), aws_ec2.Port.tcp(22))

        ami = aws_ec2.LookupMachineImage(
            name="ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*",
            owners=["099720109477"],
        )

        ec2 = aws_ec2.Instance(
            self,
            'website',
            instance_type=aws_ec2.InstanceType('t3a.micro'),
            machine_image=ami,
            vpc=self.vpc,
            security_group=self.sg_ssh,
            key_name="autoscaled",
            user_data=self.change_ssh_port,
        )
        print(ec2.instance_public_dns_name)

but the output for cdk deploy, cdk synthor cdk diff is always sth like this:

${Token[TOKEN.41]}

Is this even possible? Anyone succeeded?

like image 448
Ikar Pohorský Avatar asked Oct 26 '25 05:10

Ikar Pohorský


1 Answers

One way is to create a CloudFormation output for each value you would like to fetch. You can use the following attributes of aws_cdk.aws_ec2.Instance class.

  • instance_public_ip
  • instance_public_dns_name
core.CfnOutput(
   scope=self,
   id="PublicIp",
   value=my_instance.instance_public_ip, 
   description="public ip of my instance", 
   export_name="ec2-public-ip")

CDK deploy command prints out the stack outputs when it runs successfully.

# cdk deploy
...
Outputs:

mystack.PublicDns = ec2-19-174-49-175.eu-west-1.compute.amazonaws.com
mystack.PublicIp = 19.174.49.175

You also need to specify a public subnet in your instance definition according to the documentation. By default CDK selects a private subnet.

vpc_subnets (Optional[SubnetSelection]) – Where to place the instance within the VPC. Default: - Private subnets.

ec2 = aws_ec2.Instance(self,
        ...
        vpc_subnets=aws_ec2.SubnetSelection(subnet_type=aws_ec2.SubnetType.PUBLIC)
)
like image 152
Vikyol Avatar answered Oct 29 '25 05:10

Vikyol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!