Ansible is used for automation.
In this post we will learn some basic stuff and workarounds in ansible.
Here is a sample ansible playbook:
hosts: localhost
vars_files:
- ./vars/main.yml
tasks:
- name: This a task
vars:
a: "apple"
b: ["book", "cat", "dog"]
command: echo "{{ a }}"
register: sample_task
- debug: var=sample_task # or msg="{{ sample_task }}"
This command contains a list or a environment where all the tasks will run. Hosts can be defined in multiple ways. Like using a custom inventory file, using default inventory file and directly writing after hosts module.
- Directly Writing after hosts module
hosts: localhost
- using inventory file
Create an inventory file with name
inventory
with following containts:
[host1]
IP_1
[host2]
IP_2
[host3]
IP_3
[host_list:children]
host1
host2
host3
Write hosts module as:
hosts: host1:host2:host3
or hosts: host1
or hosts: hostlist
To exucute playbook use command: ansible-playbook -i inventory my_playbook.yml --private-key="KEY"
- using default inventory
Default inventory file is at
/etc/ansible/hosts
. If inventory file is not provided, this is used as inventory.
This command is used to write tasks to be executed on the environmet, all tasks will be inside this only, for that environment. A simple task is written as:
- name: This a task
vars:
a: "apple"
b: ["book", "cat", "dog"]
command: echo "{{ a }}"
register: sample_task
Script module is used to upload script at the environment and execute the script. script will contain a complete playbook. A sample task with script module:
- script: './files/my_script.yml -i inventory --private-key=keys/KEY.pem'
args:
chdir: '/home/ubuntu/scripts' # the inventory file and keys folder will be located here
register: output
List of files that contains the varibales needed in the tasks. A typical vars file:
INT_VAR: 12313
STR_VAR: "Apple"
use:
vars_files:
- ./vars/main.yml
This module is used to inialize new variable.
This module is used to inialize new variable.
For Itrating over list etc.
vars:
my_list:
- 1
- 2
- 3
To append more:
vars:
my_list: []
set_fact:
my_list: "{{ my_list }} + [ {{ item }} ]"
vars:
dict:
a: "apple"
b: "book"
c: "cat"
To append more:
- name: Create and add items to dict
vars:
def_val: "asdf"
dict: {}
set_fact:
dict: '{{ dict | combine( { item: def_val } ) }}'
with_items:
- 1
- 2
- 3
To get values:
- name: Get values
debug:
msg: "{{item.key}}: {{ item.value }}"
with_dict: "{{ dict }}"