0% found this document useful (0 votes)
103 views

Ansible Chors Content

This document summarizes common Linux commands: - pwd displays the present working directory, ls lists contents of the present directory, and cd .. moves one folder up. mkdir creates a directory, and rm removes files or directories including forcefully removing non-empty directories with rm -rf. vi edits or creates files.

Uploaded by

AniKet B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views

Ansible Chors Content

This document summarizes common Linux commands: - pwd displays the present working directory, ls lists contents of the present directory, and cd .. moves one folder up. mkdir creates a directory, and rm removes files or directories including forcefully removing non-empty directories with rm -rf. vi edits or creates files.

Uploaded by

AniKet B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

 pwd: psresent working directory

 ls: list contents in present directory


 cd ..: move one folder up
 mkdir: create directory
 rm -rf dir_name: remove non-empty directory forcefully
 rm file_name: remove file/directory
 vi file_name: edit/create a file. Press i for insert mode, Esc to come out of
insert mode, :wq to save the file and exit from vi editor, :q! to exit
from vi editor without saving the file.

Variables may be included inline with the rest of a playbook, using vars:

---

- hosts: all

vars:

var: 20

tasks:

- debug: msg="Variable 'var' is set to {{ var }}"

Variables In Playbook
Variables may also be included in a separate file, using the vars_files section

file: playbook.yml
---

- hosts: all

vars_files:

- vars.yml

tasks:

- debug: msg="Variable 'var' is set to {{ var }}"

file: vars.yml

---

var: 20

You can create the above two files in Katacoda and run it: ansible-playbook -i

myhosts playbook.yml

Variables In Inventory
You can add variables in your inventory files as:

 Host Variables - Variables are defined inline for individual host


 Group Variables - Variables are applied to entire group of hosts
#host variables

[group1]

host1 http_port=80

host2 http_port=303

#group variables

[group1:vars]

ntp_server= example.com

proxy=proxy.example.com

Organizing Host And Group Variables


What will you do when you need to define multiple variables to multiple hosts?
Writing everything inside your inventory file might be cumbersome.

Ansible recommends you to store host and group variables as individual


files under /etc/ansible/host_vars/ and /etc/ansible/group_vars/ locations
respectively.

 These variable files are in YAML format with valid file


extensions: .yml, .yaml, .jsonor no file extension

/etc/ansible/host_vars/host1.example.com

/etc/ansible/group_vars/group1.yml
/etc/ansible/group_vars/webservers

Defining Complex Variables


You can define variables as structured arrays (lists), which you can access
as foo[0] as shown:

---

- name: list variables

hosts: all

vars:

foo:

- one

- two

- three

tasks:

- name: variable index 1

debug: msg="{{ foo[0] }}"


- name: variable index 3

debug: msg="{{ foo[2] }}"

Accessing Complex Variables


For larger variables, you can easily access part of a variable by using
bracket [] or dot .syntax.

For example:

consider you want to retrieve only IPv4 address of the server. But you
might first prefer to take a look at the structure of the entire built-in variable
(ansible_eth0) as shown:
Go ahead and try this playbook in Katacoda

---

- name: complex variables

hosts: all

tasks:

- debug: var=ansible_eth0

- debug: msg="{{ ansible_eth0.ipv4.address }}"

- debug: msg="{{ ansible_eth0['ipv4']['address'] }}"


 First task will show how the variable ansible_eth0 is structured
 Second and third tasks displays only the required info

Facts
You might have observed this output while running the playbook.
GATHERING FACTS *************************

ok: [host01]

**Whenever you run Playbook, Ansible by default collects information (facts) about each
host like host IP address, CPU type, disk space, operating system information etc.**

You can run the following in **[Katacoda]


