From 23b05da923a0cf46ba721667fc1b2177a250a86e Mon Sep 17 00:00:00 2001 From: vincent Date: Tue, 16 Apr 2019 16:53:34 +0200 Subject: [PATCH] updated DNS role --- .gitignore | 19 ++ .travis.yml | 46 ++++ .yamllint | 56 +++++ CHANGELOG.md | 213 ++++++++++++++++++ LICENSE.md | 13 ++ README.md | 333 +++++++++++++++++++++++++++++ defaults/main.yml | 59 +++++ files/main.yml | 0 handlers/main.yml | 7 + meta/main.yml | 27 +++ tasks/main.yml | 109 ++++++++++ tasks/master.yml | 63 ++++++ tasks/slave.yml | 15 ++ templates/bind_zone.j2 | 121 +++++++++++ templates/main.yml | 0 templates/master_etc_named.conf.j2 | 131 ++++++++++++ templates/reverse_zone.j2 | 96 +++++++++ templates/reverse_zone_ipv6.j2 | 96 +++++++++ templates/slave_etc_named.conf.j2 | 103 +++++++++ vars/Archlinux.yml | 21 ++ vars/Debian.yml | 22 ++ vars/RedHat.yml | 23 ++ vars/main.yml | 0 23 files changed, 1573 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 .yamllint create mode 100644 CHANGELOG.md create mode 100644 LICENSE.md create mode 100644 README.md delete mode 100644 files/main.yml create mode 100644 tasks/master.yml create mode 100644 tasks/slave.yml create mode 100644 templates/bind_zone.j2 delete mode 100644 templates/main.yml create mode 100644 templates/master_etc_named.conf.j2 create mode 100644 templates/reverse_zone.j2 create mode 100644 templates/reverse_zone_ipv6.j2 create mode 100644 templates/slave_etc_named.conf.j2 create mode 100644 vars/Archlinux.yml create mode 100644 vars/Debian.yml create mode 100644 vars/RedHat.yml delete mode 100644 vars/main.yml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b433c0a --- /dev/null +++ b/.gitignore @@ -0,0 +1,19 @@ +# .gitignore + +# Hidden Vagrant-directory +.vagrant + +# Backup files (e.g. Vim, Gedit, etc.) +*~ + +# Vagrant base boxes (you never know when someone puts one in the repository) +*.box + +# Python artefacts +.ropeproject +*.pyc + +# Ignore test directory +tests/ +vagrant-tests/ +docker-tests/ diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..0571de7 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,46 @@ +--- +sudo: required + +env: + matrix: + - DISTRIBUTION: centos + VERSION: 7 + - DISTRIBUTION: ubuntu + VERSION: 16.04 + - DISTRIBUTION: ubuntu + VERSION: 18.04 + - DISTRIBUTION: debian + VERSION: 8 + - DISTRIBUTION: debian + VERSION: 9 + - DISTRIBUTION: arch + VERSION: latest + +services: + - docker + +before_install: + # Install latest Git + - sudo apt-get update + - sudo apt-get install --only-upgrade git + # Allow fetching other branches than master + - git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/* + # Fetch the branch with test code + - git fetch origin docker-tests + - git worktree add docker-tests origin/docker-tests + +script: + # Running the test script the first time will set up the master DNS server + # with IP 172.17.0.2. Running it the second time sets up the slave DNS + # server with IP 172.17.0.3. + - ./docker-tests/docker-tests.sh + - ./docker-tests/docker-tests.sh + + # Run functional tests on both master and slave server + - SUT_IP=172.17.0.2 ./docker-tests/functional-tests.sh + # Ensure the slave gets the chance to receive zone updates from the master + - sleep 6s + - SUT_IP=172.17.0.3 ./docker-tests/functional-tests.sh + +notifications: + webhooks: https://galaxy.ansible.com/api/v1/notifications/ diff --git a/.yamllint b/.yamllint new file mode 100644 index 0000000..d19261c --- /dev/null +++ b/.yamllint @@ -0,0 +1,56 @@ +--- + +rules: + braces: + min-spaces-inside: 0 + max-spaces-inside: 0 + min-spaces-inside-empty: -1 + max-spaces-inside-empty: -1 + brackets: + min-spaces-inside: 0 + max-spaces-inside: 0 + min-spaces-inside-empty: -1 + max-spaces-inside-empty: -1 + colons: + max-spaces-before: 0 + max-spaces-after: 1 + commas: + max-spaces-before: 0 + min-spaces-after: 1 + max-spaces-after: 1 + comments: + level: warning + require-starting-space: true + min-spaces-from-content: 2 + comments-indentation: + level: warning + document-end: disable + document-start: + level: warning + present: true + empty-lines: + max: 2 + max-start: 0 + max-end: 0 + empty-values: + forbid-in-block-mappings: false + forbid-in-flow-mappings: false + hyphens: + max-spaces-after: 1 + indentation: + spaces: consistent + indent-sequences: true + check-multi-line-strings: false + key-duplicates: enable + key-ordering: disable + line-length: + max: 1000 + level: warning + allow-non-breakable-words: true + allow-non-breakable-inline-mappings: false + new-line-at-end-of-file: enable + new-lines: + type: unix + trailing-spaces: enable + truthy: + level: warning diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bee5967 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,213 @@ +# Change log + +This file contains al notable changes to the bind Ansible role. + +This file adheres to the guidelines of [http://keepachangelog.com/](http://keepachangelog.com/). Versioning follows [Semantic Versioning](http://semver.org/). "GH-X" refers to the X'th issue/pull request on the Github project. + +## 4.1.0 - 2018-10-05 + +## Added + +- (GH-53) Add variable `bind_zone_dir` and `bind_zone_file_mode` for setting the master zone file path and mode, and `bind_extra_include_files` for including arbitrary configuration files into named.conf. (credit: [Brad Durrow](https://github.com/bdurrow)) +- (GH-64) Add variable `bind_query_log` to enable query logging (credit: [Angel Barrera](https://github.com/angelbarrera92)) + +## Changed + +- (GH-55) Fix issue with non-existing file when grepping domain (credit: [Tom Meinlschmidt](https://github.com/tmeinlschmidt)) +- (GH-57) Fix issue with forwarding in subdomain delegations (credit: [Stuart Knight](https://github.com/blofeldthefish)) +- (GH-66) Fix issue that causes playbook to fail when running in `--check` mode (credit: [Jörg Eichhorn](https://github.com/jeichhorn)) +- (GH-67) Improved documentation with minimal slave configuration (credit: [Christopher Hicks](https://github.com/chicks-net)) +- Add Ubuntu 18.04, Debian 8-9 and Arch Linux to list of supported distros. + +## 4.0.1 - 2018-05-21 + +### Changed + +- (GH-52) Move all zone specific configuration options to `bind_zones` (credit: [Stuart Knight](https://github.com/blofeldthefish)) + +## 4.0.0 - 2018-05-19 + +### Added + +- (GH-50) Add support for multiple zones (credit: [Stuart Knight](https://github.com/blofeldthefish)). **This is a breaking change,** as it changes the syntax for specifying zones. +- Allow out-of-zone name server records + +## 3.9.1 - 2018-04-22 + +## Changed + +- Allow multi-line `ansible_managed` comment (credit: [Fazle Arefin](https://github.com/fazlearefin)) +- Fix the atrocious implementation of (GH-35) +- Updated documentation for specifying hosts with multiple IP addresses +- Create serial as UTC UNIX time (credit: [David J. Haines](https://github.com/dhaines)) +- Fix bugs, linter and deprecation warnings + +## 3.9.0 - 2017-11-21 + +### Added + +- (GH-35) Role variable `bind_check_names`, which adds support for check-names (e.g. `check-names master ignore;`) +- (GH-36) Role variable `bind_allow_recursion`, which adds support for allow-recursion (credit: [Loic Dachary](https://github.com/dachary)) +- (GH-39) Role variable `bind_zone_delegate`, which adds support for zone delegation / NS records (credit: [Loic Dachary](https://github.com/dachary)) +- (GH-40) Role variables `bind_dnssec_enable` and `bind_dnssec_validation`, which makes DNSSEC validation configurable (credit: [Guillaume Darmont](https://github.com/gdarmont)). + +### Changed + +- (GH-38) Only append domain to MX if it does not end with a dot (credit: [Loic Dachary](https://github.com/dachary)) + +## 3.8.0 - 2017-07-12 + +This release adds support for multiple TXT entries and fixes some bugs. + +### Added + +- (GH-31) Support for multiple TXT entries for the same name (credit: [Rafael Bodill](https://github.com/rafi)) + +### Changed + +- (GH-31) Fixed ipv6 reverse zone hash calculation for complete idempotency (credit: [Stuart Knight](https://github.com/blofeldthefish)) +- (GH-32, GH-33) Fix for bug where CNAMEs and Multi-IP entries weren't working (credit: [Greg Cockburn](https://github.com/gergnz)) + +## 3.7.1 - 2017-07-03 + +### Changed + +- (GH-29) Zone files are fully idempotent, so are only changed when actual content changes (credit: [@Stuart Knight](https://github.com/blofeldthefish)) + +## 3.7.0 - 2017-06-01 + +### Added + +- (GH-10) Implement reverse IPv6 lookups +- (GH-28) Add option `bind_forwarders` and `bind_forward_only`, which allows BIND to be set up as a caching name server. + +## 3.6.1 - 2017-06-01 + +### Changed + +- Fixed a bug with generating the reverse zone names. + +## 3.6.0 - 2017-06-01 + +### Changed + +- (GH-25) Allow slave log file to be set with variable `bind_log` instead of a hard coded value (credit @kartone). +- The alignment of columns in the reverse zone file are improved + +### Added + +- (GH-22, 23) Documentation improvements +- (GH-27) Allow dynamic updates (credit: @bverschueren) + +### Removed + +- The custom filter plugins were removed. The functionality has since been added to Ansible's built-in filter plugins. This does require `python-netaddr` to be installed on the management node. + +## 3.5.2 - 2016-09-29 + +### Changed + +* The call to `named-checkconf` was fixed. It had the full path to the binary, which is not the same on all distributions. (GH-20, credit @peterjanes) + +## 3.5.1 - 2016-09-22 + +### Changed + +* The check for master/slave server is improved (GH-19, credit @josetaas) + +## 3.5.0 - 2016-07-28 + +### Added + +* Introduced role variable `bind_log`, the path to the log file. +* Introduced role variable `bind_zone_also_notify`, a list of servers that will receive a notification when the master zone file is reloaded (GH-18, credit: Joanna Delaporte) +* Reverse zone files now handle the case with only a single host (GH-18, credit: Joanna Delaporte) + +## 3.4.0 - 2016-05-26 + +### Added + +* (GH-16) Support for service record (SRV) lookups +* Support for text record (TXT) lookups + +### Changed + +* Fixed Ansible 2.0 deprecation warnings +* Generating a serial is no longer considered a change +* Ensured that all role variables have a default value, e.g. empty list instead of undefined. This simplifies template logic (no `if defined` tests), and is considered [deprecated in playbooks within a *with_* loop](https://docs.ansible.com/ansible/porting_guide_2.0.html#deprecated). + +## 3.3.1 - 2016-04-08 + +### Removed + +* The `version:` field in `meta/main.yml`. This an unofficial field that is used by a third-party tool for managing role dependencies (librarian-ansible). Custom meta fields are no longer accepted in Ansible 2.0. See [ansible/ansible#13496](https://github.com/ansible/ansible/issues/13496) for more info. Unfortunately, this will break support for librarian-ansible. As a workaround, until this issue is resolved upstream, use version 3.3.0 of this role. + +## 3.3.0 - 2016-04-08 + +### Added + +* Added role variable `bind_other_name_servers` for adding NS records for DNS servers outside of the domain. (GH-12) +* Re-added `bind_recursion`, as it is needed in some cases. (GH-14) + +### Removed + +## 3.2.1 - 2015-12-15 + +### Added + +* The domain name can now also point to an IP address, enabling e.g. "http://example.com/" (GH-11) + +## 3.2.0 - 2015-12-07 + +### Added + +* Add support for multiple IP addresses per host (GH-9) +* Allow setting `rrset-order` (for DNS round robin) +* Add support for (multiple) IPv6 (AAAA) records (GH-2). For now, only forward lookups are supported. + +### Changed + +* Test code is put into a separate branch. This means that test code is no longer included when installing the role from Ansible Galaxy. + +## 3.1.0 - 2015-12-04 + +### Added + +* Add support for zone transfers (GH-8) +* Check whether `bind_zone_master_server_ip` was set (GH-7) + +### Removed + +* Role variable `bind_recursion` was removed. This role is explicitly only suitable for an authoritative DNS server, and in this case, recursion should be off. + +## 3.0.0 - 2015-06-14 + +### Added + +* You can now set up a master and slave DNS server. +* The variable `bind_zone_master_server_ip` was added. This is a **required** variable, which makes this release not backwards compatible. +* Automated acceptance tests for the test playbook + +## 2.0.0 - 2015-06-10 + +### Added + +* Added EL6 to supported platforms. Thanks to @rilindo for verifying this. + +### Changed + +* Recursion is turned off by default, which fits an authoritative name server. This change is not backwards compatible, as the behaviour of BIND is different from before when you do not set the variable `bind_recursion` explicitly. + +### Removed + +* Firewall settings. This should not be a concern of this role. Configuring the firewall is functionality offered by other roles (e.g. [bertvv.bind](https://github.com/bertvv/ansible-role-el7)) + +## 1.0.0 - 2015-04-22 + +First release! + +### Added + +- Functionality for master DNS server +- Multiple reverse lookup zones + diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..8411892 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,13 @@ +# BSD License + +Copyright (c) 2014, Bert Van Vreckem, (bert.vanvreckem@gmail.com) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7e56d6b --- /dev/null +++ b/README.md @@ -0,0 +1,333 @@ +# Ansible role `bind` + +[![Build Status](https://travis-ci.org/bertvv/ansible-role-bind.svg?branch=master)](https://travis-ci.org/bertvv/ansible-role-bind) + +An Ansible role for setting up BIND ISC as an **authoritative-only** DNS server for multiple domains on EL7 or Ubuntu Server. Specifically, the responsibilities of this role are to: + +- install BIND +- set up the main configuration file + - master server + - slave server +- set up forward and reverse lookup zone files + +This role supports multiple forward and reverse zones, including for IPv6. Although enabling recursion is supported (albeit *strongly* discouraged), consider using another role if you want to set up a caching or forwarding name server. + +Configuring the firewall is not a concern of this role, so you should do this using another role (e.g. [bertvv.rh-base](https://galaxy.ansible.com/bertvv/rh-base/)). + +If you like/use this role, please consider giving it a star. Thanks! + +See the [change log](CHANGELOG.md) for notable changes between versions. + +## Requirements + +- **The package `python-ipaddr` should be installed on the management node** (since v3.7.0) + +## Role Variables + +Variables are not required, unless specified. + +| Variable | Default | Comments (type) | +| :--- | :--- | :--- | +| `bind_acls` | `[]` | A list of ACL definitions, which are dicts with fields `name` and `match_list`. See below for an example. | +| `bind_allow_query` | `['localhost']` | A list of hosts that are allowed to query this DNS server. Set to ['any'] to allow all hosts | +| `bind_allow_recursion` | `['any']` | Similar to bind_allow_query, this option applies to recursive queries. | +| `bind_check_names` | `[]` | Check host names for compliance with RFC 952 and RFC 1123 and take the defined actioni (e.g. `warn`, `ignore`, `fail`). | +| `bind_dnssec_enable` | `true` | Is DNSSEC enabled | +| `bind_dnssec_validation` | `true` | Is DNSSEC validation enabled | +| `bind_extra_include_files` | `[]` | | +| `bind_forward_only` | `false` | If `true`, BIND is set up as a caching name server | +| `bind_forwarders` | `[]` | A list of name servers to forward DNS requests to. | +| `bind_listen_ipv4` | `['127.0.0.1']` | A list of the IPv4 address of the network interface(s) to listen on. Set to ['any'] to listen on all interfaces. | +| `bind_listen_ipv6` | `['::1']` | A list of the IPv6 address of the network interface(s) to listen on | +| `bind_log` | `data/named.run` | Path to the log file | +| `bind_query_log` | - | When defined (e.g. `data/query.log`), this will turn on the query log | +| `bind_recursion` | `false` | Determines whether requests for which the DNS server is not authoritative should be forwarded†. | +| `bind_rrset_order` | `random` | Defines order for DNS round robin (either `random` or `cyclic`) | +| `bind_zone_dir` | - | When defined, sets a custom absolute path to the server directory (for zone files, etc.) instead of the default. | +| `bind_zone_domains` | n/a | A list of domains to configure, with a seperate dict for each domain, with relevant details | +| `- allow_update` | `['none']` | A list of hosts that are allowed to dynamically update this DNS zone. | +| `- also_notify` | - | A list of servers that will receive a notification when the master zone file is reloaded. | +| `- delegate` | `[]` | Zone delegation. See below this table for examples. | +| `- hostmaster_email` | `hostmaster` | The e-mail address of the system administrator for the zone | +| `- hosts` | `[]` | Host definitions. See below this table for examples. | +| `- ipv6_networks` | `[]` | A list of the IPv6 networks that are part of the domain, in CIDR notation (e.g. 2001:db8::/48) | +| `- mail_servers` | `[{name: mail, preference: 10}]` | A list of dicts (with fields `name` and `preference`) specifying the mail servers for this domain. | +| `- name_servers` | `[ansible_hostname]` | A list of the DNS servers for this domain. | +| `- name` | `example.com` | The domain name | +| `- networks` | `['10.0.2']` | A list of the networks that are part of the domain | +| `- other_name_servers` | `[]` | A list of the DNS servers outside of this domain. | +| `- services` | `[]` | A list of services to be advertized by SRV records | +| `- text` | `[]` | A list of dicts with fields `name` and `text`, specifying TXT records. `text` can be a list or string. | +| `bind_zone_file_mode` | 0640 | The file permissions for the main config file (named.conf) | +| `bind_zone_master_server_ip` | - | **(Required)** The IP address of the master DNS server. | +| `bind_zone_minimum_ttl` | `1D` | Minimum TTL field in the SOA record. | +| `bind_zone_time_to_expire` | `1W` | Time to expire field in the SOA record. | +| `bind_zone_time_to_refresh` | `1D` | Time to refresh field in the SOA record. | +| `bind_zone_time_to_retry` | `1H` | Time to retry field in the SOA record. | +| `bind_zone_ttl` | `1W` | Time to Live field in the SOA record. | + +† Best practice for an authoritative name server is to leave recursion turned off. However, [for some cases](http://www.zytrax.com/books/dns/ch7/queries.html#allow-query-cache) it may be necessary to have recursion turned on. + +### Minimal variables for a working zone + +Even though only variable `bind_zone_master_server_ip` is required for the role to run without errors, this is not sufficient to get a working zone. In order to set up an authoritative name server that is available to clients, you should also at least define the following variables: + +| Variable | Master | Slave | +| :--- | :---: | :---: | +| `bind_zone_domains` | V | V | +| ` - name` | V | V | +| ` - networks` | V | -- | +| ` - name_servers` | V | -- | +| ` - hosts` | V | -- | +| `bind_listen_ipv4` | V | V | +| `bind_allow_query` | V | V | + +### Domain definitions + +```Yaml +bind_zone_domains: + - name: mydomain.com + hosts: + - name: pub01 + ip: 192.0.2.1 + ipv6: 2001:db8::1 + aliases: + - ns + - name: '@' + ip: + - 192.0.2.2 + - 192.0.2.3 + ipv6: + - 2001:db8::2 + - 2001:db8::3 + aliases: + - www + - name: priv01 + ip: 10.0.0.1 + networks: + - '192.0.2' + - '10' + - '172.16' + delegate: + - zone: foo + dns: 192.0.2.1 + services: + - name: _ldap._tcp + weight: 100 + port: 88 + target: dc001 +``` + +### Minimal slave configuration + +```Yaml + bind_listen_ipv4: ['any'] + bind_allow_query: ['any'] + bind_zone_master_server_ip: 192.168.111.222 + bind_zone_domains: + - name: example.com +``` + +### Hosts + +Host names that this DNS server should resolve can be specified in `hosts` as a list of dicts with fields `name`, `ip` and `aliases` + +To allow to surf to http://example.com/, set the host name of your web server to `'@'` (must be quoted!). In BIND syntax, `@` indicates the domain name itself. + +If you want to specify multiple IP addresses for a host, add entries to `bind_zone_hosts` with the same name (e.g. `priv01` in the code snippet). This results in multiple A/AAAA records for that host and allows [DNS round robin](http://www.zytrax.com/books/dns/ch9/rr.html), a simple load balancing technique. The order in which the IP addresses are returned can be configured with role variable `bind_rrset_order`. + +### Networks + +As you can see, not all hosts are in the same network. This is perfectly acceptable, and supported by this role. All networks should be specified in `networks` (part of bind_zone_domains.name dict), though, or the host will not get a PTR record for reverse lookup: + +Remark that only the network part should be specified here! When specifying a class B IP address (e.g. "172.16") in a variable file, it must be quoted. Otherwise, the Yaml parser will interpret it as a float. + +Based on the idea and examples detailed at for the gdnsd package, the zonefiles are fully idempotent, and thus only get updated if "real" content changes. + +### Zone delgation + +To delegate a zone to a DNS, it is enough to create a `NS` record (under delegate) which is the equivalent of: + +``` +foo IN NS 192.0.2.1 +``` + +### Service records + +Service (SRV) records can be added with the services. Tis should be a list of dicts with mandatory fields `name` (service name), `target` (host providing the service), `port` (TCP/UDP port of the service) and optional fields `priority` (default = 0) and `weight` (default = 0). + +### ACLs + +ACLs can be defined like this: + +```Yaml +bind_acls: + - name: acl1 + match_list: + - 192.0.2.0/24 + - 10.0.0.0/8 +``` + +The names of the ACLs will be added to the `allow-transfer` clause in global options. + +## Dependencies + +No dependencies. If you want to configure the firewall, do this through another role (e.g. [bertvv.rh-base](https://galaxy.ansible.com/bertvv/rh-base)). + +## Example Playbook + +See the test playbook [test.yml](https://github.com/bertvv/ansible-role-bind/blob/docker-tests/test.yml) for an elaborate example that showcases most features. + +## Testing + +There are two test environments for this role, one based on Vagrant, the other on Docker. The latter powers the Travis-CI tests. The tests are kept in a separate (orphan) branch so as not to clutter the actual code of the role. [git-worktree(1)](https://git-scm.com/docs/git-worktree) is used to include the test code into the working directory. Remark that this requires at least Git v2.5.0. + +### Running Docker tests + +1. Fetch the test branch: `git fetch origin docker-tests` +2. Create a Git worktree for the test code: `git worktree add docker-tests docker-tests`. This will create a directory `docker-tests/` + +The script `docker-tests.sh` will create a Docker container, and apply this role from a playbook `test.yml`. The Docker images are configured for testing Ansible roles and are published at . There are images available for several distributions and versions. The distribution and version should be specified outside the script using environment variables: + +``` +DISTRIBUTION=centos VERSION=7 ./docker-tests/docker-tests.sh +``` + +The specific combinations of distributions and versions that are supported by this role are specified in `.travis.yml`. + +The first time the test script is run, a container will be created that is assigned the IP address 172.17.0.2. This will be the master DNS-server. The server is still running after the script finishes and can be queried from the command line, e.g.: + +``` +$ dig @172.17.0.2 www.acme-inc.com +short +srv001.acme-inc.com. +172.17.1.1 +``` + +If you run the script again, a new container is launched with IP address 172.17.0.3 that will be set up as a slave DNS-server. After a few seconds, it will have received updates from the master server and can be queried as well. + +``` +$ dig @172.17.0.3 www.acme-inc.com +short +srv001.acme-inc.com. +172.17.1.1 +``` + +The script `docker-tests/functional-tests.sh` will run a [BATS](https://github.com/sstephenson/bats) test suite, `dns.bats` that performs a number of different queries. Specify the server IP address as the environment variable `${SUT_IP}` (short for System Under Test). + +``` +$ SUT_IP=172.17.0.2 ./docker-tests/functional-tests.sh +### Using BATS executable at: /usr/local/bin/bats +### Running test /home/bert/CfgMgmt/roles/bind/tests/dns.bats + ✓ Forward lookups public servers + ✓ Reverse lookups + ✓ Alias lookups public servers + ✓ IPv6 forward lookups + ✓ NS record lookup + ✓ Mail server lookup + ✓ Service record lookup + ✓ TXT record lookup + +8 tests, 0 failures +$ SUT_IP=172.17.0.3 ./docker-tests/functional-tests.sh +[...] +``` + +### Running Vagrant tests + +1. Fetch the tests branch: `git fetch origin vagrant-tests` +2. Create a Git worktree for the test code: `git worktree add vagrant-tests vagrant-tests`. This will create a directory `vagrant-tests/`. +3. `cd vagrant-tests/` +4. `vagrant up` will then create two VMs and apply a test playbook (`test.yml`). + +The command `vagrant up` results in a setup with *two* DNS servers, a master and a slave, set up according to playbook `test.yml`. + +| **Hostname** | **ip** | +| :--- | :--- | +| `testbindmaster` | 192.168.56.53 | +| `testbindslave` | 192.168.56.54 | + +IP addresses are in the subnet of the default VirtualBox Host Only network interface (192.168.56.0/24). You should be able to query the servers from your host system. For example, to verify if the slave is updated correctly, you can do the following: + +```ShellSession +$ dig @192.168.56.54 ns1.example.com +short +testbindmaster.example.com. +192.168.56.53 +$ dig @192.168.56.54 example.com www.example.com +short +web.example.com. +192.168.56.20 +192.168.56.21 +$ dig @192.168.56.54 MX example.com +short +10 mail.example.com. + +``` + +An automated acceptance test written in [BATS](https://github.com/sstephenson/bats.git) is provided that checks most settings specified in `vagrant-tests/test.yml`. You can run it by executing the shell script `vagrant-tests/runtests.sh`. The script can be run on either your host system (assuming you have a Bash shell), or one of the VMs. The script will download BATS if needed and run the test script `vagrant-tests/dns.bats` on both the master and the slave DNS server. + +```ShellSession +$ cd vagrant-tests +$ vagrant up +[...] +$ ./runtests.sh +Testing 192.168.56.53 +✓ The `dig` command should be installed +✓ It should return the NS record(s) +✓ It should be able to resolve host names +✓ It should be able to resolve IPv6 addresses +✓ It should be able to do reverse lookups +✓ It should be able to resolve aliases +✓ It should return the MX record(s) + +6 tests, 0 failures +Testing 192.168.56.54 +✓ The `dig` command should be installed +✓ It should return the NS record(s) +✓ It should be able to resolve host names +✓ It should be able to resolve IPv6 addresses +✓ It should be able to do reverse lookups +✓ It should be able to resolve aliases +✓ It should return the MX record(s) + +6 tests, 0 failures +``` + +Running from the VM: + +```ShellSession +$ vagrant ssh testbindmaster +Last login: Sun Jun 14 18:52:35 2015 from 10.0.2.2 +Welcome to your Packer-built virtual machine. +[vagrant@testbindmaster ~]$ /vagrant/runtests.sh +Testing 192.168.56.53 + ✓ The `dig` command should be installed +[...] +``` + +## License + +BSD + +## Contributors + +This role could only have been realized thanks to the contributions of many. If you have an idea to improve it even further, don't hesitate to pitch in! + +Issues, feature requests, ideas, suggestions, etc. can be posted in the Issues section. + +Pull requests are also very welcome. Please create a topic branch for your proposed changes. If you don't, this will create conflicts in your fork after the merge. Don't hesitate to add yourself to the contributor list below in your PR! + +- [Angel Barrera](https://github.com/angelbarrera92) +- [B. Verschueren](https://github.com/bverschueren) +- [Bert Van Vreckem](https://github.com/bertvv/) (Maintainer) +- [Brad Durrow](https://github.com/bdurrow) +- [Christopher Hicks](http://www.chicks.net/) +- [David J. Haines](https://github.com/dhaines) +- [Fazle Arefin](https://github.com/fazlearefin) +- [Greg Cockburn](https://github.com/gergnz) +- [Guillaume Darmont](https://github.com/gdarmont) +- [Joanna Delaporte](https://github.com/jdelaporte) +- [Jose Taas](https://github.com/josetaas) +- [Jörg Eichhorn](https://github.com/jeichhorn) +- [Loic Dachary](http://dachary.org) +- [Mario Ciccarelli](https://github.com/kartone) +- [Peter Janes](https://github.com/peterjanes) +- [Rafael Bodill](https://github.com/rafi) +- [Stuart Knight](https://github.com/blofeldthefish) +- [Tom Meinlschmidt](https://github.com/tmeinlschmidt) diff --git a/defaults/main.yml b/defaults/main.yml index e69de29..077bf6b 100644 --- a/defaults/main.yml +++ b/defaults/main.yml @@ -0,0 +1,59 @@ +# roles/bind/defaults/main.yml +--- + +bind_log: "data/named.run" + +bind_zone_domains: + - name: "example.com" + hostmaster_email: "hostmaster" + networks: + - "10.0.2" + +# List of acls. +bind_acls: [] + +# List of IPv4 address of the network interface(s) to listen on. Set to "any" +# to listen on all interfaces +bind_listen_ipv4: + - "127.0.0.1" + +# List of IPv6 address of the network interface(s) to listen on. +bind_listen_ipv6: + - "::1" + +# List of hosts that are allowed to query this DNS server. +bind_allow_query: + - "localhost" + +# Determines whether recursion should be allowed. Typically, an authoritative +# name server should have recursion turned OFF. +bind_recursion: false +bind_allow_recursion: + - "any" + +# Allows BIND to be set up as a caching name server +bind_forward_only: false + +# List of name servers to forward DNS requests to. +bind_forwarders: [] + +# DNS round robin order (random or cyclic) +bind_rrset_order: "random" + +# DNSSEC configuration +bind_dnssec_enable: true +bind_dnssec_validation: true + +bind_extra_include_files: [] + +# SOA information +bind_zone_ttl: "1W" +bind_zone_time_to_refresh: "1D" +bind_zone_time_to_retry: "1H" +bind_zone_time_to_expire: "1W" +bind_zone_minimum_ttl: "1D" + +# Custom location for master zone files +bind_zone_dir: "{{ bind_dir }}" +# File mode for master zone files (needs to be something like 0660 for dynamic updates) +bind_zone_file_mode: "0640" diff --git a/files/main.yml b/files/main.yml deleted file mode 100644 index e69de29..0000000 diff --git a/handlers/main.yml b/handlers/main.yml index e69de29..9acaaad 100644 --- a/handlers/main.yml +++ b/handlers/main.yml @@ -0,0 +1,7 @@ +# roles/bind/handlers/main.yml +--- + +- name: reload bind + service: + name: "{{ bind_service }}" + state: reloaded diff --git a/meta/main.yml b/meta/main.yml index e69de29..a7725e2 100644 --- a/meta/main.yml +++ b/meta/main.yml @@ -0,0 +1,27 @@ +--- +galaxy_info: + author: Bert Van Vreckem + description: Sets up ISC BIND on RHEL/CentOS 6/7, Ubuntu 16.04/18.04 LTS (Xenial/Bionic), or Arch Linux as an authoritative DNS server for one or more domains (master and/or slave). + license: BSD + min_ansible_version: 2.7 + platforms: + - name: EL + versions: + - 6 + - 7 + - name: Ubuntu + versions: + - xenial + - bionic + - name: Debian + versions: + - jessie + - stretch + - name: ArchLinux + versions: + - any + galaxy_tags: + - networking + - system + - dns +dependencies: [] diff --git a/tasks/main.yml b/tasks/main.yml index e69de29..7e6c205 100644 --- a/tasks/main.yml +++ b/tasks/main.yml @@ -0,0 +1,109 @@ +# roles/bind/tasks/main.yml +--- + +# Initialise distribution-specific variables +- name: Source specific variables + include_vars: "{{ item }}" + with_first_found: + - "{{ ansible_distribution }}.yml" + - "{{ ansible_os_family }}.yml" + tags: bind + +- name: Check whether `bind_zone_master_server_ip` was set + assert: + that: bind_zone_master_server_ip is defined + +- name: Install BIND + package: + pkg: "{{ item }}" + state: present + with_items: + - "{{ bind_packages }}" + tags: bind + +- name: Ensure runtime directories referenced in config exist + file: + path: "{{ item }}" + state: directory + owner: root + group: "{{ bind_group }}" + mode: 0770 + with_items: + - "{{ bind_dir }}/dynamic" + - "{{ bind_dir }}/data" + - "{{ bind_zone_dir }}" + tags: bind + +- name: Create serial, based on UTC UNIX time + command: date -u +%s + register: timestamp + changed_when: false + run_once: true + check_mode: false + tags: bind + +- name: Read forward zone hashes + shell: 'grep -s "^; Hash:" {{ bind_zone_dir }}/{{ item.name }} || true' + changed_when: false + check_mode: false + register: forward_hashes_temp + with_items: + - "{{ bind_zone_domains }}" + +- name: create dict of forward hashes + set_fact: + forward_hashes: "{{ forward_hashes|default([]) + [ {'hash': item.stdout|default(), 'name': item.item.name} ] }}" + with_items: + - "{{ forward_hashes_temp.results }}" + + +- name: Read reverse ipv4 zone hashes + shell: "grep -s \"^; Hash:\" {{ bind_zone_dir }}/{{ ('.'.join(item.1.replace(item.1+'.','').split('.')[::-1])) }}.in-addr.arpa || true" + changed_when: false + check_mode: false + register: reverse_hashes_temp + with_subelements: + - "{{ bind_zone_domains }}" + - networks + - flags: + skip_missing: true + +- name: create dict of reverse hashes + set_fact: + reverse_hashes: "{{ reverse_hashes|default([]) + [ {'hash': item.0.stdout|default(), 'network': item.1} ] }}" + with_subelements: + - "{{ reverse_hashes_temp.results }}" + - item + +- name: Read reverse ipv6 zone hashes + shell: "grep -s \"^; Hash:\" {{ bind_zone_dir }}/{{ (item.1 | ipaddr('revdns'))[-(9+(item.1|regex_replace('^.*/','')|int)//2):-1] }} || true" + changed_when: false + check_mode: false + register: reverse_hashes_ipv6_temp + with_subelements: + - "{{ bind_zone_domains }}" + - ipv6_networks + - flags: + skip_missing: true + +- name: create dict of reverse ipv6 hashes + set_fact: + reverse_hashes_ipv6: "{{ reverse_hashes_ipv6|default([]) + [ {'hash': item.0.stdout|default(), 'network': item.1} ] }}" + with_subelements: + - "{{ reverse_hashes_ipv6_temp.results }}" + - item + +- name: Set up the machine as a master DNS server + include_tasks: master.yml + when: bind_zone_master_server_ip in ansible_all_ipv4_addresses + +- name: Set up the machine as a slave DNS server + include_tasks: slave.yml + when: bind_zone_master_server_ip not in ansible_all_ipv4_addresses + +- name: Start BIND service + service: + name: "{{ bind_service }}" + state: started + enabled: true + tags: bind diff --git a/tasks/master.yml b/tasks/master.yml new file mode 100644 index 0000000..94f2225 --- /dev/null +++ b/tasks/master.yml @@ -0,0 +1,63 @@ +# roles/bind/tasks/master.yml +# Set up a BIND master server +--- + +- name: Master | Main BIND config file (master) + template: + src: master_etc_named.conf.j2 + dest: "{{ bind_config }}" + owner: "{{ bind_owner }}" + group: "{{ bind_group }}" + mode: '0640' + setype: named_conf_t + validate: 'named-checkconf %s' + notify: reload bind + tags: bind + +- name: Master | Create forward lookup zone file + template: + src: bind_zone.j2 + dest: "{{ bind_zone_dir }}/{{ item.name }}" + owner: "{{ bind_owner }}" + group: "{{ bind_group }}" + mode: "{{ bind_zone_file_mode }}" + setype: named_zone_t + validate: 'named-checkzone -d {{ item.name }} %s' + with_items: + - "{{ bind_zone_domains }}" + notify: reload bind + tags: bind + +- name: Master | Create reverse lookup zone file + template: + src: reverse_zone.j2 + dest: "{{ bind_zone_dir }}/{{ ('.'.join(item.1.replace(item.1+'.','').split('.')[::-1])) }}.in-addr.arpa" + owner: "{{ bind_owner }}" + group: "{{ bind_group }}" + mode: "{{ bind_zone_file_mode }}" + setype: named_zone_t + validate: "named-checkzone {{ ('.'.join(item.1.replace(item.1+'.','').split('.')[::-1])) }}.in-addr.arpa %s" + with_subelements: + - "{{ bind_zone_domains }}" + - networks + - flags: + skip_missing: true + notify: reload bind + tags: bind + +- name: Master | Create reverse IPv6 lookup zone file + template: + src: reverse_zone_ipv6.j2 + dest: "{{bind_zone_dir}}/{{ (item.1 | ipaddr('revdns'))[-(9+(item.1|regex_replace('^.*/','')|int)//2):-1] }}" + owner: "{{ bind_owner }}" + group: "{{ bind_group }}" + mode: "{{ bind_zone_file_mode }}" + setype: named_zone_t + validate: "named-checkzone {{ (item.1 | ipaddr('revdns'))[-(9+(item.1|regex_replace('^.*/','')|int)//2):] }} %s" + with_subelements: + - "{{ bind_zone_domains }}" + - ipv6_networks + - flags: + skip_missing: true + notify: reload bind + tags: bind diff --git a/tasks/slave.yml b/tasks/slave.yml new file mode 100644 index 0000000..de7de5a --- /dev/null +++ b/tasks/slave.yml @@ -0,0 +1,15 @@ +# roles/bind/tasks/master.yml +# Set up a BIND slave server +--- + +- name: Slave | Main BIND config file (slave) + template: + src: slave_etc_named.conf.j2 + dest: "{{ bind_config }}" + owner: "{{ bind_owner }}" + group: "{{ bind_group }}" + mode: '0640' + setype: named_conf_t + validate: 'named-checkconf %s' + notify: reload bind + tags: bind diff --git a/templates/bind_zone.j2 b/templates/bind_zone.j2 new file mode 100644 index 0000000..56c6d03 --- /dev/null +++ b/templates/bind_zone.j2 @@ -0,0 +1,121 @@ +{# + # First create a dict holding the entire zone information and create a hash + # from it, that it can be compared with subsequent task executions. In this + # way the serial will only be updated if there are some content changes. + #} +{% set _zone_data = {} %} +{% set _ = _zone_data.update({'ttl': bind_zone_ttl}) %} +{% set _ = _zone_data.update({'domain': item.name}) %} +{% set _ = _zone_data.update({'mname': item.name_servers|default([])}) %} +{% set _ = _zone_data.update({'aname': item.other_name_servers|default([])}) %} +{% set _ = _zone_data.update({'mail': item.mail_servers|default([])}) %} +{% if item.hostmaster_email is defined %} +{% set _ = _zone_data.update({'rname': (( item.hostmaster_email )) + ('' if (item.hostmaster_email is search('\.')) else ('.' + _zone_data['domain']))}) %} +{% else %} +{% set _ = _zone_data.update({'rname': 'hostmaster.' + _zone_data['domain']}) %} +{% endif %} +{% set _ = _zone_data.update({'refresh': bind_zone_time_to_refresh}) %} +{% set _ = _zone_data.update({'retry': bind_zone_time_to_retry}) %} +{% set _ = _zone_data.update({'expire': bind_zone_time_to_expire}) %} +{% set _ = _zone_data.update({'minimum': bind_zone_minimum_ttl}) %} +{% set _ = _zone_data.update({'hosts': item.hosts|default([])}) %} +{% set _ = _zone_data.update({'delegate': item.delegate|default([])}) %} +{% set _ = _zone_data.update({'services': item.services|default([])}) %} +{% set _ = _zone_data.update({'text': item.text|default([])}) %} +{# + # Compare the zone file hash with the current zone data hash and set serial + # accordingly + #} +{% set _zone = {'hash': _zone_data | string | hash('md5')} %} +{% for _result in forward_hashes if _result.name == item.name %} +{% set _hash_serial = _result.hash.split(' ')[2:] %} +{% if _hash_serial and _hash_serial[0] == _zone['hash'] %} +{% set _ = _zone.update({'serial': _hash_serial[1]}) %} +{% else %} +{% set _ = _zone.update({'serial': timestamp.stdout}) %} +{% endif %} +{% endfor %} +{# + # Eventually output the zone data + #} +; Hash: {{ _zone['hash'] }} {{ _zone['serial'] }} +; Zone file for {{ _zone_data['domain'] }} +{{ ansible_managed | comment(decoration='; ') }} + +$ORIGIN {{ _zone_data['domain'] }}. +$TTL {{ _zone_data['ttl'] }} + +{% if _zone_data['mname']|length > 0 %} +@ IN SOA {{ _zone_data['mname']|first }}{% if not _zone_data['mname']|first|regex_search('\.$') %}.{{ _zone_data['domain'] }}.{% endif %} {{ _zone_data['rname'] }}. ( +{% else %} +@ IN SOA {{ ansible_hostname }}.{{ _zone_data['domain'] }}. {{ _zone_data['rname'] }}. ( +{% endif %} + {{ _zone['serial'] }} + {{ _zone_data['refresh'] }} + {{ _zone_data['retry'] }} + {{ _zone_data['expire'] }} + {{ _zone_data['minimum'] }} ) + +{% if _zone_data['mname']|length > 0 %} +{% for ns in _zone_data['mname'] %} + IN NS {{ ns }}{% if not ns|regex_search('\.$') %}.{{ _zone_data['domain'] }}.{% endif %} + +{% endfor %} +{% else %} + IN NS {{ ansible_hostname }}.{{ _zone_data['domain'] }}. +{% endif %} +{% for ns in _zone_data['aname'] %} + IN NS {{ ns }}. +{% endfor %} + +{% for mail in _zone_data['mail'] %} +{% if loop.first %}@{% else %} {% endif %} IN MX {{ mail.preference}} {{ mail.name }}{% if not mail.name.endswith('.') %}.{{ _zone_data['domain'] }}.{% endif %} +{% endfor %} + +{% if _zone_data['delegate']|length > 0 %} +{% for host in _zone_data['delegate'] %} +{{ host.zone.ljust(20) }} IN NS {{ host.dns }} +{% endfor %} +{% endif %} + +{% if _zone_data['hosts']|length > 0 %} +{% for host in _zone_data['hosts'] %} +{% if host.ip is defined %} +{% if host.ip is string %} +{{ host.name.ljust(20) }} IN A {{ host.ip }} +{% else %} +{% for ip in host.ip %} +{{ host.name.ljust(20) }} IN A {{ ip }} +{% endfor %} +{% endif %} +{% endif %} +{% if host.ipv6 is defined %} +{% if host.ipv6 is string %} +{{ host.name.ljust(20) }} IN AAAA {{ host.ipv6 }} +{% else %} +{% for ip6 in host.ipv6 %} +{{ host.name.ljust(20) }} IN AAAA {{ ip6 }} +{% endfor %} +{% endif %} +{% endif %} +{% if host.aliases is defined %} +{% for alias in host.aliases %} +{{ alias.ljust(20) }} IN CNAME {{ host.name }} +{% endfor %} +{% endif %} +{% endfor %} +{% else %} +{{ ansible_hostname.ljust(20) }} IN A {{ ansible_default_ipv4.address }} +{% endif %} +{% for service in _zone_data['services'] %} +{{ service.name.ljust(20) }} IN SRV {{ service.priority|default('0') }} {{ service.weight|default('0') }} {{ service.port }} {{ service.target }} +{% endfor %} +{% for text in _zone_data['text'] %} +{% if text.text is string %} +{{ text.name.ljust(20) }} IN TXT "{{ text.text }}" +{% else %} +{% for entry in text.text %} +{{ text.name.ljust(20) }} IN TXT "{{ entry }}" +{% endfor %} +{% endif %} +{% endfor %} diff --git a/templates/main.yml b/templates/main.yml deleted file mode 100644 index e69de29..0000000 diff --git a/templates/master_etc_named.conf.j2 b/templates/master_etc_named.conf.j2 new file mode 100644 index 0000000..ec400ae --- /dev/null +++ b/templates/master_etc_named.conf.j2 @@ -0,0 +1,131 @@ +// +// named.conf +// +{{ ansible_managed | comment('c') }} +{% for acl in bind_acls %} +acl "{{ acl.name }}" { +{% for match in acl.match_list %} + {{ match }}; +{% endfor %} +}; + +{% endfor %} +options { + listen-on port 53 { {{ bind_listen_ipv4|join(';') }}; }; + listen-on-v6 port 53 { {{ bind_listen_ipv6|join(';') }}; }; + directory "{{ bind_dir }}"; + dump-file "{{ bind_dir }}/data/cache_dump.db"; + statistics-file "{{ bind_dir }}/data/named_stats.txt"; + memstatistics-file "{{ bind_dir }}/data/named_mem_stats.txt"; + allow-query { {{ bind_allow_query|join(';') }}; }; +{% if bind_acls|length != 0 %} + allow-transfer { {% for acl in bind_acls %}"{{ acl.name }}"; {% endfor %}}; +{% endif %} +{% if bind_check_names is defined %} + check-names {{ bind_check_names }}; +{% endif %} + + recursion {% if bind_recursion %}yes{% else %}no{% endif %}; + {% if bind_recursion %}allow-recursion { {{ bind_allow_recursion|join('; ') }}; }; + {% endif %} +{% if bind_forwarders|length > 0 %}forwarders { {{ bind_forwarders|join('; ') }}; };{% endif %} + {% if bind_forward_only %}forward only;{% endif %} + + rrset-order { order {{ bind_rrset_order }}; }; + + dnssec-enable {{ bind_dnssec_enable }}; + dnssec-validation {{ bind_dnssec_validation }}; + dnssec-lookaside auto; + + /* Path to ISC DLV key */ + bindkeys-file "/etc/named.iscdlv.key"; + + managed-keys-directory "{{ bind_dir }}/dynamic"; + + pid-file "/run/named/named.pid"; + session-keyfile "/run/named/session.key"; + +{% if bind_query_log is defined %} + querylog yes; +{% endif %} +}; + +logging { + channel default_debug { + file "{{ bind_log }}"; + severity dynamic; + print-time yes; + }; +{% if bind_query_log is defined %} + channel querylog { + file "{{ bind_query_log }}" versions 600 size 20m; + severity dynamic; + print-time yes; + }; + category queries { querylog; }; +{% endif %} +}; + +{% for file in bind_default_zone_files %} +include "{{ file }}"; +{% endfor %} +{% for file in bind_extra_include_files %} +include "{{ file }}"; +{% endfor %} + +{% if bind_zone_domains is defined %} +{% for bind_zone in bind_zone_domains %} +zone "{{ bind_zone.name }}" IN { + type master; + file "{{ bind_zone_dir }}/{{ bind_zone.name }}"; + notify yes; +{% if bind_zone.also_notify is defined %} + also-notify { {{ bind_zone.also_notify|join(';') }}; }; +{% endif %} +{% if bind_zone.allow_update is defined %} + allow-update { {{ bind_zone.allow_update|join(';') }}; }; +{% else %} + allow-update { none; }; +{% endif %} +{% if bind_zone.delegate is defined %} + forwarders {}; +{% endif %} +}; + +{% if bind_zone.networks is defined %} +{% for network in bind_zone.networks %} +zone "{{ ('.'.join(network.replace(network+'.','').split('.')[::-1])) }}.in-addr.arpa" IN { + type master; + file "{{ bind_zone_dir }}/{{ ('.'.join(network.replace(network+'.','').split('.')[::-1])) }}.in-addr.arpa"; + notify yes; +{% if bind_zone.also_notify is defined %} + also-notify { {{ bind_zone.also_notify|join(';') }}; }; +{% endif %} +{% if bind_zone.allow_update is defined %} + allow-update { {{ bind_zone.allow_update|join(';') }}; }; +{% else %} + allow-update { none; }; +{% endif %} +}; +{% endfor %} +{% endif %} + +{% if bind_zone.ipv6_networks is defined %} +{% for network in bind_zone.ipv6_networks %} +zone "{{ (network | ipaddr('revdns'))[-(9+(network|regex_replace('^.*/','')|int)//2):] }}" IN { + type master; + file "{{ bind_zone_dir }}/{{ (network | ipaddr('revdns'))[-(9+(network|regex_replace('^.*/','')|int)//2):-1] }}"; + notify yes; +{% if bind_zone.also_notify is defined %} + also-notify { {{ bind_zone.also_notify|join(';') }}; }; +{% endif %} +{% if bind_zone.allow_update is defined %} + allow-update { {{ bind_zone.allow_update|join(';') }}; }; +{% else %} + allow-update { none; }; +{% endif %} +}; +{% endfor %} +{% endif %} +{% endfor %} +{% endif %} diff --git a/templates/reverse_zone.j2 b/templates/reverse_zone.j2 new file mode 100644 index 0000000..f7176fa --- /dev/null +++ b/templates/reverse_zone.j2 @@ -0,0 +1,96 @@ +{# + # First create a dict holding the entire zone information and create a hash + # from it, that it can be compared with subsequent task executions. In this + # way the serial will only be updated if there are some content changes. + #} +{% set _zone_data = {} %} +{% set _ = _zone_data.update({'ttl': bind_zone_ttl}) %} +{% set _ = _zone_data.update({'domain': item.0.name}) %} +{% set _ = _zone_data.update({'mname': item.0.name_servers|default([])}) %} +{% set _ = _zone_data.update({'aname': item.0.other_name_servers|default([])}) %} +{% if item.0.hostmaster_email is defined %} +{% set _ = _zone_data.update({'rname': (( item.0.hostmaster_email )) + ('' if (item.0.hostmaster_email is search('\.')) else ('.' + _zone_data['domain']))}) %} +{% else %} +{% set _ = _zone_data.update({'rname': 'hostmaster.' + _zone_data['domain']}) %} +{% endif %} +{% set _ = _zone_data.update({'refresh': bind_zone_time_to_refresh}) %} +{% set _ = _zone_data.update({'retry': bind_zone_time_to_retry}) %} +{% set _ = _zone_data.update({'expire': bind_zone_time_to_expire}) %} +{% set _ = _zone_data.update({'minimum': bind_zone_minimum_ttl}) %} +{% set _ = _zone_data.update({'hosts': item.0.hosts|default([]) | selectattr('ip', 'defined') | selectattr('ip', 'string') | selectattr('ip', 'search', '^'+item.1) | list}) %} +{% set _ = _zone_data.update({'revip': ('.'.join(item.1.replace(item.1+'.','').split('.')[::-1]))}) %} +{# + # Compare the zone file hash with the current zone data hash and set serial + # accordingly + #} +{% set _zone = {'hash': _zone_data | string | hash('md5')} %} +{% for _result in reverse_hashes if _result.network == item.1 %} +{% set _hash_serial = _result.hash.split(' ')[2:] %} +{% if _hash_serial and _hash_serial[0] == _zone['hash'] %} +{% set _ = _zone.update({'serial': _hash_serial[1]}) %} +{% else %} +{% set _ = _zone.update({'serial': timestamp.stdout}) %} +{% endif %} +{% endfor %} +{# + # Eventually output the zone data + #} +; Hash: {{ _zone['hash'] }} {{ _zone['serial'] }} +; Reverse zone file for {{ _zone_data['domain'] }} +{{ ansible_managed | comment(decoration='; ') }} + +$TTL {{ _zone_data['ttl'] }} +$ORIGIN {{ ('.'.join(item.1.replace(item.1+'.','').split('.')[::-1])) }}.in-addr.arpa. + +{% if _zone_data['mname']|length > 0 %} +@ IN SOA {{ _zone_data['mname']|first }}{% if not _zone_data['mname']|first|regex_search('\.$') %}.{{ _zone_data['domain'] }}.{% endif %} {{ _zone_data['rname'] }}. ( +{% else %} +@ IN SOA {{ ansible_hostname }}.{{ _zone_data['domain'] }}. {{ _zone_data['rname'] }}. ( +{% endif %} + {{ _zone['serial'] }} + {{ _zone_data['refresh'] }} + {{ _zone_data['retry'] }} + {{ _zone_data['expire'] }} + {{ _zone_data['minimum'] }} ) + +{% if _zone_data['mname']|length > 0 %} +{% for ns in _zone_data['mname'] %} + IN NS {{ ns }}{% if not ns|regex_search('\.$') %}.{{ _zone_data['domain'] }}.{% endif %} + +{% endfor %} +{% else %} + IN NS {{ ansible_hostname }}.{{ _zone_data['domain'] }}. +{% endif %} +{% for ns in _zone_data['aname'] %} + IN NS {{ ns }}. +{% endfor %} + +{% if _zone_data['hosts']|length > 0 %} +{% for host in _zone_data['hosts'] %} +{% if host.ip is defined %} +{% if host.ip == item.1 %} +@ IN PTR {{ host.name }}.{{ _zone_data['domain'] }}. +{% else %} +{% if host.ip is string and host.ip.startswith(item.1) %} +{% if host.name == '@' %} +{{ ('.'.join(host.ip.replace(item.1+'.','').split('.')[::-1])).ljust(16) }} IN PTR {{ _zone_data['domain'] }}. +{% else %} +{{ ('.'.join(host.ip.replace(item.1+'.','').split('.')[::-1])).ljust(16) }} IN PTR {{ host.name }}.{{ _zone_data['domain'] }}. +{% endif %} +{% else %} +{% for ip in host.ip %} +{% if ip.startswith(item.1) %} +{{ ('.'.join(ip.replace(item.1+'.','').split('.')[::-1])).ljust(16) }} IN PTR {{ _zone_data['domain'] }}. +{% if host.name == '@' %} +{% else %} +{{ ('.'.join(ip.replace(item.1+'.','').split('.')[::-1])).ljust(16) }} IN PTR {{ host.name }}.{{ _zone_data['domain'] }}. +{% endif %} +{% endif %} +{% endfor %} +{% endif %} +{% endif %} +{% endif %} +{% endfor %} +{% else %} +{{ ('.'.join(ansible_default_ipv4.address.replace(item.1+'.','').split('.')[::-1])).ljust(16) }} IN PTR {{ ansible_hostname }}.{{ _zone_data['domain'] }}. +{% endif %} diff --git a/templates/reverse_zone_ipv6.j2 b/templates/reverse_zone_ipv6.j2 new file mode 100644 index 0000000..b859bfa --- /dev/null +++ b/templates/reverse_zone_ipv6.j2 @@ -0,0 +1,96 @@ +{# + # First create a dict holding the entire zone information and create a hash + # from it, that it can be compared with subsequent task executions. In this + # way the serial will only be updated if there are some content changes. + #} +{% set _zone_data = {} %} +{% set _ = _zone_data.update({'ttl': bind_zone_ttl}) %} +{% set _ = _zone_data.update({'domain': item.0.name}) %} +{% set _ = _zone_data.update({'mname': item.0.name_servers|default([])}) %} +{% set _ = _zone_data.update({'aname': item.0.other_name_servers|default([])}) %} +{% if item.0.hostmaster_email is defined %} +{% set _ = _zone_data.update({'rname': (( item.0.hostmaster_email )) + ('' if (item.0.hostmaster_email is search('\.')) else ('.' + _zone_data['domain']))}) %} +{% else %} +{% set _ = _zone_data.update({'rname': 'hostmaster.' + _zone_data['domain']}) %} +{% endif %} +{% set _ = _zone_data.update({'refresh': bind_zone_time_to_refresh}) %} +{% set _ = _zone_data.update({'retry': bind_zone_time_to_retry}) %} +{% set _ = _zone_data.update({'expire': bind_zone_time_to_expire}) %} +{% set _ = _zone_data.update({'minimum': bind_zone_minimum_ttl}) %} +{% set _ = _zone_data.update({'hosts': item.0.hosts|default([]) | selectattr('ipv6','defined') | selectattr('ipv6','string') | selectattr('ipv6', 'search', '^'+item.1|regex_replace('/.*$','')) | list }) %} +{% set _ = _zone_data.update({'revip': (item.1 | ipaddr('revdns'))[-(9+(item.1|regex_replace('^.*/','')|int)//2):] }) %} +{# + # Compare the zone file hash with the current zone data hash and set serial + # accordingly + #} +{% set _zone = {'hash': _zone_data | string | hash('md5')} %} +{% for _result in reverse_hashes_ipv6 if _result.network == item.1 %} +{% set _hash_serial = _result.hash.split(' ')[2:] %} +{% if _hash_serial and _hash_serial[0] == _zone['hash'] %} +{% set _ = _zone.update({'serial': _hash_serial[1]}) %} +{% else %} +{% set _ = _zone.update({'serial': timestamp.stdout}) %} +{% endif %} +{% endfor %} +{# + # Eventually output the zone data + #} +; Hash: {{ _zone['hash'] }} {{ _zone['serial'] }} +; Reverse zone file for {{ _zone_data['domain'] }} +{{ ansible_managed | comment(decoration='; ') }} + +$TTL {{ _zone_data['ttl'] }} +$ORIGIN {{ (item.1 | ipaddr('revdns'))[-(9+(item.1|regex_replace('^.*/','')|int)//2):] }} + +{% if _zone_data['mname']|length > 0 %} +@ IN SOA {{ _zone_data['mname']|first }}{% if not _zone_data['mname']|first|regex_search('\.$') %}.{{ _zone_data['domain'] }}.{% endif %} {{ _zone_data['rname'] }}. ( +{% else %} +@ IN SOA {{ ansible_hostname }}.{{ _zone_data['domain'] }}. {{ _zone_data['rname'] }}. ( +{% endif %} + {{ _zone['serial'] }} + {{ _zone_data['refresh'] }} + {{ _zone_data['retry'] }} + {{ _zone_data['expire'] }} + {{ _zone_data['minimum'] }} ) + +{% if _zone_data['mname']|length > 0 %} +{% for ns in _zone_data['mname'] %} + IN NS {{ ns }}{% if not ns|regex_search('\.$') %}.{{ _zone_data['domain'] }}.{% endif %} + +{% endfor %} +{% else %} + IN NS {{ ansible_hostname }}.{{ _zone_data['domain'] }}. +{% endif %} +{% for ns in _zone_data['aname'] %} + IN NS {{ ns }}. +{% endfor %} + +{% if _zone_data['hosts']|length > 0 %} +{% for host in _zone_data['hosts'] %} +{% if host.ipv6 is defined %} +{% if host.ipv6 == item.1 %} +@ IN PTR {{ host.name }}.{{ _zone_data['domain'] }}. +{% else %} +{% if host.ipv6 is string and host.ipv6.startswith(item.1|regex_replace('/.*$','')) %} +{% if host.name == '@' %} +{{ host.ipv6 | ipaddr('revdns') }} IN PTR {{ _zone_data['domain'] }}. +{% else %} +{{ host.ipv6 | ipaddr('revdns') }} IN PTR {{ host.name }}.{{ _zone_data['domain'] }}. +{% endif %} +{% else %} +{% for ip in host.ipv6 %} +{% if ip.startswith(item.1|regex_replace('/.*$','')) %} +{{ ip | ipaddr('revdns') }} IN PTR {{ _zone_data['domain'] }}. +{% if host.name == '@' %} +{% else %} +{{ ip | ipaddr('revdns') }} IN PTR {{ host.name }}.{{ _zone_data['domain'] }}. +{% endif %} +{% endif %} +{% endfor %} +{% endif %} +{% endif %} +{% endif %} +{% endfor %} +{% else %} +{{ ansible_default_ipv6.address | ipaddr('revdns') }} IN PTR {{ ansible_hostname }}.{{ _zone_data['domain'] }}. +{% endif %} diff --git a/templates/slave_etc_named.conf.j2 b/templates/slave_etc_named.conf.j2 new file mode 100644 index 0000000..ec5584a --- /dev/null +++ b/templates/slave_etc_named.conf.j2 @@ -0,0 +1,103 @@ +// +// named.conf +// +{{ ansible_managed | comment('c') }} +// +{% for acl in bind_acls %} +acl "{{ acl.name }}" { +{% for match in acl.match_list %} + {{ match }}; +{% endfor %} +}; + +{% endfor %} +options { + listen-on port 53 { {{ bind_listen_ipv4|join(';') }}; }; + listen-on-v6 port 53 { {{ bind_listen_ipv6|join(';') }}; }; + directory "{{ bind_dir }}"; + dump-file "{{ bind_dir }}/data/cache_dump.db"; + statistics-file "{{ bind_dir }}/data/named_stats.txt"; + memstatistics-file "{{ bind_dir }}/data/named_mem_stats.txt"; + allow-query { {{ bind_allow_query|join(';') }}; }; +{% if bind_acls|length != 0 %} + allow-transfer { {% for acl in bind_acls %}"{{ acl.name }}"; {% endfor %}}; +{% endif %} + + recursion {% if bind_recursion %}yes{% else %}no{% endif %}; +{% if bind_forwarders|length > 0 %}forwarders { {{ bind_forwarders|join('; ') }}; };{% endif %} + {% if bind_forward_only %}forward only;{% endif %} + + rrset-order { order {{ bind_rrset_order }}; }; + + dnssec-enable {{ bind_dnssec_enable }}; + dnssec-validation {{ bind_dnssec_validation }}; + dnssec-lookaside auto; + + /* Path to ISC DLV key */ + bindkeys-file "/etc/named.iscdlv.key"; + + managed-keys-directory "{{ bind_dir }}/dynamic"; + + pid-file "/run/named/named.pid"; + session-keyfile "/run/named/session.key"; +{% if bind_query_log is defined %} + querylog yes; +{% endif %} +}; + +logging { + channel default_debug { + file "{{ bind_log }}"; + severity dynamic; + print-time yes; + }; +{% if bind_query_log is defined %} + channel querylog { + file "{{ bind_query_log }}" versions 600 size 20m; + severity dynamic; + print-time yes; + }; + category queries { querylog; }; +{% endif %} +}; + +{% for file in bind_default_zone_files %} +include "{{ file }}"; +{% endfor %} +{% for file in bind_extra_include_files %} +include "{{ file }}"; +{% endfor %} + +{% if bind_zone_domains is defined %} +{% for bind_zone in bind_zone_domains %} +zone "{{ bind_zone.name }}" IN { + type slave; + masters { {{ bind_zone_master_server_ip }}; }; + file "slaves/{{ bind_zone.name }}"; +{% if bind_zone.delegate is defined %} + forwarders {}; +{% endif %} +}; + +{% if bind_zone.networks is defined %} +{% for network in bind_zone.networks %} +zone "{{ ('.'.join(network.replace(network+'.','').split('.')[::-1])) }}.in-addr.arpa" IN { + type slave; + masters { {{ bind_zone_master_server_ip }}; }; + file "slaves/{{ ('.'.join(network.replace(network+'.','').split('.')[::-1])) }}.in-addr.arpa"; +}; +{% endfor %} +{% endif %} + +{% if bind_zone.ipv6_networks is defined %} +{% for network in bind_zone.ipv6_networks %} +zone "{{ (network | ipaddr('revdns'))[-(9+(network|regex_replace('^.*/','')|int)//2):] }}" IN { + type slave; + masters { {{ bind_zone_master_server_ip }}; }; + file "slaves/{{ (network | ipaddr('revdns'))[-(9+(network|regex_replace('^.*/','')|int)//2):-1] }}"; +}; +{% endfor %} +{% endif %} +{% endfor %} +{% endif %} + diff --git a/vars/Archlinux.yml b/vars/Archlinux.yml new file mode 100644 index 0000000..ce96098 --- /dev/null +++ b/vars/Archlinux.yml @@ -0,0 +1,21 @@ +# roles/bind/vars/RedHat.yml +--- + +bind_packages: + - python-netaddr + - bind + - bind-tools + +bind_service: named + +# Main config file +bind_config: /etc/named.conf + +# Zone files included in the installation +bind_default_zone_files: [] + +# Directory with run-time stuff +bind_dir: /var/named + +bind_owner: root +bind_group: named diff --git a/vars/Debian.yml b/vars/Debian.yml new file mode 100644 index 0000000..53ad28f --- /dev/null +++ b/vars/Debian.yml @@ -0,0 +1,22 @@ +# roles/bind/vars/Debian.yml +--- + +bind_packages: + - python-netaddr + - bind9 + - bind9utils + +bind_service: bind9 + +# Main config file +bind_config: /etc/bind/named.conf + +# Localhost zone +bind_default_zone_files: + - /etc/bind/named.conf.default-zones + +# Directory with run-time stuff +bind_dir: /var/cache/bind + +bind_owner: root +bind_group: bind diff --git a/vars/RedHat.yml b/vars/RedHat.yml new file mode 100644 index 0000000..abad819 --- /dev/null +++ b/vars/RedHat.yml @@ -0,0 +1,23 @@ +# roles/bind/vars/RedHat.yml +--- + +bind_packages: + - python-netaddr + - bind + - bind-utils + +bind_service: named + +# Main config file +bind_config: /etc/named.conf + +# Zone files included in the installation +bind_default_zone_files: + - /etc/named.root.key + - /etc/named.rfc1912.zones + +# Directory with run-time stuff +bind_dir: /var/named + +bind_owner: root +bind_group: named diff --git a/vars/main.yml b/vars/main.yml deleted file mode 100644 index e69de29..0000000