├── LICENSE └── README.md /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Thomas Stringer 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ansible Development by Example 2 | 3 | - [Why?](#why) 4 | - [What is this?](#what-is-this) 5 | - [Environment setup](#environment-setup) 6 | - [New module development](#new-module-development) 7 | - [Local/direct module testing](#localdirect-module-testing) 8 | - [Playbook module testing](#playbook-module-testing) 9 | - [Debugging (local)](#debugging-local) 10 | - [Debugging (remote)](#debugging-remote) 11 | - [Unit testing](#unit-testing) 12 | - Integration testing (coming soon) 13 | - [Communication and development support](#communication-and-development-support) 14 | - [Credit](#credit) 15 | 16 | ### Why? 17 | 18 | Ansible is an awesome tool for configuration management. It is also a highly utilized one, and there are so many ways to contribute as a community. 19 | 20 | ### What is this? 21 | 22 | There is no doubt that Ansible is a complex tool, with lots of inner-workings, yet it is easy to work with as an end user. But on the other end of that, contributing to Ansible with code can sometimes be a daunting task. 23 | 24 | This documentation is a way to show step-by-step how to develop Ansible modules, both new module development as well as bug fixes and debugging. 25 | 26 | # Environment setup 27 | 28 | 1. Clone the Ansible repository: `$ git clone https://github.com/ansible/ansible.git` 29 | 1. Change directory into the repository root dir: `$ cd ansible` 30 | 1. Create a virtual environment: `$ python3 -m venv venv` (or for Python 2 `$ virtualenv venv`. Note, this requires you to install the virtualenv package: `$ pip install virtualenv`) 31 | 1. Activate the virtual environment: `$ . venv/bin/activate` 32 | 1. Install development requirements: `$ pip install -r requirements.txt` 33 | 1. Run the environment setup script for each new dev shell process: `$ . hacking/env-setup` 34 | 35 | :zap: After the initial setup above, every time you are ready to start developing Ansible you should be able to just run the following from the root of the Ansible repo: `$ . venv/bin/activate && . hacking/env-setup` 36 | 37 | :bulb: Starting new development now? Fixing a bug? Create a new branch: `$ git checkout -b my-new-branch`. If you are planning on contributing back to the main Ansible repostiry, fork the Ansible repository into your own GitHub account and developing against your new non-devel branch in your fork. When you believe you have a good working code change, submit a pull request to the Ansible repository. 38 | 39 | :bulb: :bulb: Submitting a new module to the upstream Ansible repo? Run through sanity checks first: `$ ansible-test sanity -v --docker --python 2.7 MODULE_NAME` (this requires docker to be installed and running. If you'd rather not use a container for this you can choose to use `--tox` instead of `--docker`) 40 | 41 | # New module development 42 | 43 | If you are creating a new module that doesn't exist, you would start working on a whole new file. Here is an example: 44 | 45 | - Navigate to the directory that you want to develop your new module in. E.g. `$ cd lib/ansible/modules/cloud/azure/` 46 | - Create your new module file: `$ touch my_new_test_module.py` 47 | - Paste this simple into the new module file: (explanation in comments) 48 | ```python 49 | #!/usr/bin/python 50 | 51 | ANSIBLE_METADATA = { 52 | 'metadata_version': '1.0', 53 | 'status': ['preview'], 54 | 'supported_by': 'curated' 55 | } 56 | 57 | DOCUMENTATION = ''' 58 | --- 59 | module: my_sample_module 60 | 61 | short_description: This is my sample module 62 | 63 | version_added: "2.4" 64 | 65 | description: 66 | - "This is my longer description explaining my sample module" 67 | 68 | options: 69 | name: 70 | description: 71 | - This is the message to send to the sample module 72 | required: true 73 | new: 74 | description: 75 | - Control to demo if the result of this module is changed or not 76 | required: false 77 | 78 | extends_documentation_fragment 79 | - azure 80 | 81 | author: 82 | - Your Name (@yourhandle) 83 | ''' 84 | 85 | EXAMPLES = ''' 86 | # Pass in a message 87 | - name: Test with a message 88 | my_new_test_module: 89 | name: hello world 90 | 91 | # pass in a message and have changed true 92 | - name: Test with a message and changed output 93 | my_new_test_module: 94 | name: hello world 95 | new: true 96 | 97 | # fail the module 98 | - name: Test failure of the module 99 | my_new_test_module: 100 | name: fail me 101 | ''' 102 | 103 | RETURN = ''' 104 | original_message: 105 | description: The original name param that was passed in 106 | type: str 107 | message: 108 | description: The output message that the sample module generates 109 | ''' 110 | 111 | from ansible.module_utils.basic import AnsibleModule 112 | 113 | def run_module(): 114 | # define the available arguments/parameters that a user can pass to 115 | # the module 116 | module_args = dict( 117 | name=dict(type='str', required=True), 118 | new=dict(type='bool', required=False, default=False) 119 | ) 120 | 121 | # seed the result dict in the object 122 | # we primarily care about changed and state 123 | # change is if this module effectively modified the target 124 | # state will include any data that you want your module to pass back 125 | # for consumption, for example, in a subsequent task 126 | result = dict( 127 | changed=False, 128 | original_message='', 129 | message='' 130 | ) 131 | 132 | # the AnsibleModule object will be our abstraction working with Ansible 133 | # this includes instantiation, a couple of common attr would be the 134 | # args/params passed to the execution, as well as if the module 135 | # supports check mode 136 | module = AnsibleModule( 137 | argument_spec=module_args, 138 | supports_check_mode=True 139 | ) 140 | 141 | # if the user is working with this module in only check mode we do not 142 | # want to make any changes to the environment, just return the current 143 | # state with no modifications 144 | if module.check_mode: 145 | return result 146 | 147 | # manipulate or modify the state as needed (this is going to be the 148 | # part where your module will do what it needs to do) 149 | result['original_message'] = module.params['name'] 150 | result['message'] = 'goodbye' 151 | 152 | # use whatever logic you need to determine whether or not this module 153 | # made any modifications to your target 154 | if module.params['new']: 155 | result['changed'] = True 156 | 157 | # during the execution of the module, if there is an exception or a 158 | # conditional state that effectively causes a failure, run 159 | # AnsibleModule.fail_json() to pass in the message and the result 160 | if module.params['name'] == 'fail me': 161 | module.fail_json(msg='You requested this to fail', **result) 162 | 163 | # in the event of a successful module execution, you will want to 164 | # simple AnsibleModule.exit_json(), passing the key/value results 165 | module.exit_json(**result) 166 | 167 | def main(): 168 | run_module() 169 | 170 | if __name__ == '__main__': 171 | main() 172 | ``` 173 | 174 | # Local/direct module testing 175 | 176 | You may want to test the module on the local machine without targeting a remote host. This is a great way to quickly and easily debug a module that can run locally. 177 | 178 | - Create an arguments file in `/tmp/args.json` with the following content: (explanation below) 179 | ```json 180 | { 181 | "ANSIBLE_MODULE_ARGS": { 182 | "name": "hello", 183 | "new": true 184 | } 185 | } 186 | ``` 187 | - If you are using a virtual environment (highly recommended for development) activate it: `$ . venv/bin/activate` 188 | - Setup the environment for development: `$ . hacking/env-setup` 189 | - Run your test module locally and directly: `$ python ./my_new_test_module.py /tmp/args.json` 190 | 191 | This should be working output that resembles something like the following: 192 | 193 | ``` 194 | {"changed": true, "state": {"original_message": "hello", "new_message": "goodbye"}, "invocation": {"module_args": {"name": "hello", "new": true}}} 195 | ``` 196 | 197 | :bulb: The arguments file is just a basic json config file that you can use to pass the module your parameters to run the module it 198 | 199 | # Playbook module testing 200 | 201 | If you want to test your new module, you can now consume it with an Ansible playbook. 202 | 203 | - Create a playbook in any directory: `$ touch testmod.yml` 204 | - Add the following to the new playbook file 205 | ```yaml 206 | --- 207 | - name: test my new module 208 | connection: local 209 | hosts: localhost 210 | 211 | tasks: 212 | - name: run the new module 213 | my_new_test_module: 214 | name: 'hello' 215 | new: true 216 | register: testout 217 | 218 | - name: dump test output 219 | debug: 220 | msg: '{{ testout }}' 221 | ``` 222 | - Run the playbook and analyze the output: `$ ansible-playbook ./testmod.yml` 223 | 224 | # Debugging (local) 225 | 226 | If you want to break into a module and step through with the debugger, locally running the module you can do: 227 | 228 | 1. Set a breakpoint in the module: `import pdb; pdb.set_trace()` 229 | 1. Run the module on the local machine: `$ python -m pdb ./my_new_test_module.py ./args.json` 230 | 231 | # Debugging (remote) 232 | 233 | In the event you want to debug a module that is running on a remote target (i.e. not localhost), one way to do this is the following: 234 | 235 | 1. On your controller machine (running Ansible) set `ANSIBLE_KEEP_REMOTE_FILES=1` (this tells Ansible to retain the modules it sends to the remote machine instead of removing them) 236 | 1. Run your playbook targetting the remote machine and specify `-vvvv` (the verbose output will show you many things, including the remote location that Ansible uses for the modules) 237 | 1. Take note of the remote path Ansible used on the remote host 238 | 1. SSH into the remote target after the completion of the playbook 239 | 1. Navigate to the directory (most likely it is going to be your ansible remote user defined or implied from the playbook: `~/.ansible/tmp/ansible-tmp-...`) 240 | 1. Here you should see the module that you executed from your Ansible controller, but this is the zipped file that Ansible sent to the remote host. You can run this by specifying `python my_test_module.py` (not necessary) 241 | 1. To debug, though, we will want to extra this zip out to the original module format: `python my_test_module.py explode` (Ansible will expand the module into `./debug-dir`) 242 | 1. Navigate to `./debug-dir` (notice that unzipping has caused the generation of `ansible_module_my_test_module.py`) 243 | 1. Modify or set a breakpoint in the unzipped module 244 | 1. Ensure that the unzipped module is executable: `$ chmod 755 ansible_module_my_test_module.py` 245 | 1. Run the unzipped module directly passing the args file: `$ ./ansible_module_my_test_module.py args` (args is the file that contains the params that were originally passed. Good for repro and debugging) 246 | 247 | # Unit testing 248 | 249 | Unit tests for modules will be appropriately located in `./test/units/modules`. You must first setup your testing environment. In my case, I'm using Python 3.5. 250 | 251 | - Install the requirements (outside of your virtual environment): `$ pip3 install -r ./test/runner/requirements/units.txt` 252 | - To run all tests do the following: `$ ansible-test units --python 3.5` (you must run `. hacking/env-setup` prior to this) 253 | 254 | :bulb: Ansible uses pytest for unit testing 255 | 256 | To run pytest against a single test module, you can do the following (provide the path to the test module appropriately): 257 | 258 | ``` 259 | $ pytest -r a --cov=. --cov-report=html --fulltrace --color yes test/units/modules/.../test_my_new_test_module.py 260 | ``` 261 | 262 | # Communication and development support 263 | 264 | Join the IRC channel `#ansible-devel` on freenode for discussions surrounding Ansible development. 265 | 266 | For questions and discussions pertaining to using the Ansible product, use the `#ansible` channel. 267 | 268 | # Credit 269 | 270 | A *huge* thank you to the Ansible team at Red Hat for providing not only a great product but also the willingness to help out contributors! 271 | --------------------------------------------------------------------------------