Rafiq
Rafiq

Reputation: 1642

How do I construct DHCPOptionsAssociation in AWS CDK using Python

I have the following code:

from aws_cdk import (
    aws_ec2 as ec2,
    core,
)

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

    # The code that defines your stack goes here 
    vpc = ec2.Vpc(
        self, 'MyVpc',
        cidr='10.10.10.0/23',
        max_azs=2
    )

    dhcp_options = ec2.CfnDHCPOptions(
        self, 'MyDhcpOptions', 
        domain_name='aws-prod.mydomain.com', 
        domain_name_servers=['10.1.1.5','10.2.1.5'],
        ntp_servers=['10.1.1.250','10.2.1.250'],
    )

    dhcp_options_associations = ec2.CfnVPCDHCPOptionsAssociation(
        self, 'MyDhcpOptionsAssociation', 
        dhcp_options_id=dhcp_options.logical_id, 
        vpc_id=vpc.vpc_id
    )

It generates VPCDHCPOptionsAssociation property INCORRECTLY for this in CloudFormation template like this:

  MyDhcpOptionsAssociation:
    Type: AWS::EC2::VPCDHCPOptionsAssociation
    Properties:
      DhcpOptionsId: MyDhcpOptions
      VpcId:
        Ref: myvpcAB8B6A91

I need this section in CloudFormation template to be like this (CORRECT):

  MyDhcpOptionsAssociation:
    Type: AWS::EC2::VPCDHCPOptionsAssociation
    Properties:
      DhcpOptionsId: 
        Ref: MyDhcpOptions
      VpcId:
        Ref: myvpcAB8B6A91

If I use dhcp_options_id=dhcp_options.id, I get error AttributeError: 'CfnDHCPOptions' object has no attribute 'id'.

If I use dhcp_options_id=dhcp_options.dhcp_options_id, I get error AttributeError: 'CfnDHCPOptions' object has no attribute 'dhcp_options_id'.

Here is the CDK API reference for this: https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_ec2/CfnVPCDHCPOptionsAssociation.html

Upvotes: 0

Views: 512

Answers (1)

Rafiq
Rafiq

Reputation: 1642

I found it. It has to be .ref, not consistent though with other resource properties.

dhcp_options_associations = ec2.CfnVPCDHCPOptionsAssociation(
    self, 'MyDhcpOptionsAssociation', 
    dhcp_options_id=dhcp_options.ref, 
    vpc_id=vpc.vpc_id
)

Upvotes: 3

Related Questions