Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.74 KB | None | 0 0
  1. # Ansible study-sheet:
  2. ## General information:
  3.  
  4. * A variable is defined as `{{ value }}`.
  5. * When using variables inside conditionals, you do not need to use brackets (`{{}}`) to specify it. eg: `when: (ansible_distribution == "CentOS")`
  6. * `with_items` and `with_files` can be used to specify multiple values in one variable.
  7. * Use the `ignore-errors` module when you want a playbook to continue when a play fails.
  8. * Tags can be used in playbooks to include or skip certain portions. See a playbook with tags below.
  9. * If a tag is selected when running a playbook, only the plays with the tag will be included in the run.
  10. * To call tags, use `--tags "tagname"`. (eg. `ansible-playbook test.yml --tags "mytag"`).
  11. * You can also exclude tags with the `--skip-tags` flag. (eg. `ansible-playbook test.yml --skip-tags "skipthis"`).
  12. * A template is a file with variables that will get replaced.
  13. * Templates uses the Jinja2 format, and are called via the template module (see example in the playbook section).
  14. * Jinja2 template-files uses the same way as yaml-files to specify variables (eg. `{{ myvariable }}`).
  15. * You can call handlers at the end of a playbook by specifying a notify tag on a play, and a handler with that name that starts at the end (see example in playbook section).
  16. * Own facts can be placed inside a `facts.d` folder in the ansible directory.
  17. * These facts can be in json or yaml format and needs to end with the extension `.fact`.
  18. * The facts in this directory will be displayed under `ansible_local` when gathering facts.
  19. * When getting sub-facts, they will need to be specified as such: `{{ ansible_date_time.date }}`. `ansible_date_time` is the fact, and `date` is the subfact.
  20. * If you don't have internet access and you want to check the ansible-docs for a module, use the `ansible-doc` command. (eg: `ansible-doc yum`).
  21. * To list all the modules on your ansible-installation, run the command: `ansible-doc -l`.
  22.  
  23. ## Useful flags:
  24. ```
  25. -f # Forks. Decides how many threads are running at the time.
  26. ```
  27. ## Ad-hoc:
  28. ### Commands:
  29. ```
  30. ansible all -b -m yum -a "name=vim state=latest" # run ad-hoc command on all servers defined in inventory file, with root, using the module yum and install vim.
  31. ansible home-servers -a "ls -l /root" # run ad-hoc command (ls -l) on the group `home-servers` defined in default inventory file.
  32. ansible -i /tmp/esxi.py all -a "echo $HOME" # echoes $HOME on all servers specified in the "esxi.py" dynamic inventory.
  33.  
  34. ansible -b -i stat-inventory web-servers -m file -a "path={{ log_folder }} state=directory" # run ad-hoc command on all `web-servers` in the `stat-inventory` file and create the folder specified in the `log_folder` variable.
  35.  
  36. ansible all -m setup | less # gathers facts from all machines in inventory and display it in `less`.
  37. ansible all -m setup -a "filter=ansible_nodename" | less # gathers facts from all machines in inventory and displays all facts from machines corresponding to the filter `ansible_nodename` it in `less`.
  38. ```
  39. ### Flags:
  40. ```
  41. # ansible all = run ad-hoc command on all servers.
  42. # -b = become (uses sudo).
  43. # -m = module name (eg. yum).
  44. # -a = command (eg. 'ls -l /root').
  45. ```
  46.  
  47. ## Inventories:
  48. ### Inventory information:
  49. * You can use your own inventory file using the flag `-i`.
  50. * Inventories can include connection information (such as port number or ip-address).
  51. * In versions older than Ansible 2.0, ansible_ssh_user/host was used instead of ansible_user/host.
  52. * There are two default groups. `all` and `ungrouped`. `ungrouped` contains all hosts without a group aside from `all`.
  53. * Ansible will accept any kind of executable as an inventory file (eg. `ansible all -i /tmp/esxi.py -m ping`).
  54. * If an inventory file is executable (eg. dynamic inventory), Ansible expects a json output to stdout.
  55. * Make sure a dynamic inventory program is executable, otherwise it will not work.
  56. * When calling an executable, it will call it with the argument `--list`.
  57. * Ansible will call the script with `--host [hostname]` for host information.
  58.  
  59. ### Inventory locations:
  60. * Standard inventory file: `/etc/ansible/hosts`.
  61. * Default location for inventory group-variables: `/etc/ansible/group_vars/webservers.yaml`.
  62. * It's also possible to store the group-variables like this: `/etc/ansible/group_vars/webservers/ntp_settings.yaml`.
  63. * Default location for inventory host-variables: `/etc/ansible/host_vars/apache01.asdf.se.yaml`.
  64. * It's also possible to store the host-variables like this: `/etc/ansible/host_vars/apache01.asdf.se/ntp_settings.yaml`.
  65. * Note that the paths for variables are relative to the inventory file.
  66. * Also note that the variable files are in yaml-format, so use yaml-syntax in the files.
  67.  
  68. ### Inventory types:
  69. * Static inventories: does not change unless you make changes to them.
  70. * Dynamic inventories: changes dynamically in relation to the reported vms.
  71.  
  72. ### Inventory syntax:
  73. `/etc/ansible/hosts`:
  74. ```
  75. [web-servers] # server group.
  76. apache[01:15].asdf.se # span of apache servers.
  77. test.asdf.se ansible_connection=local # test.asdf.se is a local machine.
  78. test2.asdf.se ansible_user=test2 # use user 'test2' on server 'test2.asdf.se'.
  79.  
  80. [web-servers:vars] # variables for web-servers. note that this is not recommended, but possible. preferred way is the file below.
  81. ntp_server=ntp.asdf.se # sets the 'ntp_server'-variable to all webservers.
  82. ```
  83. `/etc/ansible/group_vars/web-servers.yaml`:
  84. ```
  85. ---
  86. ntp_server: ntp.asdf.se # sets the 'ntp_server'-variable to all webservers.
  87. ```
  88.  
  89. `/etc/ansible/host_vars/apache01.asdf.se.yaml`:
  90. ```
  91. ---
  92. log_folder: /opt/logs # sets the 'log_folder'-variable to the 'apache01.rawbit.se' host.
  93. ```
  94.  
  95. ## Playbooks:
  96. ### Playbook information:
  97. * A playbook always starts with `---` to mark the beginning of a yaml-file. Same goes with variable-files based on yaml.
  98. * A playbook is 1 or more plays.
  99. * A play is a set of steps in a process.
  100. * A playbook should be idempotent (should not break when ran multiple times).
  101. * If a j2 file is used in the template module in a playbook, variables will be expanded when copied over.
  102. * You can speed up the execution of playbooks by using forks. This will execute multiple threads at once, so for example 10 machines will be ran at once instead of the default five.
  103. * To use forks, specify the parameter `-f 10` (where 10 is the number of forks) when running a playbook, or add `serial: 10` to the playbook.
  104. * You can also use percentage in forks. (eg. `serial: "30%"`). It will then run on 30% of the hosts at the time.
  105. * If you want to allow a certain amount of failed plays in a playbook, you can use `max_fail_percentage`. (eg. `max_fail_percentage: 30`).
  106. * You can limit a playbook run using the `-l` flag. It will then run against the group specified. (eg: `ansible-playbook -l wildflyservers ping.yml`).
  107.  
  108. ### Modules to take note of:
  109. ```bash
  110. # management
  111. user # manages user accounts and attributes.
  112. groups # create and remove groups.
  113.  
  114. # system
  115. command # execute a command on a remote node.
  116. shell # execute commands on nodes. it is almost exactly the same as 'command' module, but this runs it through the shell '/bin/sh' which exposes env-vars like $HOME. Use when using commands and not executing scripts (eg. 'echo hej').
  117. script # runs a local script on node after transferring it.
  118. service # manage services. start/enable/stop etc.
  119. ping # ensure that a connection can be made with node. (returns 'pong' on success).
  120. yum # manages packages using the yum command. install/uninstall etc.
  121.  
  122. # file management
  123. copy # copies files to remote locations.
  124. lineinfile # add or replace a line in a file. (eg: find line that says '#listen' and change to 'listen').
  125. get_url # downloads files from http(s) or ftp to a node.
  126. unarchive # unpacks an archive and (optionally) copies it.
  127.  
  128. # application
  129. htpasswd # add or remove username/password entries in a password file. used by apache and nginx for authentication.
  130. ```
  131.  
  132. ### Playbook examples:
  133. **'/etc/ansible/playbooks/install-apache.yaml':**
  134. ```yaml
  135. ---
  136. - hosts: webservers
  137. become: yes
  138. serial: 10
  139.  
  140. vars:
  141. http_port: 80
  142. max_clients: 200
  143.  
  144. tasks:
  145. - name: install apache
  146. yum:
  147. name: httpd
  148. state: latest
  149.  
  150. - name: copy template config file
  151. template:
  152. src: /etc/ansible/templates/httpd.j2
  153. dest: /etc/httpd.conf
  154. owner: apache
  155. group: apache
  156. notify:
  157. - restart apache
  158.  
  159. - name: start and enable apache
  160. service:
  161. name: httpd
  162. state: started
  163. enabled: yes
  164.  
  165. handlers:
  166. - name: restart apache
  167. service:
  168. name: httpd
  169. state: restarted
  170. ```
  171.  
  172. **'/etc/ansible/playbooks/echo-hello.yaml':**
  173. ```yaml
  174. ---
  175. - hosts: webservers
  176. tasks:
  177. - name: echo "Hello World!"
  178. command: echo "Hello World!"
  179. register: hello
  180.  
  181. - name: echo stdout of the hello register
  182. debug:
  183. msg: "{{ hello.stdout }}"
  184.  
  185. - name: echo stderr of the hello register
  186. debug:
  187. msg: "{{ hello.stderr }}"
  188. ```
  189.  
  190. **'/etc/ansible/playbooks/install-apache-centos.yaml':**
  191. ```yaml
  192. ---
  193. - hosts: apache.asdf.se
  194. become: yes
  195.  
  196. tasks:
  197. - name: install apache if os equals centos
  198. yum:
  199. name: httpd
  200. state: latest
  201. when: ansible_os_family == "RedHat"
  202. ```
  203.  
  204. **'/etc/ansible/playbooks/initial-install.yaml':**
  205. ```yaml
  206. - hosts: '{{ target }}'
  207. gather_facts: no
  208. tasks:
  209. - name: upgrade all packages
  210. yum:
  211. name: '*'
  212. state: latest
  213. update_cache: yes
  214. tags:
  215. - upgrade
  216.  
  217. - name: install ius repo on centos7-machines
  218. yum:
  219. name: https://centos7.iuscommunity.org/ius-release.rpm
  220. state: latest
  221. when:
  222. - ansible_distribution == "CentOS"
  223. - ansible_distribution_major_version == "7"
  224.  
  225. - name: install EPEL-repo
  226. yum:
  227. name: 'epel-release'
  228. state: present
  229.  
  230. - name: install base packages
  231. yum:
  232. name: '{{ item }}'
  233. state: present
  234. with_items:
  235. - htop
  236. - vim
  237. - nano
  238. - git
  239. - wget
  240. - nfs-utils
  241. - gcc
  242. - policycoreutils-python
  243. - tmux
  244. - unzip
  245. - python-pip
  246. - rubygems
  247. ```
  248.  
  249. **'/etc/ansible/playbooks/ignore-error.yaml':**
  250. ```yaml
  251. - hosts: '{{ target }}'
  252. gather_facts: no
  253. tasks:
  254. - name: try to touch a file without permission
  255. file:
  256. state: touch
  257. path: /etc/important_file
  258. ignore_errors: yes
  259. register: touch
  260.  
  261. - name: echo stdout of the touch register
  262. debug:
  263. msg: "{{ touch.stdout }}"
  264.  
  265. - name: echo stderr of the touch register
  266. debug:
  267. msg: "{{ touch.stderr }}"
  268.  
  269. ```
  270.  
  271. ## Roles:
  272. * Roles can be thought of as a playbook that has been split into multiple parts. (eg. one file for tasks, one for variables and one for handlers).
  273. * This structure has the advantage of being scaleable, creating the possibility to register certain variables when certain portions run and getting a nice overview.
  274. * When using split up playbooks, use the `include`-module, to call them.
  275. * When calling a role, it will look for a file called `main.yaml`.
  276. * When using roles, it's very important to use the official tree structure so that ansible can find the files correctly. (see below).
  277. * You can use the ansible-galaxy command to create the correct tree structure by invoking: `ansible-galaxy init rolename`.
  278. * When using yaml-files in the roles tree-structure, you do not need to declare the files with `---` in the beginning (but it is still recommended).
  279. * Handlers will ALWAYS run at the end, even if it is included in the first role of several in the playbook.
  280.  
  281.  
  282. ### Tree structure of roles:
  283. ```
  284. roles/
  285. common/ # this hierarchy represents a "role"
  286. tasks/ #
  287. main.yml # <-- tasks file can include smaller files if warranted
  288. handlers/ #
  289. main.yml # <-- handlers file
  290. templates/ # <-- files for use with the template resource
  291. ntp.conf.j2 # <------- templates end in .j2
  292. files/ #
  293. bar.txt # <-- files for use with the copy resource
  294. foo.sh # <-- script files for use with the script resource
  295. vars/ #
  296. main.yml # <-- variables associated with this role
  297. defaults/ #
  298. main.yml # <-- default lower priority variables for this role
  299. meta/ #
  300. main.yml # <-- role dependencies
  301. library/ # roles can also include custom modules
  302. module_utils/ # roles can also include custom module_utils
  303. lookup_plugins/ # or other types of plugins, like lookup in this case
  304. apache/ # this hierarchy represents a "role"
  305. tasks/ #
  306. main.yml # <-- tasks file can include smaller files if warranted
  307. handlers/ #
  308. main.yml # <-- handlers file
  309. templates/ # <-- files for use with the template resource
  310. httpd.conf.j2 # <------- templates end in .j2
  311. files/ #
  312. bar.txt # <-- files for use with the copy resource
  313. vars/ #
  314. main.yml # <-- variables associated with this role
  315. ```
  316.  
  317. ### Role example:
  318. `playbook.yaml`:
  319. ```yaml
  320. ---
  321. - hosts: webservers
  322. roles:
  323. - common
  324. - { role: apache, when: "ansible_os_family == 'RedHat'" } # the role should be available at ./$rolename with the structure above.
  325.  
  326. tasks:
  327. - include: tasks/mainplay.yml # tasks can be inserted besides a role
  328. ```
  329. `tasks/mainplay.yml`:
  330. ```yaml
  331. ---
  332. - name: cat motd
  333. shell: cat /etc/motd
  334. ```
  335.  
  336. ## Ansible Galaxy:
  337. * Ansible galaxy is a site where users can upload their roles
  338. * You can use the `ansible-galaxy` command to download these roles.
  339. * By default, the roles are downloaded to the path in the config file `/etc/ansible`. This can be changed with the `-p` option.
  340. * Roles can have dependencies, but if they do, they will be installed automatically.
  341. * You can access Ansible Galaxy by going to [their website](https://galaxy.ansible.com).
  342. * The roles from Ansible Galaxy often includes a readme with syntax usage, so be sure to read it before executing.
  343.  
  344. ## Ansible Vault
  345. ### Main info:
  346. * Ansible Vault is a secure store for storing passwords, files and variables securely.
  347. * Use the command `ansible-vault` for editing and creating the encryption.
  348. * When using content from the ansible vault, you need to specify the password-file or password-string with the flag `--ask-vault-pass` or `--vault-password-file`.
  349. * Ansible will automatically sense if the file is a vault if it is included in a role or playbook. Ansible will fail if the password is not provided in that case.
  350. * **Do note that when using verbose mode in a playbook, the decrypted content from ansible-vault may be seen in cleartext.**
  351. * If you want a play to be excluded from running verbose, use the `no_log` tag (eg. `no_log: true`).
  352.  
  353. ### Using password-files:
  354. * When using password-files, a playbook can run without interaction even when using files or variables inside ansible-vault.
  355. * To use a password-file, create a regular file with the password inside and call the playbook using the syntax below.
  356.  
  357. ### Syntax:
  358.  
  359. ```bash
  360. ansible-vault encrypt /path/to/file # encrypts a file using ansible-vault
  361. ansible-vault decrypt /path/to/file # decrypts a file using ansible-vault
  362.  
  363. ansible-vault rekey /path/to/file # changes the password of a file that is encrypted
  364. ansible-vault edit /path/to/file # edits a file that is encrypted
  365. ansible-vault view /path/to/file # views (cat) a file that is encrypted
  366.  
  367. ansible-playbook all play.yml --vault-password-file=/path/to/passwordfile # runs playbook and uses the passwordfile as vault-password
  368. ```
  369.  
  370. ## Ansible Tower
  371. ### Main info:
  372. * The installation of Ansible Tower requires at least 2GB of RAM.
  373. * It is packaged as a tar.gz file, which needs to be unpacked before installation.
  374. * If you look in the README, you will notice that a few variables needs to be changed (eg. password), before running `setup.sh`.
  375. * You will need a license for Ansible Tower. Though, you can install the open source variant "AWX".
  376. * After adding a user in the GUI, you will have to set up credentials for the machines / services that you plan to control. This is done via the settings menu.
  377. * A Project is a logical collection of Ansible playbooks, represented in Tower.
  378. * A job template is a definition and set of parameters for running an Ansible job. Job templates are useful to execute the same job many times.
  379. * Ad-hoc commands can be ran against hosts via the hosts menu.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement