メインコンテンツへスキップ

CDKでNatGatewayのIPアドレスをOutputsに出力する

· loading · loading ·
kiitosu
著者
kiitosu
画像処理やデバイスドライバ、データ基盤構築からWebバックエンドまで、多様な領域に携わってきました。地図解析や地図アプリケーションの仕組みにも経験があり、幅広い技術を活かした開発に取り組んでいます。休日は草野球とランニングを楽しんでいます。
目次

概要
#

CDKで作成した別スタックで定義されたNatGatewayのIPアドレスを取得したくなった。 別スタックから取得できるように ALBのリスナーでNatGatewayを通る通信だけ許可したかったため。

# やり方

// NatGatwayのPublicIpを取得する関数
const getNatgwIp = (vpc: IVpc): string[] => {
    // vpcにあるnat gatwayを全て取得する
    const natgws = vpc.node.findAll().filter(
        (child) => child instanceof aws_ec2.CfnNatGateway
    ) as aws_ec2.CfnNatGateway[];

    // natgatewayに付与されるallocationIdを取得
    const allocIds = natgws.map(gw => gw.allocationId);

    // ElasticIpを全て取得
    const eips = vpc.node.findAll().filter(
        (child) => child instanceof aws_ec2.CfnEIP
    ) as aws_ec2.CfnEIP[];

    // eipの中でnatgatwayに付与されているもののipアドレスを返す
    const ips = eips
        .filter(eip => allocIds.includes(eip.attrAllocationId))
        .map(eip => eip.attrPublicIp);

    return ips;
};

// NatGatewayのIPを取得してOutputsに登録する
natIps = getNatgwIp(vpc)
natIps.forEach((ip, i) => {
    new CfnOutput(this, `natGwIp${i}`, {
        value: ip,
        exportName: `natGwIp${i}`, // Fn.importValue で取得して使う
    }).node.addDependency(vpc);
});

結構めんどくさかったんですけどもっといい方法があるんですかね?

Reply by Email

関連記事

anroidアプリでawsのパッケージが出力するログを抑制したい
· loading · loading
NeetCode 150 [Arrays & Hashing]:medium 5/6
· loading · loading
NeetCode 150 [Arrays & Hashing]:medium 4/6
· loading · loading