LoginSignup
0
0

AWS CLIでRoute53のHosted ZoneにサブドメインのNSレコードを登録しよう

Last updated at Posted at 2023-06-23

はじめに

AWS CLIを利用して、Route53のHosted ZoneにサブドメインのNSレコードを登録する。
GitHub Actionsでも利用できるように、シェルスクリプトで作成する。

スクリプト

add_ns.sh
#!/bin/bash

set -e

if [ $# != 2 ] || [ $1 = "" ] || [ $2 = "" ]; then
  echo -e "Two parameters are required

  1st - string: Hosted Domain Name on Route 53 (e.g. example.com)
  2nd - string: Subdomain Name (e.g. sub.mexample.com)

  example command
  \t sh ./add_ns.sh example.com sub.example.com"
  exit
fi

HOSTED_DOMAIN=$1
TARGET_DOMAIN=$2

echo -e "\t HOSTED_DOMAIN = ${HOSTED_DOMAIN}"
echo -e "\t TARGET_DOMAIN = ${TARGET_DOMAIN}"

RECORD_SET_ID_HOSTED_DOMAIN=$( \
  aws route53 list-hosted-zones \
  --query "HostedZones[?Name=='${HOSTED_DOMAIN}.'].Id" \
  --output text) \
&& echo -e "\t RECORD_SET_ID_HOSTED_DOMAIN = ${RECORD_SET_ID_HOSTED_DOMAIN}"

RECORD_SET_ID_TARGET_DOMAIN=$( \
  aws route53 list-hosted-zones \
  --query "HostedZones[?Name=='${TARGET_DOMAIN}.'].Id" \
  --output text) \
&& echo -e "\t RECORD_SET_ID_TARGET_DOMAIN = ${RECORD_SET_ID_TARGET_DOMAIN}"

IS_RECORD_SET=$( \
  aws route53 list-resource-record-sets \
  --hosted-zone-id ${RECORD_SET_ID_HOSTED_DOMAIN} \
  --query "ResourceRecordSets[?Name=='${TARGET_DOMAIN}.'].Name" \
  --output text \
  | wc -w) \
&& echo -e "\t IS_RECORD_SET = ${IS_RECORD_SET}"

if [ ${IS_RECORD_SET} != 0 ]; then
  echo -e  "\t it already exists"
else
  RECORDS=$( \
    aws route53 list-resource-record-sets \
    --hosted-zone-id ${RECORD_SET_ID_TARGET_DOMAIN} \
    --query "ResourceRecordSets[?Type=='NS'].ResourceRecords[]") \
  && echo -e "\t RECORDS = ${RECORDS}"

  CHANGE_ID=$( \
    aws route53 change-resource-record-sets \
    --hosted-zone-id ${RECORD_SET_ID_HOSTED_DOMAIN} \
    --change-batch \
    "{
      \"Changes\": [
        {
          \"Action\": \"CREATE\",
          \"ResourceRecordSet\": {
            \"Name\": \"${TARGET_DOMAIN}\",
            \"Type\": \"NS\",
            \"TTL\": 300,
            \"ResourceRecords\": ${RECORDS}
          }
        }
      ]
    }" \
    --query "ChangeInfo.Id" \
    --output text) \
  && echo -e "\t Change ID : ${CHANGE_ID}\n"
fi
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0