├── .delivery └── project.toml ├── .gitignore ├── .kitchen.dokken.yml ├── .kitchen.yml ├── .rubocop.yml ├── .travis.yml ├── Berksfile ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Gemfile ├── LICENSE ├── README.md ├── TESTING.md ├── attributes └── default.rb ├── chefignore ├── libraries ├── entry.rb ├── manipulator.rb └── matchers.rb ├── metadata.rb ├── resources └── entry.rb ├── spec ├── spec_helper.rb └── unit │ ├── entry_spec.rb │ └── manipulator_spec.rb └── test ├── fixtures └── cookbooks │ └── test │ ├── metadata.rb │ └── recipes │ ├── append.rb │ ├── append_existing.rb │ ├── create.rb │ ├── create_if_missing.rb │ ├── default.rb │ ├── options.rb │ ├── remove.rb │ ├── unique.rb │ └── update.rb └── integration ├── append └── serverspec │ └── append_spec.rb ├── append_existing └── serverspec │ └── append_existing_spec.rb ├── create └── serverspec │ └── create_spec.rb ├── create_if_missing └── serverspec │ └── create_if_missing_spec.rb ├── default └── serverspec │ └── default_spec.rb ├── options └── serverspec │ └── options_spec.rb └── unique └── serverspec └── unique_spec.rb /.delivery/project.toml: -------------------------------------------------------------------------------- 1 | remote_file = "https://raw.githubusercontent.com/chef-cookbooks/community_cookbook_tools/master/delivery/project.toml" 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.rbc 2 | .config 3 | coverage 4 | InstalledFiles 5 | lib/bundler/man 6 | pkg 7 | rdoc 8 | spec/reports 9 | test/tmp 10 | test/version_tmp 11 | tmp 12 | _Store 13 | *~ 14 | *# 15 | .#* 16 | \#*# 17 | .*.sw[a-z] 18 | *.un~ 19 | *.tmp 20 | *.bk 21 | *.bkup 22 | 23 | # ruby/bundler files 24 | .ruby-version 25 | .ruby-gemset 26 | .rvmrc 27 | Gemfile.lock 28 | .bundle 29 | *.gem 30 | 31 | # YARD artifacts 32 | .yardoc 33 | _yardoc 34 | doc/ 35 | .idea 36 | 37 | # chef stuff 38 | Berksfile.lock 39 | .kitchen 40 | .kitchen.local.yml 41 | vendor/ 42 | .coverage/ 43 | .zero-knife.rb 44 | Policyfile.lock.json 45 | Cheffile.lock 46 | .librarian/ 47 | 48 | # vagrant stuff 49 | .vagrant/ 50 | .vagrant.d/ 51 | .kitchen/ 52 | -------------------------------------------------------------------------------- /.kitchen.dokken.yml: -------------------------------------------------------------------------------- 1 | driver: 2 | name: dokken 3 | privileged: true # because Docker and SystemD/Upstart 4 | chef_version: <%= ENV['CHEF_VERSION'] || 'current' %> 5 | 6 | transport: 7 | name: dokken 8 | 9 | provisioner: 10 | name: dokken 11 | deprecations_as_errors: true 12 | 13 | verifier: 14 | name: inspec 15 | 16 | platforms: 17 | - name: amazonlinux 18 | driver: 19 | image: dokken/amazonlinux 20 | pid_one_command: /sbin/init 21 | 22 | - name: debian-7 23 | driver: 24 | image: dokken/debian-7 25 | pid_one_command: /sbin/init 26 | intermediate_instructions: 27 | - RUN /usr/bin/apt-get update 28 | 29 | - name: debian-8 30 | driver: 31 | image: dokken/debian-8 32 | pid_one_command: /bin/systemd 33 | intermediate_instructions: 34 | - RUN /usr/bin/apt-get update 35 | 36 | - name: debian-9 37 | driver: 38 | image: dokken/debian-9 39 | pid_one_command: /bin/systemd 40 | intermediate_instructions: 41 | - RUN /usr/bin/apt-get update 42 | 43 | - name: centos-6 44 | driver: 45 | image: dokken/centos-6 46 | pid_one_command: /sbin/init 47 | 48 | - name: centos-7 49 | driver: 50 | image: dokken/centos-7 51 | pid_one_command: /usr/lib/systemd/systemd 52 | 53 | - name: fedora-latest 54 | driver: 55 | image: dokken/fedora-latest 56 | pid_one_command: /usr/lib/systemd/systemd 57 | 58 | - name: ubuntu-14.04 59 | driver: 60 | image: dokken/ubuntu-14.04 61 | pid_one_command: /sbin/init 62 | intermediate_instructions: 63 | - RUN /usr/bin/apt-get update 64 | 65 | - name: ubuntu-16.04 66 | driver: 67 | image: dokken/ubuntu-16.04 68 | pid_one_command: /bin/systemd 69 | intermediate_instructions: 70 | - RUN /usr/bin/apt-get update 71 | 72 | - name: opensuse-leap 73 | driver: 74 | image: dokken/opensuse-leap 75 | pid_one_command: /bin/systemd -------------------------------------------------------------------------------- /.kitchen.yml: -------------------------------------------------------------------------------- 1 | driver: 2 | name: vagrant 3 | 4 | provisioner: 5 | name: chef_zero 6 | deprecations_as_errors: true 7 | 8 | platforms: 9 | - name: amazon-linux 10 | driver_config: 11 | box: mvbcoding/awslinux 12 | - name: centos-6.9 13 | - name: centos-7.3 14 | - name: debian-7.11 15 | - name: debian-8.9 16 | - name: debian-9.1 17 | - name: fedora-26 18 | - name: opensuse-leap-42.3 19 | - name: ubuntu-14.04 20 | - name: ubuntu-16.04 21 | 22 | suites: 23 | - name: append 24 | run_list: test::append 25 | - name: append_existing 26 | run_list: test::append_existing 27 | - name: create 28 | run_list: test::create 29 | - name: create_if_missing 30 | run_list: test::create_if_missing 31 | - name: default 32 | run_list: test::default 33 | - name: options 34 | run_list: test::options 35 | - name: unique 36 | run_list: test::unique 37 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | # Rubocop (cookstyle) todo: 2 | 3 | # Configuration parameters: AllowSafeAssignment. 4 | Lint/AssignmentInCondition: 5 | Exclude: 6 | - 'libraries/manipulator.rb' 7 | 8 | Lint/ShadowingOuterLocalVariable: 9 | Exclude: 10 | - 'libraries/entry.rb' 11 | - 'libraries/manipulator.rb' 12 | 13 | Style/DoubleNegation: 14 | Exclude: 15 | - 'libraries/manipulator.rb' 16 | 17 | # Configuration parameters: MinBodyLength. 18 | Style/GuardClause: 19 | Exclude: 20 | - 'libraries/manipulator.rb' 21 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | dist: trusty 3 | 4 | addons: 5 | apt: 6 | sources: 7 | - chef-current-trusty 8 | packages: 9 | - chefdk 10 | 11 | # Don't `bundle install` which takes about 1.5 mins 12 | install: echo "skip bundle install" 13 | 14 | branches: 15 | only: 16 | - master 17 | 18 | services: docker 19 | 20 | env: 21 | matrix: 22 | - INSTANCE=append-centos-6 23 | - INSTANCE=append-centos-7 24 | - INSTANCE=append-ubuntu-1404 25 | - INSTANCE=append-ubuntu-1604 26 | - INSTANCE=create-centos-6 27 | - INSTANCE=create-centos-7 28 | - INSTANCE=create-ubuntu-1404 29 | - INSTANCE=create-ubuntu-1604 30 | 31 | before_script: 32 | - sudo iptables -L DOCKER || ( echo "DOCKER iptables chain missing" ; sudo iptables -N DOCKER ) 33 | - eval "$(chef shell-init bash)" 34 | - chef --version 35 | - cookstyle --version 36 | - foodcritic --version 37 | 38 | script: KITCHEN_LOCAL_YAML=.kitchen.dokken.yml kitchen verify ${INSTANCE} 39 | 40 | matrix: 41 | include: 42 | - script: 43 | - chef exec delivery local all 44 | env: UNIT_AND_LINT=1 45 | -------------------------------------------------------------------------------- /Berksfile: -------------------------------------------------------------------------------- 1 | source 'https://supermarket.chef.io' 2 | 3 | metadata 4 | 5 | group :integration do 6 | cookbook 'test', path: 'test/fixtures/cookbooks/test' 7 | end 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # hostsfile Cookbook CHANGELOG 2 | 3 | This file is used to list changes made in each version of the hostsfile cookbook. 4 | 5 | ## v3.0.1 (2017-08-22) 6 | 7 | - Add TESTING.md and CONTRIBUTING.md files 8 | - Fix the readme to properly specify Chef 12.7+ as the Chef requirement 9 | - Add a local delivery configuration and remove the existing rakefile 10 | - Resolve _most_ of the ChefSpec failures 11 | 12 | ## v3.0.0 (2017-08-22) 13 | 14 | - Converted the LWRP to a custom resource which increases the required Chef release to 12.7 15 | - Namespaced the helper libraries under the HostsFile module to prevent method collisions with other resources or the chef-client itself 16 | 17 | ## v2.4.6 (2017-08-15) 18 | 19 | - use openssl for FIPS compatibility 20 | - Expand priority documentation in README 21 | - Add ::1 loopback to test cases and priority settings 22 | 23 | ## v2.4.5 (2014-06-24) 24 | 25 | - Fix notifications and why-run mode 26 | 27 | ## v2.4.4 (2014-02-25) 28 | 29 | - Bump Berkshelf version 30 | - Remove scope pieces from IPv6 addresses 31 | 32 | ## v2.4.3 (2014-02-01) 33 | 34 | - Package custom ChefSpec matchers 35 | - Update testing harness 36 | - Avoid using `Chef::Application.fatal!` 37 | - Use Chef::Resource::File for atomic updates 38 | 39 | ## v2.4.2 40 | 41 | - Fix Travis CI integration 42 | - Remove newline characters 43 | - Allow specifying a custom hostsfile path 44 | 45 | ## v2.4.1 46 | 47 | - Force a new upload to the community site 48 | 49 | ## v2.4.0 50 | 51 | - Convert everything to Ruby 1.9 syntax because I'm tired of people removing trailing commas despite the **massive** warning in the README: ([#29](https://github.com/customink-webops/hostsfile/issues/29), [#30](https://github.com/customink-webops/hostsfile/issues/30), [#32](https://github.com/customink-webops/hostsfile/issues/32), [#33](https://github.com/customink-webops/hostsfile/issues/33), [#34](https://github.com/customink-webops/hostsfile/issues/34), [#35](https://github.com/customink-webops/hostsfile/issues/35), [#36](https://github.com/customink-webops/hostsfile/issues/36), [#38](https://github.com/customink-webops/hostsfile/issues/38), [#39](https://github.com/customink-webops/hostsfile/issues/39)) 52 | - Update to the latest and greatest testing gems and practices 53 | - Remove strainer in favor of a purer solution 54 | - Update `.gitignore` to ignore additional files 55 | - Add more platforms to the `.kitchen.yml` 56 | - Use `converge_by` and support whyruny mode 57 | 58 | ## v2.0.0 59 | 60 | - Completely manage the hostsfile, ensuring no duplicate entries 61 | 62 | ## v1.0.2 63 | 64 | - Support Windows (thanks @igantt-daptiv) 65 | - Specs + Travis support 66 | - Throw fatal error if hostsfile does not exist (@jkerzner) 67 | - Write priorities in hostsfile so they are read on subsequent Chef runs 68 | 69 | ## v0.2.0 70 | 71 | - Updated README to require Ruby 1.9 72 | - Allow hypens in hostnames 73 | - Ensure newline at end of file 74 | - Allow priority ordering in hostsfile 75 | 76 | ## v0.1.1 77 | 78 | - Fixed issue #1 79 | - Better unique object filtering 80 | - Better handing of aliases 81 | 82 | ## v0.1.0 83 | 84 | - Initial release 85 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 1. Fork the project 4 | 2. Create a feature branch corresponding to you change 5 | 3. Commit and test thoroughly 6 | 4. Create a Pull Request on GitHub 7 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # This gemfile provides additional gems for testing and releasing this cookbook 2 | # It is meant to be installed on top of ChefDK which provides the majority 3 | # of the necessary gems for testing this cookbook 4 | # 5 | # Run 'chef exec bundle install' to install these dependencies 6 | 7 | source 'https://rubygems.org' 8 | 9 | gem 'stove' 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # hostsfile cookbook 2 | 3 | [![Build Status](https://travis-ci.org/customink-webops/hostsfile.svg?branch=master)](https://travis-ci.org/customink-webops/hostsfile) 4 | 5 | `hostsfile` provides a resource for managing your `/etc/hosts` (or Windows equivalent) file using Chef. 6 | 7 | ## Requirements 8 | 9 | - Chef 12.7 or higher 10 | 11 | ## Attributes 12 | 13 | Attribute | Description | Example | Default 14 | ---------- | ------------------------------------------------------- | --------------------- | ------------------------------------ 15 | ip_address | (name attribute) the IP address for the entry | 1.2.3.4 | 16 | hostname | (required) the hostname associated with the entry | example.com | 17 | unique | remove any existing entries that have the same hostname | true | false 18 | aliases | array of aliases for the entry | ['www.example.com'] | [] 19 | comment | a comment to append to the end of the entry | 'internal DNS server' | nil 20 | priority | the relative position of this entry | 20 | (varies, see **Priorities** section) 21 | 22 | ## Actions 23 | 24 | **Please note**: In `v0.1.2`, specifying a hostname or alias that existed in another automatically removed that hostname from the other entry before. In `v2.1.0`, the `unique` option was added to give the user case-by-case control of this behavior. For example, given an `/etc/hosts` file that contains: 25 | 26 | ``` 27 | 1.2.3.4 example.com www.example.com 28 | ``` 29 | 30 | when the Chef recipe below is converged: 31 | 32 | ```ruby 33 | hostsfile_entry '2.3.4.5' do 34 | hostname 'www.example.com' 35 | unique true 36 | end 37 | ``` 38 | 39 | then the `/etc/hosts` file will look like this: 40 | 41 | ``` 42 | 1.2.3.4 example.com 43 | 2.3.4.5 www.example.com 44 | ``` 45 | 46 | Not specifying the `unique` parameter will result in duplicate hostsfile entries. 47 | 48 | ### `create` 49 | 50 | Creates a new hosts file entry. If an entry already exists, it will be overwritten by this one. 51 | 52 | ```ruby 53 | hostsfile_entry '1.2.3.4' do 54 | hostname 'example.com' 55 | action :create 56 | end 57 | ``` 58 | 59 | This will create an entry like this: 60 | 61 | ``` 62 | 1.2.3.4 example.com 63 | ``` 64 | 65 | ### `create_if_missing` 66 | 67 | Create a new hosts file entry, only if one does not already exist for the given IP address. If one exists, this does nothing. 68 | 69 | ```ruby 70 | hostsfile_entry '1.2.3.4' do 71 | hostname 'example.com' 72 | action :create_if_missing 73 | end 74 | ``` 75 | 76 | ### `append` 77 | 78 | Append a hostname or alias to an existing record. If the given IP address doesn't already exist in the hostsfile, this method behaves the same as create. Otherwise, it will append the additional hostname and aliases to the existing entry. 79 | 80 | ``` 81 | 1.2.3.4 example.com www.example.com # Created by Chef 82 | ``` 83 | 84 | ```ruby 85 | hostsfile_entry '1.2.3.4' do 86 | hostname 'www2.example.com' 87 | aliases ['foo.com', 'foobar.com'] 88 | comment 'Appended by Recipe X' 89 | action :append 90 | end 91 | ``` 92 | 93 | would yield: 94 | 95 | ``` 96 | 1.2.3.4 example.com www.example.com www2.example.com foo.com foobar.com # Created by Chef, Appended by Recipe X 97 | ``` 98 | 99 | ### `update` 100 | 101 | Updates the given hosts file entry. Does nothing if the entry does not exist. 102 | 103 | ```ruby 104 | hostsfile_entry '1.2.3.4' do 105 | hostname 'example.com' 106 | comment 'Updated by Chef' 107 | action :update 108 | end 109 | ``` 110 | 111 | This will create an entry like this: 112 | 113 | ``` 114 | 1.2.3.4 example # Updated by Chef 115 | ``` 116 | 117 | ### `remove` 118 | 119 | Removes an entry from the hosts file. Does nothing if the entry does not exist. 120 | 121 | ```ruby 122 | hostsfile_entry '1.2.3.4' do 123 | action :remove 124 | end 125 | ``` 126 | 127 | This will remove the entry for `1.2.3.4`. 128 | 129 | ## Usage 130 | 131 | If you're using [Berkshelf](http://berkshelf.com/), just add `hostsfile` to your `Berksfile`: 132 | 133 | ```ruby 134 | cookbook 'hostsfile' 135 | ``` 136 | 137 | Otherwise, install the cookbook from the community site: 138 | 139 | ``` 140 | knife cookbook site install hostsfile 141 | ``` 142 | 143 | Have any other cookbooks _depend_ on hostsfile by editing editing the `metadata.rb` for your cookbook. 144 | 145 | ```ruby 146 | # metadata.rb 147 | depends 'hostsfile' 148 | ``` 149 | 150 | Note that you can specify a custom path to your hosts file in the `['hostsfile']['path']` node attribute. Otherwise, it defaults to sensible paths depending on your OS. 151 | 152 | ### Testing 153 | 154 | If you are using [ChefSpec](https://github.com/sethvargo/chefspec) to unit test a cookbook that implements the `hostsfile_entry` resource, this cookbook packages customer matchers that you can use in your unit tests: 155 | 156 | - `append_hostsfile_entry` 157 | - `create_hostsfile_entry` 158 | - `create_hostsfile_entry_if_missing` 159 | - `remove_hostsfile_entry` 160 | - `update_hostsfile_entry` 161 | 162 | For example: 163 | 164 | ```ruby 165 | it 'creates a hostsfile entry for the DNS server' do 166 | expect(chef_run).to create_hostsfile_entry('1.2.3.4') 167 | .with_hostname('dns.example.com') 168 | end 169 | ``` 170 | 171 | ## Priority 172 | 173 | Priority is a relatively new addition to the cookbook. It gives you the ability to (somewhat) specify the relative order of entries. By default, the priority is calculated for you as follows: 174 | 175 | 82. 127.0.0.1 176 | 81. ::1 177 | 80. 127.0.0.0/8 178 | 60. IPV4 179 | 20. IPV6 180 | 00. default 181 | 182 | However, you can override it using the `priority` option. 183 | 184 | ## License & Authors 185 | 186 | - Author:: Seth Vargo (sethvargo@gmail.com) 187 | 188 | ```text 189 | Copyright 2012-2013, Seth Vargo 190 | Copyright 2012, CustomInk, LLC 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | ``` 204 | -------------------------------------------------------------------------------- /TESTING.md: -------------------------------------------------------------------------------- 1 | Please refer to 2 | https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/TESTING.MD 3 | -------------------------------------------------------------------------------- /attributes/default.rb: -------------------------------------------------------------------------------- 1 | # 2 | # Author:: Seth Vargo 3 | # Cookbook:: hostsfile 4 | # Attribute:: default 5 | # 6 | # Copyright:: 2012-2013, Seth Vargo 7 | # Copyright:: 2012, CustomInk, LCC 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | default['hostsfile']['path'] = nil 23 | -------------------------------------------------------------------------------- /chefignore: -------------------------------------------------------------------------------- 1 | # Put files/directories that should be ignored in this file when uploading 2 | # to a chef-server or supermarket. 3 | # Lines that start with '# ' are comments. 4 | 5 | # OS generated files # 6 | ###################### 7 | .DS_Store 8 | Icon? 9 | nohup.out 10 | ehthumbs.db 11 | Thumbs.db 12 | 13 | # SASS # 14 | ######## 15 | .sass-cache 16 | 17 | # EDITORS # 18 | ########### 19 | \#* 20 | .#* 21 | *~ 22 | *.sw[a-z] 23 | *.bak 24 | REVISION 25 | TAGS* 26 | tmtags 27 | *_flymake.* 28 | *_flymake 29 | *.tmproj 30 | .project 31 | .settings 32 | mkmf.log 33 | 34 | ## COMPILED ## 35 | ############## 36 | a.out 37 | *.o 38 | *.pyc 39 | *.so 40 | *.com 41 | *.class 42 | *.dll 43 | *.exe 44 | */rdoc/ 45 | 46 | # Testing # 47 | ########### 48 | .watchr 49 | .rspec 50 | spec/* 51 | spec/fixtures/* 52 | test/* 53 | features/* 54 | examples/* 55 | Guardfile 56 | Procfile 57 | .kitchen* 58 | .rubocop.yml 59 | spec/* 60 | Rakefile 61 | .travis.yml 62 | .foodcritic 63 | .codeclimate.yml 64 | 65 | # SCM # 66 | ####### 67 | .git 68 | */.git 69 | .gitignore 70 | .gitmodules 71 | .gitconfig 72 | .gitattributes 73 | .svn 74 | */.bzr/* 75 | */.hg/* 76 | */.svn/* 77 | 78 | # Berkshelf # 79 | ############# 80 | Berksfile 81 | Berksfile.lock 82 | cookbooks/* 83 | tmp 84 | 85 | # Policyfile # 86 | ############## 87 | Policyfile.rb 88 | Policyfile.lock.json 89 | 90 | # Cookbooks # 91 | ############# 92 | CONTRIBUTING* 93 | CHANGELOG* 94 | TESTING* 95 | MAINTAINERS.toml 96 | 97 | # Strainer # 98 | ############ 99 | Colanderfile 100 | Strainerfile 101 | .colander 102 | .strainer 103 | 104 | # Vagrant # 105 | ########### 106 | .vagrant 107 | Vagrantfile 108 | -------------------------------------------------------------------------------- /libraries/entry.rb: -------------------------------------------------------------------------------- 1 | # 2 | # Author:: Seth Vargo 3 | # Cookbook:: hostsfile 4 | # Library:: entry 5 | # 6 | # Copyright:: 2012-2013, Seth Vargo 7 | # Copyright:: 2012, CustomInk, LCC 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | require 'ipaddr' 23 | 24 | # An object representation of a single line in a hostsfile. 25 | # 26 | # @author Seth Vargo 27 | module HostsFile 28 | class Entry 29 | class << self 30 | # Creates a new Hostsfile::Entry object by parsing a text line. The 31 | # `line` attribute will be in the following format: 32 | # 33 | # 1.2.3.4 hostname [alias[, alias[, alias]]] [# comment [@priority]] 34 | # 35 | # @param [String] line 36 | # the line to parse 37 | # @return [Entry] 38 | # a new entry object 39 | def parse(line) 40 | entry, comment = extract_comment(line) 41 | comment, priority = extract_priority(comment) 42 | entries = extract_entries(entry) 43 | 44 | # Return nil if the line is empty 45 | return nil if entries.nil? || entries.empty? 46 | 47 | # If /etc/hosts has a broken content we throw a descriptive exception 48 | if entries[0].nil? 49 | raise ArgumentError, "/etc/hosts has a line without IP address: #{line}" 50 | end 51 | if entries[1].nil? 52 | raise ArgumentError, "/etc/hosts has a line without hostname: #{line}" 53 | end 54 | 55 | new( 56 | ip_address: entries[0], 57 | hostname: entries[1], 58 | aliases: entries[2..-1], 59 | comment: comment, 60 | priority: priority 61 | ) 62 | end 63 | 64 | private 65 | 66 | def extract_comment(line) 67 | return nil if presence(line).nil? 68 | line.split('#', 2).collect { |part| presence(part) } 69 | end 70 | 71 | def extract_priority(comment) 72 | return nil if comment.nil? 73 | 74 | if comment.include?('@') 75 | comment.split('@', 2).collect { |part| presence(part) } 76 | else 77 | [comment, nil] 78 | end 79 | end 80 | 81 | def extract_entries(entry) 82 | return nil if entry.nil? 83 | entry.split(/\s+/).collect { |entry| presence(entry) }.compact 84 | end 85 | 86 | def presence(string) 87 | return nil if string.nil? 88 | return nil if string.strip.empty? 89 | string.strip 90 | end 91 | end 92 | 93 | # @return [String] 94 | attr_accessor :ip_address, :hostname, :aliases, :comment, :priority 95 | 96 | # Creates a new entry from the given options. 97 | # 98 | # @param [Hash] options 99 | # a list of options to create the entry with 100 | # @option options [String] :ip_address 101 | # the IP Address for this entry 102 | # @option options [String] :hostname 103 | # the hostname for this entry 104 | # @option options [String, Array] :aliases 105 | # a alias or array of aliases for this entry 106 | # @option options[String] :comment 107 | # an optional comment for this entry 108 | # @option options [Integer] :priority 109 | # the relative priority of this entry (compared to others) 110 | # 111 | # @raise [ArgumentError] 112 | # if neither :ip_address nor :hostname are supplied 113 | def initialize(options = {}) 114 | if options[:ip_address].nil? || options[:hostname].nil? 115 | raise ArgumentError, ':ip_address and :hostname are both required options' 116 | end 117 | 118 | @ip_address = IPAddr.new(remove_ip_scope(options[:ip_address])) 119 | @hostname = options[:hostname] 120 | @aliases = [options[:aliases]].flatten.compact 121 | @comment = options[:comment] 122 | @priority = options[:priority] || calculated_priority 123 | end 124 | 125 | # Set a the new priority for an entry. 126 | # 127 | # @param [Integer] new_priority 128 | # the new priority to set 129 | def priority=(new_priority) 130 | @calculated_priority = false 131 | @priority = new_priority 132 | end 133 | 134 | # The line representation of this entry. 135 | # 136 | # @return [String] 137 | # the string representation of this entry 138 | def to_line 139 | hosts = [hostname, aliases].flatten.join(' ') 140 | 141 | comments = "# #{comment}".strip 142 | comments << " @#{priority}" unless priority.nil? || @calculated_priority 143 | comments = comments.strip 144 | comments = nil if comments == '#' 145 | 146 | [ip_address, hosts, comments].compact.join("\t").strip 147 | end 148 | 149 | # Returns true if priority is calculated 150 | # 151 | # @return [Boolean] 152 | # true if priority is calculated and false otherwise 153 | def calculated_priority? 154 | @calculated_priority 155 | end 156 | 157 | private 158 | 159 | # Calculates the relative priority of this entry. 160 | # 161 | # @return [Integer] 162 | # the relative priority of this item 163 | def calculated_priority 164 | @calculated_priority = true 165 | 166 | return 82 if ip_address == IPAddr.new('127.0.0.1') 167 | return 81 if ip_address == IPAddr.new('::1') 168 | return 80 if IPAddr.new('127.0.0.0/8').include?(ip_address) # local 169 | return 60 if ip_address.ipv4? # ipv4 170 | return 20 if ip_address.ipv6? # ipv6 171 | 00 172 | end 173 | 174 | # Removes the scopes pieces of the address, because reasons. 175 | # 176 | # @see https://bugs.ruby-lang.org/issues/8464 177 | # @see https://github.com/customink-webops/hostsfile/issues/51 178 | # 179 | # @return [String, nil] 180 | # 181 | def remove_ip_scope(address) 182 | return nil if address.nil? 183 | address.to_s.sub(/%.*/, '') 184 | end 185 | end 186 | end 187 | -------------------------------------------------------------------------------- /libraries/manipulator.rb: -------------------------------------------------------------------------------- 1 | # 2 | # Author:: Seth Vargo 3 | # Cookbook:: hostsfile 4 | # Library:: manipulator 5 | # 6 | # Copyright:: 2012-2013, Seth Vargo 7 | # Copyright:: 2012, CustomInk, LCC 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | require 'chef/application' 23 | require 'openssl' 24 | 25 | module HostsFile 26 | class Manipulator 27 | attr_reader :node 28 | attr_reader :entries 29 | 30 | # Create a new Manipulator object (aka an /etc/hosts manipulator). If a 31 | # hostsfile is not found, an exception is raised. 32 | # 33 | # @param [Chef::node] node 34 | # the current Chef node 35 | # @return [Manipulator] 36 | # a class designed to manipulate the node's /etc/hosts file 37 | def initialize(node) 38 | @node = node 39 | 40 | # Fail if no hostsfile is found 41 | unless ::File.exist?(hostsfile_path) 42 | raise "No hostsfile exists at `#{hostsfile_path}'!" 43 | end 44 | 45 | @entries = [] 46 | collect_and_flatten(::File.readlines(hostsfile_path)) 47 | end 48 | 49 | # Return a list of all IP Addresses for this hostsfile. 50 | # 51 | # @return [Array] 52 | # the list of IP Addresses 53 | def ip_addresses 54 | @entries.collect(&:ip_address).compact || [] 55 | end 56 | 57 | # Add a new record to the hostsfile. 58 | # 59 | # @param [Hash] options 60 | # a list of options to create the entry with 61 | # @option options [String] :ip_address 62 | # the IP Address for this entry 63 | # @option options [String] :hostname 64 | # the hostname for this entry 65 | # @option options [String, Array] :aliases 66 | # a alias or array of aliases for this entry 67 | # @option options[String] :comment 68 | # an optional comment for this entry 69 | # @option options [Integer] :priority 70 | # the relative priority of this entry (compared to others) 71 | def add(options = {}) 72 | entry = HostsFile::Entry.new( 73 | ip_address: options[:ip_address], 74 | hostname: options[:hostname], 75 | aliases: options[:aliases], 76 | comment: options[:comment], 77 | priority: options[:priority] 78 | ) 79 | 80 | @entries << entry 81 | remove_existing_hostnames(entry) if options[:unique] 82 | end 83 | 84 | # Update an existing entry. This method will do nothing if the entry 85 | # does not exist. 86 | # 87 | # @param (see #add) 88 | def update(options = {}) 89 | if entry = find_entry_by_ip_address(options[:ip_address]) 90 | entry.hostname = options[:hostname] 91 | entry.aliases = options[:aliases] 92 | entry.comment = options[:comment] 93 | entry.priority = options[:priority] 94 | 95 | remove_existing_hostnames(entry) if options[:unique] 96 | end 97 | end 98 | 99 | # Append content to an existing entry. This method will add a new entry 100 | # if one does not already exist. 101 | # 102 | # @param (see #add) 103 | def append(options = {}) 104 | if entry = find_entry_by_ip_address(options[:ip_address]) 105 | hosts = normalize(entry.hostname, entry.aliases, options[:hostname], options[:aliases]) 106 | entry.hostname = hosts.shift 107 | entry.aliases = hosts 108 | 109 | unless entry.comment && options[:comment] && entry.comment.include?(options[:comment]) 110 | entry.comment = normalize(entry.comment, options[:comment]).join(', ') 111 | end 112 | 113 | remove_existing_hostnames(entry) if options[:unique] 114 | else 115 | add(options) 116 | end 117 | end 118 | 119 | # Remove an entry by it's IP Address 120 | # 121 | # @param [String] ip_address 122 | # the IP Address of the entry to remove 123 | def remove(ip_address) 124 | if entry = find_entry_by_ip_address(ip_address) 125 | @entries.delete(entry) 126 | end 127 | end 128 | 129 | # Save the new hostsfile to the target machine. This method will only write the 130 | # hostsfile if the current version has changed. In other words, it is convergent. 131 | def save 132 | file = Chef::Resource::File.new(hostsfile_path, node.run_context) 133 | file.content(new_content) 134 | file.atomic_update false if docker_guest? 135 | file.run_action(:create) 136 | end 137 | 138 | # Determine if the content of the hostfile has changed by comparing sha 139 | # values of existing file and new content 140 | # 141 | # @return [Boolean] 142 | def content_changed? 143 | new_sha = OpenSSL::Digest::SHA512.hexdigest(new_content) 144 | new_sha != current_sha 145 | end 146 | 147 | # Find an entry by the given IP Address. 148 | # 149 | # @param [String] ip_address 150 | # the IP Address of the entry to find 151 | # @return [Entry, nil] 152 | # the corresponding entry object, or nil if it does not exist 153 | def find_entry_by_ip_address(ip_address) 154 | @entries.find do |entry| 155 | !entry.ip_address.nil? && entry.ip_address == ip_address 156 | end 157 | end 158 | 159 | # Determine if the current hostsfile contains the given resource. This 160 | # is really just a proxy to {find_resource_by_ip_address} / 161 | # 162 | # @param [Chef::Resource] resource 163 | # 164 | # @return [Boolean] 165 | def contains?(resource) 166 | !!find_entry_by_ip_address(resource.ip_address) 167 | end 168 | 169 | private 170 | 171 | # Determine if we are running inside a Docker container 172 | # 173 | # @return [Boolean] 174 | def docker_guest? 175 | node['virtualization'] && node['virtualization']['systems'] && 176 | node['virtualization']['systems']['docker'] && node['virtualization']['systems']['docker'] == 'guest' 177 | end 178 | 179 | # The path to the current hostsfile. 180 | # 181 | # @return [String] 182 | # the full path to the hostsfile, depending on the operating system 183 | # can also be overriden in the node attributes 184 | def hostsfile_path 185 | return @hostsfile_path if @hostsfile_path 186 | @hostsfile_path = node['hostsfile']['path'] || case node['platform_family'] 187 | when 'windows' 188 | "#{node['kernel']['os_info']['system_directory']}\\drivers\\etc\\hosts" 189 | else 190 | '/etc/hosts' 191 | end 192 | end 193 | 194 | # The header of the new hostsfile 195 | # 196 | # @return [Array] 197 | # an array of header comments 198 | def hostsfile_header 199 | lines = [] 200 | lines << '#' 201 | lines << '# This file is managed by Chef, using the hostsfile cookbook.' 202 | lines << '# Editing this file by hand is highly discouraged!' 203 | lines << '#' 204 | lines << '# Comments containing an @ sign should not be modified or else' 205 | lines << '# hostsfile will be unable to guarantee relative priority in' 206 | lines << '# future Chef runs!' 207 | lines << '#' 208 | lines << '' 209 | end 210 | 211 | # The content that will be written to the hostfile 212 | # 213 | # @return [String] 214 | # the full contents of the hostfile to be written 215 | def new_content 216 | entries = hostsfile_header 217 | entries += unique_entries.map(&:to_line) 218 | entries << '' 219 | entries.join("\n") 220 | end 221 | 222 | # The current sha of the system hostsfile. 223 | # 224 | # @return [String] 225 | # the sha of the current hostsfile 226 | def current_sha 227 | @current_sha ||= OpenSSL::Digest::SHA512.hexdigest(File.read(hostsfile_path)) 228 | end 229 | 230 | # Normalize the given list of elements into a single array with no nil 231 | # values and no duplicate values. 232 | # 233 | # @param [Object] things 234 | # 235 | # @return [Array] 236 | # a normalized array of things 237 | def normalize(*things) 238 | things.flatten.compact.uniq 239 | end 240 | 241 | # This is a crazy way of ensuring unique objects in an array using a Hash. 242 | # 243 | # @return [Array] 244 | # the sorted list of entires that are unique 245 | def unique_entries 246 | entries = Hash[*@entries.map { |entry| [entry.ip_address, entry] }.flatten].values 247 | entries.sort_by { |e| [-e.priority.to_i, e.hostname.to_s] } 248 | end 249 | 250 | # Takes /etc/hosts file contents and builds a flattened entries 251 | # array so that each IP address has only one line and multiple hostnames 252 | # are flattened into a list of aliases. 253 | # 254 | # @param [Array] contents 255 | # Array of lines from /etc/hosts file 256 | def collect_and_flatten(contents) 257 | contents.each do |line| 258 | entry = HostsFile::Entry.parse(line) 259 | next if entry.nil? 260 | 261 | append( 262 | ip_address: entry.ip_address, 263 | hostname: entry.hostname, 264 | aliases: entry.aliases, 265 | comment: entry.comment, 266 | priority: !entry.calculated_priority? && entry.priority 267 | ) 268 | end 269 | end 270 | 271 | # Removes duplicate hostnames in other files ensuring they are unique 272 | # 273 | # @param [Entry] entry 274 | # the entry to keep the hostname and aliases from 275 | # 276 | # @return [nil] 277 | def remove_existing_hostnames(entry) 278 | @entries.delete(entry) 279 | changed_hostnames = [entry.hostname, entry.aliases].flatten.uniq 280 | 281 | @entries = @entries.collect do |entry| 282 | entry.hostname = nil if changed_hostnames.include?(entry.hostname) 283 | entry.aliases = entry.aliases - changed_hostnames 284 | 285 | if entry.hostname.nil? 286 | if entry.aliases.empty? 287 | nil 288 | else 289 | entry.hostname = entry.aliases.shift 290 | entry 291 | end 292 | else 293 | entry 294 | end 295 | end.compact 296 | 297 | @entries << entry 298 | 299 | nil 300 | end 301 | end 302 | end 303 | -------------------------------------------------------------------------------- /libraries/matchers.rb: -------------------------------------------------------------------------------- 1 | if defined?(ChefSpec) 2 | def append_hostsfile_entry(resource_name) 3 | ChefSpec::Matchers::ResourceMatcher.new(:hostsfile_entry, :append, resource_name) 4 | end 5 | 6 | def create_hostsfile_entry(resource_name) 7 | ChefSpec::Matchers::ResourceMatcher.new(:hostsfile_entry, :create, resource_name) 8 | end 9 | 10 | def create_hostsfile_entry_if_missing(resource_name) 11 | ChefSpec::Matchers::ResourceMatcher.new(:hostsfile_entry, :create_if_missing, resource_name) 12 | end 13 | 14 | def remove_hostsfile_entry(resource_name) 15 | ChefSpec::Matchers::ResourceMatcher.new(:hostsfile_entry, :remove, resource_name) 16 | end 17 | 18 | def update_hostsfile_entry(resource_name) 19 | ChefSpec::Matchers::ResourceMatcher.new(:hostsfile_entry, :update, resource_name) 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /metadata.rb: -------------------------------------------------------------------------------- 1 | name 'hostsfile' 2 | maintainer 'Seth Vargo' 3 | maintainer_email 'sethvargo@gmail.com' 4 | license 'Apache-2.0' 5 | description 'Provides an resource for managing the /etc/hosts file' 6 | long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) 7 | version '3.0.1' 8 | issues_url 'https://github.com/customink-webops/hostsfile/issues' 9 | source_url 'https://github.com/customink-webops/hostsfile' 10 | chef_version '>= 12.7' if respond_to?(:chef_version) 11 | supports 'all' 12 | -------------------------------------------------------------------------------- /resources/entry.rb: -------------------------------------------------------------------------------- 1 | # 2 | # Author:: Seth Vargo 3 | # Cookbook:: hostsfile 4 | # Resource:: entry 5 | # 6 | # Copyright:: 2012-2013, Seth Vargo 7 | # Copyright:: 2012, CustomInk, LCC 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | # Required attributes 23 | property :ip_address, String, name_property: true 24 | property :hostname, String 25 | 26 | # Optional attributes 27 | property :aliases, Array 28 | property :comment, String 29 | property :priority, Integer 30 | property :unique, [TrueClass, FalseClass] 31 | 32 | # Creates a new hosts file entry. If an entry already exists, it will be 33 | # overwritten by this one. 34 | action :create do 35 | if hostsfile.contains?(new_resource) 36 | Chef::Log.debug "#{new_resource} already exists - overwriting." 37 | end 38 | 39 | hostsfile.add( 40 | ip_address: new_resource.ip_address, 41 | hostname: new_resource.hostname, 42 | aliases: new_resource.aliases, 43 | comment: new_resource.comment, 44 | priority: new_resource.priority, 45 | unique: new_resource.unique 46 | ) 47 | 48 | if hostsfile.content_changed? 49 | converge_by("Create #{new_resource}") { hostsfile.save } 50 | else 51 | Chef::Log.info "#{new_resource} content already matches - nothing to do." 52 | end 53 | end 54 | 55 | # Create a new hosts file entry, only if one does not already exist for 56 | # the given IP address. If one exists, this does nothing. 57 | action :create_if_missing do 58 | if hostsfile.contains?(new_resource) 59 | Chef::Log.info "#{new_resource} already exists - skipping create_if_missing." 60 | else 61 | converge_by("Create #{new_resource} if missing") do 62 | hostsfile.add( 63 | ip_address: new_resource.ip_address, 64 | hostname: new_resource.hostname, 65 | aliases: new_resource.aliases, 66 | comment: new_resource.comment, 67 | priority: new_resource.priority, 68 | unique: new_resource.unique 69 | ) 70 | hostsfile.save 71 | end 72 | end 73 | end 74 | 75 | # Appends the given data to an existing entry. If an entry does not exist, 76 | # one will be created 77 | action :append do 78 | unless hostsfile.contains?(new_resource) 79 | Chef::Log.info "#{new_resource} does not exist - creating instead." 80 | end 81 | 82 | hostsfile.append( 83 | ip_address: new_resource.ip_address, 84 | hostname: new_resource.hostname, 85 | aliases: new_resource.aliases, 86 | comment: new_resource.comment, 87 | priority: new_resource.priority, 88 | unique: new_resource.unique 89 | ) 90 | 91 | if hostsfile.content_changed? 92 | converge_by("Append #{new_resource}") { hostsfile.save } 93 | else 94 | Chef::Log.info "#{new_resource} content already matches - nothing to do." 95 | end 96 | end 97 | 98 | # Updates the given hosts file entry. Does nothing if the entry does not 99 | # exist. 100 | action :update do 101 | if hostsfile.contains?(new_resource) 102 | 103 | hostsfile.update( 104 | ip_address: new_resource.ip_address, 105 | hostname: new_resource.hostname, 106 | aliases: new_resource.aliases, 107 | comment: new_resource.comment, 108 | priority: new_resource.priority, 109 | unique: new_resource.unique 110 | ) 111 | 112 | if hostsfile.content_changed? 113 | converge_by("Update #{new_resource}") { hostsfile.save } 114 | else 115 | Chef::Log.info "#{new_resource} content already matches - nothing to do." 116 | end 117 | else 118 | Chef::Log.info "#{new_resource} does not exist - skipping update." 119 | end 120 | end 121 | 122 | # Removes an entry from the hosts file. Does nothing if the entry does 123 | # not exist. 124 | action :remove do 125 | if hostsfile.contains?(new_resource) 126 | converge_by("Remove #{new_resource}") do 127 | hostsfile.remove(new_resource.ip_address) 128 | hostsfile.save 129 | end 130 | else 131 | Chef::Log.info "#{new_resource} does not exist - skipping remove." 132 | end 133 | end 134 | 135 | action_class do 136 | # The hostsfile object 137 | # 138 | # @return [Manipulator] 139 | # the manipulator for this hostsfile 140 | def hostsfile 141 | @hostsfile ||= HostsFile::Manipulator.new(node) 142 | end 143 | end 144 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require 'chefspec' 2 | require_relative '../libraries/entry' 3 | require_relative '../libraries/manipulator' 4 | 5 | RSpec.configure do |c| 6 | c.filter_run(focus: true) 7 | c.run_all_when_everything_filtered = true 8 | end 9 | -------------------------------------------------------------------------------- /spec/unit/entry_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe HostsFile::Entry do 4 | describe '.parse' do 5 | it 'returns nil for invalid lines' do 6 | expect(HostsFile::Entry.parse(' ')).to be_nil 7 | end 8 | 9 | context '' do 10 | let(:entry) { double('entry') } 11 | 12 | before do 13 | allow(HostsFile::Entry).to receive(:new).and_return(entry) 14 | end 15 | 16 | it 'parses just an ip_address and hostname' do 17 | expect(HostsFile::Entry).to receive(:new).with(ip_address: '1.2.3.4', hostname: 'www.example.com', aliases: [], comment: nil, priority: nil) 18 | HostsFile::Entry.parse('1.2.3.4 www.example.com') 19 | end 20 | 21 | it 'parses aliases' do 22 | expect(HostsFile::Entry).to receive(:new).with(ip_address: '1.2.3.4', hostname: 'www.example.com', aliases: %w(foo bar), comment: nil, priority: nil) 23 | HostsFile::Entry.parse('1.2.3.4 www.example.com foo bar') 24 | end 25 | 26 | it 'parses a comment' do 27 | expect(HostsFile::Entry).to receive(:new).with(ip_address: '1.2.3.4', hostname: 'www.example.com', aliases: [], comment: 'This is a comment!', priority: nil) 28 | HostsFile::Entry.parse('1.2.3.4 www.example.com # This is a comment!') 29 | end 30 | 31 | it 'parses aliases and comments' do 32 | expect(HostsFile::Entry).to receive(:new).with(ip_address: '1.2.3.4', hostname: 'www.example.com', aliases: %w(foo bar), comment: 'This is a comment!', priority: nil) 33 | HostsFile::Entry.parse('1.2.3.4 www.example.com foo bar # This is a comment!') 34 | end 35 | 36 | it 'parses priorities with comments' do 37 | expect(HostsFile::Entry).to receive(:new).with(ip_address: '1.2.3.4', hostname: 'www.example.com', aliases: [], comment: 'This is a comment!', priority: '40') 38 | HostsFile::Entry.parse('1.2.3.4 www.example.com # This is a comment! @40') 39 | end 40 | 41 | it 'parses priorities' do 42 | expect(HostsFile::Entry).to receive(:new).with(ip_address: '1.2.3.4', hostname: 'www.example.com', aliases: [], comment: nil, priority: '40') 43 | HostsFile::Entry.parse('1.2.3.4 www.example.com # @40') 44 | end 45 | end 46 | end 47 | 48 | describe '.initialize' do 49 | subject { HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com', aliases: %w(foo bar), comment: 'This is a comment!', priority: 100) } 50 | 51 | it 'raises an exception if :ip_address is missing' do 52 | expect do 53 | HostsFile::Entry.new(hostname: 'www.example.com') 54 | end.to raise_error(ArgumentError) 55 | end 56 | 57 | it 'raises an exception if :hostname is missing' do 58 | expect do 59 | HostsFile::Entry.new(ip_address: '2.3.4.5') 60 | end.to raise_error(ArgumentError) 61 | end 62 | 63 | it 'sets the @ip_address instance variable' do 64 | expect(subject.ip_address).to be_a(IPAddr) 65 | expect(subject.ip_address).to eq(IPAddr.new('2.3.4.5')) 66 | end 67 | 68 | it 'removes IPV6 scope pieces' do 69 | instance = HostsFile::Entry.new(ip_address: 'fe80::1%lo0', hostname: 'www.example.com') 70 | expect(instance.ip_address).to eq(IPAddr.new('fe80::1')) 71 | end 72 | 73 | it 'sets the @hostname instance variable' do 74 | expect(subject.hostname).to eq('www.example.com') 75 | end 76 | 77 | it 'sets the @aliases instance variable' do 78 | expect(subject.aliases).to be_a(Array) 79 | expect(subject.aliases).to eq(%w(foo bar)) 80 | end 81 | 82 | it 'sets the @comment instance variable' do 83 | expect(subject.comment).to eq('This is a comment!') 84 | end 85 | 86 | it 'sets the @priority instance variable' do 87 | expect(subject.priority).to eq(100) 88 | end 89 | 90 | context 'with no options' do 91 | subject { HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com') } 92 | 93 | it 'sets @aliases to an empty array' do 94 | expect(subject.aliases).to be_empty 95 | end 96 | 97 | it 'sets @comment to nil' do 98 | expect(subject.comment).to be_nil 99 | end 100 | 101 | it 'calls calculated_priority for @priority' do 102 | expect_any_instance_of(HostsFile::Entry).to receive(:calculated_priority) 103 | HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com') 104 | end 105 | end 106 | 107 | context 'with aliases as a string' do 108 | subject { HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com', aliases: 'foo') } 109 | 110 | it 'sets the @aliases to be an Array' do 111 | expect(subject.aliases).to be_a(Array) 112 | expect(subject.aliases).to eq(['foo']) 113 | end 114 | end 115 | end 116 | 117 | describe '#priority=' do 118 | subject { HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com') } 119 | 120 | it 'sets the new priority' do 121 | subject.priority = 50 122 | expect(subject.priority).to eq(50) 123 | end 124 | 125 | it 'sets @calculated_priority to false' do 126 | subject.priority = 50 127 | expect(subject.instance_variable_get(:@calculated_priority)).to be_falsey 128 | end 129 | end 130 | 131 | describe '#to_line' do 132 | context 'without a comment' do 133 | subject { HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com') } 134 | 135 | it 'prints without aliases' do 136 | expect(subject.to_line).to eq("2.3.4.5\twww.example.com") 137 | end 138 | 139 | it 'prints with aliases' do 140 | subject.aliases << 'foo' 141 | expect(subject.to_line).to eq("2.3.4.5\twww.example.com foo") 142 | end 143 | 144 | it 'prints out the priority' do 145 | subject.priority = 10 146 | expect(subject.to_line).to eq("2.3.4.5\twww.example.com\t# @10") 147 | end 148 | end 149 | 150 | context 'with a comment' do 151 | subject { HostsFile::Entry.new(ip_address: '2.3.4.5', hostname: 'www.example.com', comment: 'This is a comment!') } 152 | 153 | it 'prints without aliases' do 154 | expect(subject.to_line).to eq("2.3.4.5\twww.example.com\t# This is a comment!") 155 | end 156 | 157 | it 'prints with aliases' do 158 | subject.aliases << 'foo' 159 | expect(subject.to_line).to eq("2.3.4.5\twww.example.com foo\t# This is a comment!") 160 | end 161 | 162 | it 'prints out the priority' do 163 | subject.priority = 10 164 | expect(subject.to_line).to eq("2.3.4.5\twww.example.com\t# This is a comment! @10") 165 | end 166 | end 167 | end 168 | end 169 | -------------------------------------------------------------------------------- /spec/unit/manipulator_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe HostsFile::Manipulator do 4 | let(:node) do 5 | { 'hostsfile' => { 'path' => nil } } 6 | end 7 | 8 | let(:lines) do 9 | [ 10 | '127.0.0.1 localhost', 11 | '::1 localhost6', 12 | '1.2.3.4 example.com', 13 | '4.5.6.7 foo.example.com', 14 | ] 15 | end 16 | 17 | let(:entries) do 18 | [ 19 | HostsFile::Entry.new(ip_address: '127.0.0.1', hostname: 'localhost', to_line: '127.0.0.1 localhost', priority: 10), 20 | HostsFile::Entry.new(ip_address: '::1', hostname: 'localhost6', to_line: '::1 localhost6', priority: 11), 21 | HostsFile::Entry.new(ip_address: '1.2.3.4', hostname: 'example.com', to_line: '1.2.3.4 example.com', priority: 20), 22 | HostsFile::Entry.new(ip_address: '4.5.6.7', hostname: 'foo.example.com', to_line: '4.5.6.7 foo.example.com', priority: 30), 23 | ] 24 | end 25 | 26 | let(:manipulator) { HostsFile::Manipulator.new(node) } 27 | let(:header) { manipulator.hostsfile_header } 28 | 29 | before do 30 | allow(File).to receive(:exist?).and_call_original 31 | allow(File).to receive(:readlines).and_call_original 32 | allow(File).to receive(:exist?).with('/etc/hosts').and_return(true) 33 | allow(File).to receive(:readlines).with('/etc/hosts').and_return(lines) 34 | manipulator.instance_variable_set(:@entries, entries) 35 | end 36 | 37 | describe '.initialize' do 38 | it 'saves the node hash to an instance variable' do 39 | manipulator = HostsFile::Manipulator.new(node) 40 | expect(manipulator.node).to be(node) 41 | end 42 | 43 | it 'raises a fatal error if the hostsfile does not exist' do 44 | allow(File).to receive(:exist?).with('/etc/hosts').and_return(false) 45 | expect { HostsFile::Manipulator.new(node) }.to raise_error(RuntimeError) 46 | end 47 | 48 | it 'sends the line to be parsed by the Entry class' do 49 | lines.each { |l| allow(HostsFile::Entry).to receive(:parse).with(l) } 50 | HostsFile::Manipulator.new(node) 51 | end 52 | end 53 | 54 | describe '#ip_addresses' do 55 | it 'returns a list of all the IP Addresses' do 56 | expect(manipulator.ip_addresses).to eq(entries.map(&:ip_address)) 57 | end 58 | end 59 | 60 | describe '#add' do 61 | let(:entry) { double('entry') } 62 | 63 | let(:options) { { ip_address: '1.2.3.4', hostname: 'example.com', aliases: nil, comment: 'Some comment', priority: 5 } } 64 | 65 | before { allow(HostsFile::Entry).to receive(:new).and_return(entry) } 66 | 67 | it 'creates a new entry object' do 68 | allow(HostsFile::Entry).to receive(:new).with(options) 69 | manipulator.add(options) 70 | end 71 | 72 | it 'pushes the new entry onto the collection' do 73 | manipulator.add(options) 74 | expect(manipulator.instance_variable_get(:@entries)).to include(entry) 75 | end 76 | end 77 | 78 | describe '#update' do 79 | context 'when the entry does not exist' do 80 | before do 81 | allow(manipulator).to receive(:find_entry_by_ip_address) 82 | .with(any_args) 83 | .and_return(nil) 84 | end 85 | 86 | it 'does nothing' do 87 | manipulator.update(ip_address: '5.4.3.2', hostname: 'seth.com') 88 | expect(manipulator.instance_variable_get(:@entries)).to eq(entries) 89 | end 90 | end 91 | 92 | context 'with the entry does exist' do 93 | let(:entry) { double('entry', :hostname= => nil, :aliases= => nil, :comment= => nil, :priority= => nil) } 94 | 95 | before do 96 | allow(manipulator).to receive(:find_entry_by_ip_address) 97 | .with(any_args) 98 | .and_return(entry) 99 | end 100 | 101 | it 'updates the hostname' do 102 | allow(entry).to receive(:hostname=).with('seth.com') 103 | manipulator.update(ip_address: '1.2.3.4', hostname: 'seth.com') 104 | end 105 | end 106 | end 107 | 108 | describe '#append' do 109 | let(:options) { { ip_address: '1.2.3.4', hostname: 'example.com', aliases: nil, comment: 'Some comment', priority: 5 } } 110 | 111 | context 'when the record exists' do 112 | let(:entry) { double('entry', options.merge(:aliases= => nil, :comment= => nil)) } 113 | 114 | before do 115 | allow(manipulator).to receive(:find_entry_by_ip_address) 116 | .with(any_args) 117 | .and_return(entry) 118 | end 119 | 120 | it 'updates the hostname' do 121 | allow(entry).to receive(:hostname=).with('example.com') 122 | manipulator.append(options) 123 | end 124 | 125 | it 'updates the aliases' do 126 | allow(entry).to receive(:aliases=).with(['www.example.com']) 127 | allow(entry).to receive(:hostname=).with('example.com') 128 | manipulator.append(options.merge(aliases: 'www.example.com')) 129 | end 130 | 131 | it 'updates the comment' do 132 | allow(entry).to receive(:comment=).with('Some comment, This is a new comment!') 133 | allow(entry).to receive(:hostname=).with('example.com') 134 | manipulator.append(options.merge(comment: 'This is a new comment!')) 135 | end 136 | end 137 | 138 | context 'when the record does not exist' do 139 | before do 140 | allow(manipulator).to receive(:find_entry_by_ip_address) 141 | .with(any_args) 142 | .and_return(nil) 143 | allow(manipulator).to receive(:add) 144 | end 145 | 146 | it 'delegates to #add' do 147 | allow(manipulator).to receive(:add).with(options).once 148 | manipulator.append(options) 149 | end 150 | end 151 | end 152 | 153 | describe '#remove' do 154 | context 'when the entry does not exist' do 155 | before do 156 | allow(manipulator).to receive(:find_entry_by_ip_address).with(any_args).and_return(nil) 157 | end 158 | 159 | it 'does nothing' do 160 | manipulator.remove('5.4.3.2') 161 | expect(manipulator.instance_variable_get(:@entries)).to eq(entries) 162 | end 163 | end 164 | 165 | context 'with the entry does exist' do 166 | let(:entry) { entries[0] } 167 | 168 | before do 169 | allow(manipulator).to receive(:find_entry_by_ip_address) 170 | .with(any_args) 171 | .and_return(entry) 172 | end 173 | 174 | it 'removes the entry' do 175 | expect(manipulator.instance_variable_get(:@entries)).to include(entry) 176 | manipulator.remove('5.4.3.2') 177 | expect(manipulator.instance_variable_get(:@entries)).to_not include(entry) 178 | end 179 | end 180 | end 181 | 182 | describe '#new_content' do 183 | let(:entries_string) { entries.map(&:to_line).join("\n").concat("\n") } 184 | 185 | before do 186 | manipulator.class.send(:public, :new_content) 187 | manipulator.class.send(:public, :hostsfile_header) 188 | allow(manipulator).to receive(:unique_entries).and_return(entries) 189 | end 190 | 191 | it 'starts with comment header' do 192 | expect(manipulator.new_content).to start_with(header.join("\n").concat("\n")) 193 | end 194 | 195 | it 'ends with all unique entry lines' do 196 | expect(manipulator.new_content).to end_with(entries_string) 197 | end 198 | end 199 | 200 | describe '#content_changed?' do 201 | let(:current_content) do 202 | (header << entries.map(&:to_line) << '').flatten.join("\n") 203 | end 204 | 205 | before do 206 | allow(File).to receive(:read).and_return(current_content) 207 | allow(manipulator).to receive(:unique_entries).and_return(entries) 208 | end 209 | 210 | context 'when content has not changed' do 211 | it 'returns false' do 212 | expect(manipulator.content_changed?).to be_falsey 213 | end 214 | end 215 | 216 | context 'when content has changed' do 217 | it 'returns true' do 218 | manipulator.remove('4.5.6.7') 219 | expect(manipulator.content_changed?).to be_truthy 220 | end 221 | end 222 | end 223 | 224 | describe '#hostsfile_header' do 225 | it 'is an array' do 226 | expect(manipulator.hostsfile_header).to be_an(Array) 227 | end 228 | 229 | it 'each line is blank or starts with comment' do 230 | manipulator.hostsfile_header.each do |item| 231 | expect(item).to match(/^(\s*|#.*)/) 232 | end 233 | end 234 | end 235 | 236 | describe '#save' do 237 | let(:file) { double('file', content: nil, run_action: nil) } 238 | 239 | before do 240 | allow(Chef::Resource::File).to receive(:new).and_return(file) 241 | allow(manipulator).to receive(:unique_entries).and_return(entries) 242 | allow(node).to receive(:run_context) 243 | end 244 | 245 | it 'writes out the new file' do 246 | expect(Chef::Resource::File).to receive(:new).with('/etc/hosts', nil) 247 | expect(file).to receive(:content).once 248 | expect(file).to receive(:run_action).with(:create).once 249 | manipulator.save 250 | end 251 | end 252 | 253 | describe '#find_entry_by_ip_address' do 254 | it 'finds the associated entry' do 255 | expect(manipulator.find_entry_by_ip_address('127.0.0.1')).to eq(entries[0]) 256 | expect(manipulator.find_entry_by_ip_address('::1')).to eq(entries[1]) 257 | expect(manipulator.find_entry_by_ip_address('1.2.3.4')).to eq(entries[2]) 258 | expect(manipulator.find_entry_by_ip_address('4.5.6.7')).to eq(entries[3]) 259 | end 260 | 261 | it 'returns nil if the entry does not exist' do 262 | expect(manipulator.find_entry_by_ip_address('77.77.77.77')).to be_nil 263 | end 264 | end 265 | 266 | describe '#hostsfile_path' do 267 | before do 268 | manipulator.class.send(:public, :hostsfile_path) 269 | allow(File).to receive(:exists?).and_return(true) 270 | end 271 | 272 | context 'with no node attribute specified' do 273 | it 'returns /etc/hosts on a *nix machine' do 274 | expect(manipulator.hostsfile_path).to eq('/etc/hosts') 275 | end 276 | it 'returns C:\Windows\system32\drivers\etc\hosts on a Windows machine' do 277 | windows_attributes = node.merge('platform_family' => 'windows', 'kernel' => { 'os_info' => { 'system_directory' => 'C:\Windows\system32' } }) 278 | windows_path = 'C:\Windows\system32\drivers\etc\hosts' 279 | allow(File).to receive(:exist?).with(windows_path).and_return(true) 280 | allow(File).to receive(:readlines).with(windows_path).and_return(lines) 281 | expect(HostsFile::Manipulator.new(windows_attributes).hostsfile_path).to eq('C:\Windows\system32\drivers\etc\hosts') 282 | end 283 | end 284 | 285 | context 'with a custom hostsfile node attribute' do 286 | it 'returns the custom path' do 287 | custom_path = '/custom/path' 288 | allow(File).to receive(:exist?).with(custom_path).and_return(true) 289 | allow(File).to receive(:readlines).with(custom_path).and_return(lines) 290 | expect(HostsFile::Manipulator.new(node.merge('hostsfile' => { 'path' => custom_path })).hostsfile_path).to eq(custom_path) 291 | end 292 | end 293 | end 294 | 295 | describe '#remove_existing_hostnames' do 296 | before { manipulator.class.send(:public, :remove_existing_hostnames) } 297 | 298 | context 'with no duplicates' do 299 | it 'does not change anything' do 300 | entry = HostsFile::Entry.new(ip_address: '7.8.9.10', hostname: 'new.example.com') 301 | entries << entry 302 | 303 | expect do 304 | manipulator.remove_existing_hostnames(entry) 305 | end.to_not change(manipulator, :entries) 306 | end 307 | end 308 | 309 | context 'with duplicate hostnames' do 310 | it 'removes the duplicate hostnames' do 311 | entry = HostsFile::Entry.new(ip_address: '7.8.9.10', hostname: 'example.com') 312 | entries << entry 313 | 314 | manipulator.remove_existing_hostnames(entry) 315 | expect(manipulator.entries).to_not include(entries.find { |e| e.hostname == 'example.com' }) 316 | end 317 | end 318 | 319 | context 'with duplicate aliases' do 320 | it 'removes the duplicate aliases' do 321 | entry = HostsFile::Entry.new(ip_address: '7.8.9.10', hostname: 'bar.example.com') 322 | entries << entry 323 | entries[1].aliases = ['bar.example.com'] 324 | 325 | manipulator.remove_existing_hostnames(entry) 326 | expect(manipulator.entries).to include(entries[1]) 327 | expect(manipulator.entries[1].aliases).to be_empty 328 | end 329 | end 330 | end 331 | end 332 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/metadata.rb: -------------------------------------------------------------------------------- 1 | name 'test' 2 | version '1.0.0' 3 | license 'Apache-2.0' 4 | depends 'hostsfile' 5 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/append.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | action :append 4 | end 5 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/append_existing.rb: -------------------------------------------------------------------------------- 1 | # We can guarantee that 127.0.0.1 exists on every system... 2 | hostsfile_entry '127.0.0.1' do 3 | hostname 'www.example.com' 4 | action :append 5 | end 6 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/create.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | action :create 4 | end 5 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/create_if_missing.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | action :create_if_missing 4 | end 5 | 6 | hostsfile_entry '2.3.4.5' do 7 | hostname 'domain' 8 | action :create_if_missing 9 | end 10 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/default.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | end 4 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/options.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | aliases %w(foo bar) 4 | comment 'This is a comment!' 5 | priority 100 6 | end 7 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/remove.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | action :remove 4 | end 5 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/unique.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '1.2.3.4' do 2 | hostname 'example.com' 3 | aliases ['www.example.com'] 4 | end 5 | 6 | hostsfile_entry '2.3.4.5' do 7 | hostname 'www.example.com' 8 | unique true 9 | end 10 | -------------------------------------------------------------------------------- /test/fixtures/cookbooks/test/recipes/update.rb: -------------------------------------------------------------------------------- 1 | hostsfile_entry '2.3.4.5' do 2 | hostname 'www.example.com' 3 | action :update 4 | end 5 | -------------------------------------------------------------------------------- /test/integration/append/serverspec/append_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - append' do 5 | it 'creates a new entry if one does not already exist' do 6 | expect(file('/etc/hosts')).to contain('2.3.4.5[[:space:]]www.example.com') 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/integration/append_existing/serverspec/append_existing_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - append_existing' do 5 | it 'creates a new entry if one does not already exist' do 6 | expect(file('/etc/hosts')).to contain('127.0.0.1.*www.example.com') 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/integration/create/serverspec/create_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - create' do 5 | it 'creates a new entry' do 6 | expect(file('/etc/hosts')).to contain('2.3.4.5[[:space:]]www.example.com') 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/integration/create_if_missing/serverspec/create_if_missing_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - create_if_missing' do 5 | it 'creates a new entry if one is missing' do 6 | expect(file('/etc/hosts')).to contain('2.3.4.5[[:space:]]www.example.com') 7 | end 8 | 9 | it 'does not create an entry if one exists' do 10 | expect(file('/etc/hosts')).to_not contain('domain') 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /test/integration/default/serverspec/default_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - default' do 5 | it 'creates a new entry' do 6 | expect(file('/etc/hosts')).to contain('2.3.4.5[[:space:]]www.example.com') 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /test/integration/options/serverspec/options_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - options' do 5 | it 'appends all options to the entry' do 6 | expect(file('/etc/hosts')).to contain('2.3.4.5') 7 | expect(file('/etc/hosts')).to contain('www.example.com') 8 | expect(file('/etc/hosts')).to contain('foo') 9 | expect(file('/etc/hosts')).to contain('bar') 10 | expect(file('/etc/hosts')).to contain('comment') 11 | expect(file('/etc/hosts')).to contain('@100') 12 | end 13 | end 14 | -------------------------------------------------------------------------------- /test/integration/unique/serverspec/unique_spec.rb: -------------------------------------------------------------------------------- 1 | require 'serverspec' 2 | set :backend, :exec 3 | 4 | describe 'hostsfile_entry - unique' do 5 | it 'removes existing hostnames when unique is specified' do 6 | expect(file('/etc/hosts')).to contain('1.2.3.4[[:space:]]example.com') 7 | expect(file('/etc/hosts')).to contain('2.3.4.5[[:space:]]www.example.com') 8 | 9 | expect(file('/etc/hosts')).to_not contain('1.2.3.4[[:space:]]example.com[[:space:]]www.example.com') 10 | end 11 | end 12 | --------------------------------------------------------------------------------