(https://www.katacoda.com/jonatanblue/scenarios/1)** to find the information about
**host01**:

`ansible host01 -i myhosts -m setup`

Gathering Facts Takes Time


In case you do not need facts of hosts, you can skip the task by
setting gather_facts: noin your playbook.
This can save time especially when you are running your Playbook in dozens or
hundreds of servers.

Run the following in Katacoda and observe if the task (Gathering Facts) runs or
not:

---

- name: testing gather_facts

hosts: all

gather_facts: no

tasks:

- action: ping

Built-In Variables
In Ansible you get some variables by default, even if you do not define
them, that helps you to access information about other hosts. Thus you
should not define these variables explicitly, as they are reserved.

Let us explore a few of them:

 hostvars
 groups
 inventory_hostname

Hostvars
Occasionally you might be running a task that needs the value of the
variable defined in other hosts. By default, variables in Ansible are
scoped by hosts.
Ansible provides you with hostvars variable that has all the variables and
facts (facts are gathered only if you have talked to the host at least once in any
play of your playbook) of all the hosts.

For Example:

Consider you need to run a task in host1 that need IP address of the eth1
interface of the host2

{{ hostvars['host2'].ansible_eth1.ipv4.address }}

Hostvars
Occasionally you might be running a task that needs the value of the
variable defined in other hosts. By default, variables in Ansible are
scoped by hosts.
Ansible provides you with hostvars variable that has all the variables and
facts (facts are gathered only if you have talked to the host at least once in any
play of your playbook) of all the hosts.

For Example:

Consider you need to run a task in host1 that need IP address of the eth1
interface of the host2

{{ hostvars['host2'].ansible_eth1.ipv4.address }}

Scope Of Host Variables


Wondering the scope of variables defined in group of servers??
#host variables

[group1]

host1 http_port=80

host2 http_port=303

host3

#group variables

[group1:vars]

ntp_server= example.com

proxy=proxy.example.com

Variables defined in group variables are actually copied to individual hosts


of that group, thus making their scope limited to only the host.

Groups
You can find the list of group names defined in your inventory
file using groups variable.

For Example: Consider you need the IP address of all the servers in
you web group
{% for host in groups.web %}

server {{ host.inventory_hostname }} {{ host.ansible_default_ipv4.address }}:8080

{% endfor %}

The generated file might look like this:

server chennai.fresco.me 192.0.115.17:8080

server california.fresco.me 192.0.115.78:8080

server singapore.fresco.me 193.0.115.68:8080

Inventory_hostname
You can find the name of the current host using inventory_hostname.

#inventory file

[group1]

server1 ansible_ssh_host=192.169.67.34

inventory_hostname would be server1 instead of 192.169.67.34


Registered Variable
Ansible allows you to save the output of a task in a variable at run time,
through registerkeyword.

Syntax: register: variable_name

Let us now see how the return value of  command module looks like. Go ahead
and run the following playbook in Katacoda

file: test.yml

---

- name: show return value of command module

hosts: all

tasks:

- name: creating folder

command: mkdir folder7

register: output

- debug: var=output

 Run your playbook: ansible-playbook -i myhosts test.yml  and observe the


output carefully
 You might observe the output of running a task is returned in JSON
format

Registered Variable
This playbook will check the contents of the home directory of your host
machine (host01)and display a message accordingly

Go ahead and run this in Katacoda

---

- name: check registered variable for emptiness

hosts: all

tasks:

- name: list contents of the directory in the host

command: ls /home/ubuntu

register: contents

- name: check dir is empty

debug: msg="Directory is empty"

when: contents.stdout == ""

- name: check dir has contents


debug: msg="Directory is not empty"

when: contents.stdout != ""

 register variable stores the output, after executing command module,


in contentsvariable
 stdout is used to access string content of register variable

Variable Precedence
If you define the same variable in multiple places, it will be overwritten in a certain
order as shown:

 variable you define in Command Line Interface while executing


Playbook (Highest Priority)

 variables that you define inside play of Playbook

 facts that you discover about other hosts

 variables defined under the [defaults] category of Roles* (least priority)

Command Line > Playbook > Facts > Roles

You can find the complete details here

*Hold On!! Roles will be discussed in upcoming sections

Workout - - Variable Precedence


 Fact: The default value of fact variable ansible_bios_version is Bochs
ansible host01 -i myhosts -m setup

 Play: Write Playbook defining the fact


variable ansible_bios_version as fresco

#file: test.yml

---

- hosts: all

vars:

ansible_bios_version: Fresco

tasks:

- debug: msg="Variable 'ansible_bios_version' is set to {{ ansible_bios_version }}"

Now run this playbook and notice the value of ansible_bios_version.

ansible-playbook -i myhosts test.yml

 CLI: While running the playbook in Command Line redefine the variable
- ansible-playbook -i myhosts test.yml --extra-vars
"ansible_bios_version=Ansible"

Tags
Tags arenames pinned on individual tasks, roles or an entire play, that allows
you to run or skip parts of your Playbook.

Tags can help you while testing certain parts of your Playbook.

file: tag.yml

---

- name: Play1-install apache

hosts: all

sudo: yes

tasks:

- name: install apache2

apt: name=apache2 update_cache=yes state=latest

- name: displaying "hello world"

debug: msg="hello world"

tags:

- tag1

- name: Play2-install nginx


hosts: all

sudo: yes

tags:

- tag2

tasks:

- name: install nginx

apt: name=nginx update_cache=yes state=latest

- name: debug module displays message in control machine

debug: msg="have a good day"

tags:

- mymessage

- name: shell module displays message in host machine.

shell: echo "yet another task"

tags:

- mymessage
Running Tag.yml
You may save the above Playbook with name tag.yml and run the following
commands in Katacoda

 ansible-playbook -i myhosts tag.yml --list-tasks  : displays the list of


tasks in the Playbook

 ansible-playbook -i myhosts tag.yml --list-tags  : displays only tags


in your Playbook

 ansible-playbook -i myhosts tag.yml --tags


"tag1,mymessage" : executes only certain tasks which are tagged
as tag1 and mymessage

Special Tags
Ansible has some special keywords for tags:

 always: runs the task always


 tagged: run only those tasks which have some tag

 untagged: run only those tags which do not have any tags

 all: run all the tags

You can skip always tag by defining: --skip-tags always

Include
Till now you were dumping all the tasks and other stuff (handlers, variables) in a
single Playbook. This makes it cumbersome to maintain the Playbook as it grows.
Ansible gives you the flexibility of organizing your tasks through include keyword,
that introduces more abstraction and make your Playbook more easily maintainable,
reusable and powerful.
playbook_include.yml

---

- name: testing includes

hosts: all

sudo: yes

tasks:

- include: apache.yml

- include: content.yml

- include: create_folder.yml

- include: content.yml

- include: nginx.yml

 You might need root access to install anything in host, that's why sudo: yes

 First, you will be installing Apache


 Then you will observe that the host machine is empty at
location /home/ubuntu
 You will create a folder in the same location of the host machine
 Now you will again check if the location has any content
 In the end, you will install Nginx as a separate play
Now let us go ahead and add the remaining files in the same test folder.

apache.yml

---

- name: install apache2

apt: name=apache2 update_cache=yes state=latest

- name: displaying message

debug: msg="you are awesome!!"

create_folder.yml

---

- name: creating folder

file: path=/home/ubuntu/folder1 state=directory

content.yml
---

- name: list contents of directory in host

command: ls /home/ubuntu

register: contents

- name: check dir is empty

debug: msg="Directory is empty"

when: contents.stdout == ""

- name: check dir has contents

debug: msg="Directory is not empty"

when: contents.stdout != ""

nginx.yml

---

- name: installing nginx

hosts: all
sudo: yes

tasks:

- name: install nginx

apt: name=nginx update_cache=yes state=latest

- name: displaying message

debug: msg="yayy!! nginx installed"

Did you notice something? If you did, you are awesome. And if you don't,
you are like 99.9999% others. Cheers!
nginx.yml, unlike apache.yml, is a Playbook which you can run independently. That
is why it has tasks and other keywords mentioned explicitly.

Intro To Roles
Roles are added abstraction of building your Playbook in more modular fashion,
where you hide all the technicalities by splitting your tasks into smaller files and
grouping them under respective folders of tasks, templates, handlers, vars etc.

 This is similar to writing Object Oriented Code (for example) in Java


 Discrete pieces of code can be easily included into larger programs as needed
 A Role is completely self contained or encapsulated and completely reusable
A Role has following folders:

 Files
 Handlers
 Meta
 Templates
 Vars
 Defaults

File folder has static files that need to be


transferred to host machines. This also stores
script file to run.

All the special tasks that you define in your


playbooks, which run only if triggered
by  notify keyword, are kept in Handlersfolder.

You can define a list of roles that should run first


before the current role can run properly. In
short, Meta folder contains the dependencies of
current role.
You can define each task as YAML file and keep
them in Tasks folder.

You can keep all the dynamic files (jinja2), that


use variables to be substituted with values during
runtime, in Templatefolder.

The variables of your role are defined


in Vars folder.

Defaults folder works similar to vars folder, only


the priority of variables defined in defaults is less
than variables in vars.

Creating Structure For Your Role


Before beginning with the Pahase 1, you need to follow these steps to create
the folder structure for your Role:

 Create a folder called roles: mkdir roles and cd roles

 Create a folder called sample_role inside roles: mkdir sample_role and cd


sample_role

 Create your folder structure for your role: mkdir defaults files


handlers tasks templates vars

As your structure is ready, let us now create required files.


Phase 1- nginx.yml

You need to create task for installing Nginx in host under roles/sample_role/tasks/

file: tasks/nginx.yml

---

- name: Installs nginx


apt: pkg=nginx state=installed update_cache=true

notify:

- start nginx

Phase 1- Creating Handler


Now you may come out of tasks folder (cd ..) and write your special handler task
inside handlers folder

file: handlers/main.yml

---

- name: start nginx

service: name=nginx state=started

Phase 1-Including Tasks In Main.yml


*Just like nginx.yml, later you will be adding more files in tasks folder.

How will ansible know which task to execute first?*

Tasks, Handlers, and Vars folder always have main.yml file


You need to include those tasks in main.yml file.

file: tasks/main.yml
---

- include: nginx.yml

As you can see, tasks/main.yml is just list of tasks.

Creating Master Playbook


To run all your tasks, you need to create a Playbook in root location
(/home/scrapbook/tutorial) location, which will call your role (sample_role).

 Use cd .. to move up one directory


 Use pwd to know your present working directory
 Use ls to check files and folder in your present folder

file: master_playbook.yml

---

- name: my first role in ansible

hosts: all

sudo: yes

roles:

- sample_role
Telling Ansible About Your Roles
You called your role in Playbook but how will Ansible know, where your roles are
defined?

You need to explicitly tell the path(of roles) in ansible.cfg file


 Remove the default configuration file: rm ansible.cfg (present in
/home/scrapbook/tutorial/ansible.cfg)
 Add your new configuration settings: vi ansible.cfg, press i and use the
settings as shown:

file: ansible.cfg

[defaults]

host_key_checking=False

roles_path = /home/scrapbook/tutorial/roles/

```

What Is Happening?
So, let us have a look at what exactly is happening:

 You have given the location of your roles by setting roles_path in


Ansible configuration file.
 When you run this playbook, the Role will first check main.yml file
in tasks folderand execute tasks.
You can also define multiple roles in master_playbook and they are executed
in a sequential manner.

- .....

roles:

- sample_role

- sample_role2

....

Phase 2 - Copying Static File


Let us now create a task to copy a static file to your host machine.

file: tasks/copy-static.yml

---

- name: Copy a file

copy: src=some-file.txt dest=/home/ubuntu/file1.txt


But, do we have sample-file.txt ?? No!!

Static files are kept in files folder of a Role.

Let us create a file in files folder: touch some-file.txt

Phase 2 - Including Task in Main Task File


Include the new task in main.yml file

file: tasks/main.yml

---

- include: nginx.yml

- include: copy-static.yml

Run your master_playbook and check the output: ansible-playbook -i myhosts

master_playbook.yml

Note: To run your master_playbook, you must be present


at  /home/scrapbook/tutorial

Phase 3 - Creating Template And Variable File


Templates/Dynamic/Configuration files are kept in templates folder of a role.

file: templates/template-file.j2

this is {{item}}

Variables are kept in vars folder

file: vars/main.yml
var_x:

- 'variable x'

var_y:

- 'variable y'

Phase 3 - Creating Task To Send Your


Configurations
Let us create a task to send your template/dynamic/configuration file to your host
machine.

file: tasks/copy-template.yml

---

- name: sample template - x

template:

src: template-file.j2

dest: /home/ubuntu/copy-template-file.j2

with_items: var_x
Phase 3 - Including Task in Main Task File
Include the task you just created in your main file:

file: tasks/main.yml

---

- include: nginx.yml

- include: copy-static.yml

- include: copy-template.yml

Run your master_playbook and check the output: ansible-playbook -i myhosts

master_playbook.yml

Running Role
Let us run the master_playbook and check the output:

ansible-playbook -i myhosts master_playbook.yml

Note: You can enter yes if prompted while running master_playbook

What Is Ansible Galaxy?


If you are annoyed to build the file structure for a role from scratch in
Ansible every time, then this is for you.
Let us enter the Galaxy Of Ansible
 Ansible Galaxy is a website where people like you
can explore, download and rateroles. you can also contribute your role.
 ansible-galaxy is command line tool for scaffolding the creation
of directory structure needed for organizing your code

Try this command in Katacoda: ansible-galaxy init sample_role

Environment Variables
Managing huge number of hosts can be tedious when the deployment
environment is different: development, staging and production
For example, memory requirement for servers in production might be
different from servers in the development environment
Ansible recommended way of solving this issue is by maintaining inventory file
for each environment, instead of keeping all your hosts in a single inventory.

You can also maintain a separate directory for group_vars.

Multiple Inventories For Each Environment


This is how a basic directory structure of multistage environment look.

Each environment directory has one inventory file (hosts) and group_vars directory.


2 of 2

You might also like