はじめに
前回、こちらでRoute53のレコード一覧をAnsibleでエクスポートする事例をご紹介しましたが、Ansibleのroute53_facts
モジュールの仕様上、ゾーンあたり100件までしかレコードを取得できないことが分かりました。
なんとか100件以上のレコードをエクスポートしたいと思い色々調べていたところ、Ansibleのモジュールだと難しいですが、botoに同梱されているroute53
コマンドが使えることが分かりました。
というわけで、route53
コマンドをAnsibleから実行することで全件エクスポートを実現しようと思います。
前提
- AWS関連のモジュール実行にはbotoが必要です。
- route53コマンドが必要です(botoに同梱)。
- credential情報については、環境変数
AWS_DEFAULT_PROFILE
で適切なprofileが選択されていることとします。
sample
やること
取得したroute53のレコードセット情報を、ゾーンごとにworkディレクトリに保存する
ディレクトリ構成
ディレクトリ構成
site.yml
roles/
|--route53_export/
| |--tasks/
| | |--main.yml
| |--templates/
| | |--save_record_sets.j2
hosts/aws #inventory
work/ #ゾーン単位でレコード情報が出力される
|--testdomain.com.txt #出力されたレコード情報
inventory
AWSリソース関連モジュールはすべてlocalhostで実行するので、下記のようなインベントリファイルを用意します。
hosts/aws
[aws]
localhost
Role
-
route53
コマンドはAWS CLIと違い、環境変数AWS_DEFAULT_PROFILE
でセットしたプロファイルを読んでくれません。そのため、環境変数AWS_PROFILE
にセットする必要があります。
roles/route53_export/tasks/main.yml
---
- name: Create directory
file:
path: "{{ inventory_dir | dirname }}/work/route53_export"
state: directory
mode: '0775'
group: wheel
delegate_to: localhost
check_mode: no
changed_when: no
become: yes
- name: Get all hosted zones
route53_facts:
query: hosted_zone
register: hosted_zones
check_mode: no
- name: Get record sets in a given hosted zone
shell: >-
export AWS_PROFILE=`echo $AWS_DEFAULT_PROFILE` && \
route53 get {{ item.Id | regex_replace('/hostedzone/','') }}
check_mode: no
changed_when: no
register: record_sets
with_items: "{{ hosted_zones.HostedZones }}"
- name: Save record sets
template:
src: save_record_sets.j2
dest: >-
{{ inventory_dir | dirname }}/work/route53_export/{{ item.item.Name | regex_replace('(^.*)\.$','\1') }}.txt
mode: '0664'
group: wheel
delegate_to: localhost
changed_when: no
become: yes
with_items: "{{ record_sets.results }}"
when: not ansible_check_mode
template
roles/route53_export/templates/save_record_sets.j2
{{ item.stdout }}
site.yml
site.yml
---
- name: route53_export
hosts: localhost
connection: local
roles:
- role: route53_export
実行
Command
$ ansible-playbook -i hosts/aws -l localhost site.yml
出力イメージ
work/testdomain.com.txt
Name Type TTL Value(s)
testdomain.com. NS 172800 ns-174.awsdns-21.com.,ns-1037.awsdns-01.org.,ns-1745.awsdns-26.co.uk.,ns-613.awsdns-12.net.
testdomain.com. SOA 900 ns-174.awsdns-21.com. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400
cname.testdomain.com. CNAME 300 www.example.com
text.testdomain.com. TXT 300 "var"
www.testdomain.com. A 7200 10.1.1.1
まとめ
出力イメージについては、route53コマンドの出力結果がそこそこ見やすいのでそのままファイルに出力しています。
必要に応じてJSONに整形すればYAML形式に変換するのも簡単です。