Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Ansible study-sheet:
- ## General information:
- * A variable is defined as `{{ value }}`.
- * When using variables inside conditionals, you do not need to use brackets (`{{}}`) to specify it. eg: `when: (ansible_distribution == "CentOS")`
- * `with_items` and `with_files` can be used to specify multiple values in one variable.
- * Use the `ignore-errors` module when you want a playbook to continue when a play fails.
- * Tags can be used in playbooks to include or skip certain portions. See a playbook with tags below.
- * If a tag is selected when running a playbook, only the plays with the tag will be included in the run.
- * To call tags, use `--tags "tagname"`. (eg. `ansible-playbook test.yml --tags "mytag"`).
- * You can also exclude tags with the `--skip-tags` flag. (eg. `ansible-playbook test.yml --skip-tags "skipthis"`).
- * A template is a file with variables that will get replaced.
- * Templates uses the Jinja2 format, and are called via the template module (see example in the playbook section).
- * Jinja2 template-files uses the same way as yaml-files to specify variables (eg. `{{ myvariable }}`).
- * 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).
- * Own facts can be placed inside a `facts.d` folder in the ansible directory.
- * These facts can be in json or yaml format and needs to end with the extension `.fact`.
- * The facts in this directory will be displayed under `ansible_local` when gathering facts.
- * 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.
- * 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`).
- * To list all the modules on your ansible-installation, run the command: `ansible-doc -l`.
- ## Useful flags:
- ```
- -f # Forks. Decides how many threads are running at the time.
- ```
- ## Ad-hoc:
- ### Commands:
- ```
- 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.
- ansible home-servers -a "ls -l /root" # run ad-hoc command (ls -l) on the group `home-servers` defined in default inventory file.
- ansible -i /tmp/esxi.py all -a "echo $HOME" # echoes $HOME on all servers specified in the "esxi.py" dynamic inventory.
- 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.
- ansible all -m setup | less # gathers facts from all machines in inventory and display it in `less`.
- 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`.
- ```
- ### Flags:
- ```
- # ansible all = run ad-hoc command on all servers.
- # -b = become (uses sudo).
- # -m = module name (eg. yum).
- # -a = command (eg. 'ls -l /root').
- ```
- ## Inventories:
- ### Inventory information:
- * You can use your own inventory file using the flag `-i`.
- * Inventories can include connection information (such as port number or ip-address).
- * In versions older than Ansible 2.0, ansible_ssh_user/host was used instead of ansible_user/host.
- * There are two default groups. `all` and `ungrouped`. `ungrouped` contains all hosts without a group aside from `all`.
- * Ansible will accept any kind of executable as an inventory file (eg. `ansible all -i /tmp/esxi.py -m ping`).
- * If an inventory file is executable (eg. dynamic inventory), Ansible expects a json output to stdout.
- * Make sure a dynamic inventory program is executable, otherwise it will not work.
- * When calling an executable, it will call it with the argument `--list`.
- * Ansible will call the script with `--host [hostname]` for host information.
- ### Inventory locations:
- * Standard inventory file: `/etc/ansible/hosts`.
- * Default location for inventory group-variables: `/etc/ansible/group_vars/webservers.yaml`.
- * It's also possible to store the group-variables like this: `/etc/ansible/group_vars/webservers/ntp_settings.yaml`.
- * Default location for inventory host-variables: `/etc/ansible/host_vars/apache01.asdf.se.yaml`.
- * It's also possible to store the host-variables like this: `/etc/ansible/host_vars/apache01.asdf.se/ntp_settings.yaml`.
- * Note that the paths for variables are relative to the inventory file.
- * Also note that the variable files are in yaml-format, so use yaml-syntax in the files.
- ### Inventory types:
- * Static inventories: does not change unless you make changes to them.
- * Dynamic inventories: changes dynamically in relation to the reported vms.
- ### Inventory syntax:
- `/etc/ansible/hosts`:
- ```
- [web-servers] # server group.
- apache[01:15].asdf.se # span of apache servers.
- test.asdf.se ansible_connection=local # test.asdf.se is a local machine.
- test2.asdf.se ansible_user=test2 # use user 'test2' on server 'test2.asdf.se'.
- [web-servers:vars] # variables for web-servers. note that this is not recommended, but possible. preferred way is the file below.
- ntp_server=ntp.asdf.se # sets the 'ntp_server'-variable to all webservers.
- ```
- `/etc/ansible/group_vars/web-servers.yaml`:
- ```
- ---
- ntp_server: ntp.asdf.se # sets the 'ntp_server'-variable to all webservers.
- ```
- `/etc/ansible/host_vars/apache01.asdf.se.yaml`:
- ```
- ---
- log_folder: /opt/logs # sets the 'log_folder'-variable to the 'apache01.rawbit.se' host.
- ```
- ## Playbooks:
- ### Playbook information:
- * A playbook always starts with `---` to mark the beginning of a yaml-file. Same goes with variable-files based on yaml.
- * A playbook is 1 or more plays.
- * A play is a set of steps in a process.
- * A playbook should be idempotent (should not break when ran multiple times).
- * If a j2 file is used in the template module in a playbook, variables will be expanded when copied over.
- * 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.
- * 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.
- * You can also use percentage in forks. (eg. `serial: "30%"`). It will then run on 30% of the hosts at the time.
- * 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`).
- * 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`).
- ### Modules to take note of:
- ```bash
- # management
- user # manages user accounts and attributes.
- groups # create and remove groups.
- # system
- command # execute a command on a remote node.
- 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').
- script # runs a local script on node after transferring it.
- service # manage services. start/enable/stop etc.
- ping # ensure that a connection can be made with node. (returns 'pong' on success).
- yum # manages packages using the yum command. install/uninstall etc.
- # file management
- copy # copies files to remote locations.
- lineinfile # add or replace a line in a file. (eg: find line that says '#listen' and change to 'listen').
- get_url # downloads files from http(s) or ftp to a node.
- unarchive # unpacks an archive and (optionally) copies it.
- # application
- htpasswd # add or remove username/password entries in a password file. used by apache and nginx for authentication.
- ```
- ### Playbook examples:
- **'/etc/ansible/playbooks/install-apache.yaml':**
- ```yaml
- ---
- - hosts: webservers
- become: yes
- serial: 10
- vars:
- http_port: 80
- max_clients: 200
- tasks:
- - name: install apache
- yum:
- name: httpd
- state: latest
- - name: copy template config file
- template:
- src: /etc/ansible/templates/httpd.j2
- dest: /etc/httpd.conf
- owner: apache
- group: apache
- notify:
- - restart apache
- - name: start and enable apache
- service:
- name: httpd
- state: started
- enabled: yes
- handlers:
- - name: restart apache
- service:
- name: httpd
- state: restarted
- ```
- **'/etc/ansible/playbooks/echo-hello.yaml':**
- ```yaml
- ---
- - hosts: webservers
- tasks:
- - name: echo "Hello World!"
- command: echo "Hello World!"
- register: hello
- - name: echo stdout of the hello register
- debug:
- msg: "{{ hello.stdout }}"
- - name: echo stderr of the hello register
- debug:
- msg: "{{ hello.stderr }}"
- ```
- **'/etc/ansible/playbooks/install-apache-centos.yaml':**
- ```yaml
- ---
- - hosts: apache.asdf.se
- become: yes
- tasks:
- - name: install apache if os equals centos
- yum:
- name: httpd
- state: latest
- when: ansible_os_family == "RedHat"
- ```
- **'/etc/ansible/playbooks/initial-install.yaml':**
- ```yaml
- - hosts: '{{ target }}'
- gather_facts: no
- tasks:
- - name: upgrade all packages
- yum:
- name: '*'
- state: latest
- update_cache: yes
- tags:
- - upgrade
- - name: install ius repo on centos7-machines
- yum:
- name: https://centos7.iuscommunity.org/ius-release.rpm
- state: latest
- when:
- - ansible_distribution == "CentOS"
- - ansible_distribution_major_version == "7"
- - name: install EPEL-repo
- yum:
- name: 'epel-release'
- state: present
- - name: install base packages
- yum:
- name: '{{ item }}'
- state: present
- with_items:
- - htop
- - vim
- - nano
- - git
- - wget
- - nfs-utils
- - gcc
- - policycoreutils-python
- - tmux
- - unzip
- - python-pip
- - rubygems
- ```
- **'/etc/ansible/playbooks/ignore-error.yaml':**
- ```yaml
- - hosts: '{{ target }}'
- gather_facts: no
- tasks:
- - name: try to touch a file without permission
- file:
- state: touch
- path: /etc/important_file
- ignore_errors: yes
- register: touch
- - name: echo stdout of the touch register
- debug:
- msg: "{{ touch.stdout }}"
- - name: echo stderr of the touch register
- debug:
- msg: "{{ touch.stderr }}"
- ```
- ## Roles:
- * 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).
- * This structure has the advantage of being scaleable, creating the possibility to register certain variables when certain portions run and getting a nice overview.
- * When using split up playbooks, use the `include`-module, to call them.
- * When calling a role, it will look for a file called `main.yaml`.
- * When using roles, it's very important to use the official tree structure so that ansible can find the files correctly. (see below).
- * You can use the ansible-galaxy command to create the correct tree structure by invoking: `ansible-galaxy init rolename`.
- * 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).
- * Handlers will ALWAYS run at the end, even if it is included in the first role of several in the playbook.
- ### Tree structure of roles:
- ```
- roles/
- common/ # this hierarchy represents a "role"
- tasks/ #
- main.yml # <-- tasks file can include smaller files if warranted
- handlers/ #
- main.yml # <-- handlers file
- templates/ # <-- files for use with the template resource
- ntp.conf.j2 # <------- templates end in .j2
- files/ #
- bar.txt # <-- files for use with the copy resource
- foo.sh # <-- script files for use with the script resource
- vars/ #
- main.yml # <-- variables associated with this role
- defaults/ #
- main.yml # <-- default lower priority variables for this role
- meta/ #
- main.yml # <-- role dependencies
- library/ # roles can also include custom modules
- module_utils/ # roles can also include custom module_utils
- lookup_plugins/ # or other types of plugins, like lookup in this case
- apache/ # this hierarchy represents a "role"
- tasks/ #
- main.yml # <-- tasks file can include smaller files if warranted
- handlers/ #
- main.yml # <-- handlers file
- templates/ # <-- files for use with the template resource
- httpd.conf.j2 # <------- templates end in .j2
- files/ #
- bar.txt # <-- files for use with the copy resource
- vars/ #
- main.yml # <-- variables associated with this role
- ```
- ### Role example:
- `playbook.yaml`:
- ```yaml
- ---
- - hosts: webservers
- roles:
- - common
- - { role: apache, when: "ansible_os_family == 'RedHat'" } # the role should be available at ./$rolename with the structure above.
- tasks:
- - include: tasks/mainplay.yml # tasks can be inserted besides a role
- ```
- `tasks/mainplay.yml`:
- ```yaml
- ---
- - name: cat motd
- shell: cat /etc/motd
- ```
- ## Ansible Galaxy:
- * Ansible galaxy is a site where users can upload their roles
- * You can use the `ansible-galaxy` command to download these roles.
- * By default, the roles are downloaded to the path in the config file `/etc/ansible`. This can be changed with the `-p` option.
- * Roles can have dependencies, but if they do, they will be installed automatically.
- * You can access Ansible Galaxy by going to [their website](https://galaxy.ansible.com).
- * The roles from Ansible Galaxy often includes a readme with syntax usage, so be sure to read it before executing.
- ## Ansible Vault
- ### Main info:
- * Ansible Vault is a secure store for storing passwords, files and variables securely.
- * Use the command `ansible-vault` for editing and creating the encryption.
- * 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`.
- * 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.
- * **Do note that when using verbose mode in a playbook, the decrypted content from ansible-vault may be seen in cleartext.**
- * If you want a play to be excluded from running verbose, use the `no_log` tag (eg. `no_log: true`).
- ### Using password-files:
- * When using password-files, a playbook can run without interaction even when using files or variables inside ansible-vault.
- * To use a password-file, create a regular file with the password inside and call the playbook using the syntax below.
- ### Syntax:
- ```bash
- ansible-vault encrypt /path/to/file # encrypts a file using ansible-vault
- ansible-vault decrypt /path/to/file # decrypts a file using ansible-vault
- ansible-vault rekey /path/to/file # changes the password of a file that is encrypted
- ansible-vault edit /path/to/file # edits a file that is encrypted
- ansible-vault view /path/to/file # views (cat) a file that is encrypted
- ansible-playbook all play.yml --vault-password-file=/path/to/passwordfile # runs playbook and uses the passwordfile as vault-password
- ```
- ## Ansible Tower
- ### Main info:
- * The installation of Ansible Tower requires at least 2GB of RAM.
- * It is packaged as a tar.gz file, which needs to be unpacked before installation.
- * If you look in the README, you will notice that a few variables needs to be changed (eg. password), before running `setup.sh`.
- * You will need a license for Ansible Tower. Though, you can install the open source variant "AWX".
- * 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.
- * A Project is a logical collection of Ansible playbooks, represented in Tower.
- * 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.
- * Ad-hoc commands can be ran against hosts via the hosts menu.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement