1828994795
1828994795
-name: Ensure the installed service is enabled and running
GyereristepsinsAnsible
service:
name:
The above is a sample Playbook where we are trying to cover the basic syntax of a
playbook. Save the above content in a file as test.yml. A YAML syntax needs to follow the
correct indentation and one needs to be a little careful while writing the syntax.
The Different YAML Tags
Let us now go through the different YAML tags. The different tags are described below:
name
This tag specifies the name of the Ansible playbook. As in what this playbook will be doing.
Any logical name can be given to the playbook.
hosts
This tag specifies the lists of hosts or host group against which we want to run the task.
The hosts field/tag is mandatory. It tells Ansible on which hosts to run the listed tasks. The
tasks can be run on the same machine or on a remote machine. One can run the tasks on
multiple machines and hence hosts tag can have a group of hosts’ entry as well.
vars
Vars tag lets you define the variables which you can us
to variables in any programming language.
your playbook. Usage is similar
tasks
All playbooks should contain tasks or a list of tasks to be executed. Tasks are a list of
actions one needs to perform. A tasks field contains the name of the task. This works as
the help text for the user. It is not mandatory but proves useful in debugging the playbook.
Each task internally links to a piece of code called a module. A module that should be
executed, and arguments that are required for the module you want to execute.
Qerersepsine 26. Ansible — Roles
Roles provide a framework for fully independent, or interdependent collections of
variables, tasks, files, templates, and modules.
In Ansible, the role is the primary mechanism for breaking a playbook into multiple files.
This simplifies writing complex playbooks, and it makes them easier to reuse. The
breaking of playbook allows you to logically break the playbook into reusable components.
Each role is basically limited to a particular functionality or desired output, with all the
necessary steps to provide that result either within that role itself or in other roles listed
as dependencies.
Roles are not playbooks. Roles are small functionality which can be independently used
but have to be used within playbooks. There is no way to directly execute a role. Roles
have no explicit setting for which host the role will apply to.
Top-level playbooks are the bridge holding the hosts from your inventory file to roles that
should be applied to those hosts.
Creating a New Role
The directory structure for roles is essential to create a new role.
Role Structure
Roles have a structured layout on the file system. The default structure can be changed
but for now let us stick to defaults.
Each role is a directory tree in itself. The role name is the directory name within the /roles
directory.
$ ansible-galaxy -h |
Usage
ansible-galaxy [delete] import | info] init] install | ist] login] renove| search| setup]
[--help] [options] ...
Options
\elp: Show this help message and exit.
+ -v, =-verbose: Verbose mode (-vwv for more, -vwwv to enable connection
debugging)
+ =-version: Show program's version number and exit.
Gyereristepsins :Ansible
Creating a Role Directory
The above command has created the role directories.
$ ansible-galaxy init vivekrole
ERROR! The API server (https://galaxy.ansible.com/api/) is not responding,
please try again later.
$ ansible-galaxy init --force --offline vivekrole
- vivekrole was created successfully
$ tree vivekrole/
vivekrole/
aefauits
| Le main.ymi
LE files
L handiers
|G main.ym
L- neta
| Ce main.ymi
[E README .md
Fe tasks
| Ce main.ymi
[LE templates
FE tests
| inventory
| Le test ym
vars
LL main.ym
8 directories, 8 files
Not all the directories will be used in the example and we will show the use of some of
them in the example.
Qerersepsine 1Ansible
Utilizing Roles in Playbook
This is the code of the playbook we have written for demo purpose. This code is of the
playbook vivek_orchestrate.yml. We have defined the hosts: tomcat-node and called the
two roles ~ install-tomcat and start-tomcat.
The problem statement is that we have a war which we need to deploy on a machine via
Ansible.
= hosts: tomcat-node
roles:
- {role: install-tomcat}
= {role: start-tomcat}
Contents of our directory structure from where we are running the playbook.
@) Name Size (KB) Last modified]
roles 2017-11-02 1}
QWansble.cfy 1 2017-11-02 1}
hosts 1 2017-11-02 1}
vivek_orchestrate.retry 1 2017-11-08 4
(i vivek_orchestrate.yml 1 2017-11-02 1}
$s
ansible.cfg hosts roles vivek_orchestrate.retry vivek_orchestrate.yml
@ tare Ske (8) Last modified
2 retalltomeat 2017-11021.
4 starttoneat 2017-11421.
There is a tasks directory under each directory and it contains a main.yml. The main.yml
contents of install-tomcat are
#Install vivek artifacts
block:
= name: Install Tomcat artifacts
Qerersepsine 1sAnsible
action: >
yum name="demo-tomcat-1" state=present
register: Output
always:
~ debug:
mse:
- "Install Tomcat artifacts task ended with message: ((Output}}"
stalled Tomcat artifacts - {{Output.changed}}
‘The contents of main.yml of the start tomcat are:
aStart Tomcat
block:
- name: Start Tomcat
command: /bin/startup. sh"
register: output
become: true
always:
~ debug:
mse:
= "Start Tomcat task ended with message: {{output}}"
= “Tomcat started - {{output.changed})"
The advantage of breaking the playbook into roles is that anyone who wants to use the
Install tomcat feature can call the Install Tomcat role.
Breaking a Playbook into a Role
If not for the roles, the content of the main.yml of the respective role can be copied in the
playbook ym file. But to have modularity, roles were created.
Any logical entity which can be reused as a reusable function, that entity can be moved to
role. The example for this is shown above.
Ran the command to run the playbook.
-vw option for verbose output - verbose output
$ cd vivek-playbook/
Qerersepsine 16Ansible
This is the command to run the playbook.
$ sudo ansible-playbook -i hosts vivek_orchestrate.yml -vw
Output
The generated output is as seen on the screen:
Using /users/demo/vivek-playbook/ansible.cfg as config file.
PLAYBOOK: vivek_orchestrate.yml
1 plays in vivek_orchestrate.yml
PLAY [tomcat-node]
TASK [Gathering Facts]
20.056 *#4444
Tuesday 21 November 2017 13:02:05 +0530 (0:00:00.056) 0:00:
Using module file /usr/1ib/python2.7/site-
packages/ansible/modules/systen/setup.py
ESTABLISH LOCAL CONNECTION FOR USER: root
EXEC /bin/sh -c ‘echo ~ && sleep @°
EXEC /bin/sh -c ‘( umask 77 8& mkdir -p "* echo
/root/.ansible/tmp/ansible-tmp-1511249525. 88-259535494116878 ©" && echo
ansible-tmp-1511249525.88-259535494116870="" echo /root/.ansible/tmp/ansible-
‘tmp-1511249525.88-259535494116870 “" ) && sleep 0°
PUT /tmp/tmpPEPrkd TO /root/.ansible/tmp/ansible-tmp-1511249525.88-
259535494116870/setup. py
EXEC /bin/sh -c ‘chmod u+x /root/.ansible/tmp/ansible-tmp-
1511249525 .88-259535494116870/ /root/.ansible/tmp/ansible-tmp-1511249525.88-
259535494116870/setup.py && sleep @°
EXEC /bin/sh -c ‘/usr/bin/python /root/.ansible/tmp/ansible-tmp-
1511249525.88-259535494116870/setup.py; rm -rf */root/.ansible/tmp/ansible-tmp-
1511249525 ..88-259535494116870/" > /dev/null 2>81 8& sleep 0°
ok: [servert]
META: ran handlers
Qerersepsine vAnsible
TASK [install-tomcat : Install Tomcat artifacts]
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:5
Tuesday 21 November 2017 13:02:07 +0530 (0:00:01.515) @:00:01.572 *#444*
Using module file /usr/1ib/python2.7/site-
packages/ansible/modules/packaging/os/yum.py
ESTABLISH LOCAL CONNECTION FOR USER: root
EXEC /bin/sh -c ‘echo ~ && sleep 0°
EXEC /bin/sh -c "( umask 77 8& mkdir -p "” echo
/root/ .ansible/tnp/ansible-tmp-1511249527..34-40247177825302 *" && echo ansible-
‘tmp-1511249527. 34-40247177825302="" echo /root/.ansible/tmp/ansible-tmp-
1511249527. 34-40247177825302 °" ) && sleep 0°
PUT /tmp/tmpu83chg TO /root/.ansible/tnp/ansible-tmp-1511249527.34-
40247177825302/yum.py
EXEC /bin/sh -c ‘chmod u+x /root/.ansible/tmp/ansible-tmp-
1511249527. 34-40247177825302/ /root/.ansible/tmp/ansible-tmp-1511249527..34-
40247177825302/yum.py && sleep 0"
EXEC /bin/sh -c ‘/usr/bin/python /root/.ansible/tmp/ansible-tmp-
1511249527. 34-40247177825302/yum.py; rm -rf */root/.ansible/tmp/ansible-tmp-
1511249527. 34-40247177825302/" > /dev/null 2>81 && sleep 0"
changed: [servert] => {
“changed”: true,
“invocation”: {
“module_args": {
“conf_file": null,
“disable_gpg_check": false,
“disablerepo": null,
“enablerepo": null,
exclude": null,
“install_repoquery": true,
“installroot":
“list™: null,
“name”: [
“demo-tomcat-1"
1
“skip_broken": false,
resent",
“update_cache": false,
“validate_certs": true
tutorielepoint 18Ansible
esult
“Loaded plugins: product-id, search-disabled-repos, subscription-
manager\nThis system is not registered to Red Hat Subscription Management. You
can use subscription-manager to register. \nResolving Dependencies \n--> Running
transaction check\n---> Package demo-tomcat-1.noarch @:SNAPSHOT-1 will be
installed\n--> Finished Dependency Resolution\n\nDependencie:
Resolved\n\n=:
seeeesns=====\n Package Arch Version
Repository
Size\n:
\n demo-tomcat-1 noarch SNAPSHOT -1
demo-repor 7.1 M\n\nTransaction
‘Summary\
Install 1 Package\n\nTotal download size: 7.1 M\nInstalled size:
7.9 M\nDownloading packages: \nRunning transaction check\nRunning transaction
test\nTransaction test succeeded\nRunning transaction\n Installing : demo-
‘tomcat-1-SNAPSHOT-1.noarch 1/1 \n_ Verifying
demo-tomcat-1-SNAPSHOT-1.noarch ai
\n\nInstalled:\n demo-tomcat-1.noarch @:SNAPSHOT-
\n\nComplete! \n"
1
TASK [install-tomcat : debug]
task path:
/users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:11
Tuesday 21 November 2017 13:02:13 +0530 (0:00:06.757) 0:00:08.329 *#4444
{
false,
: [server2]
“changed
"msg":
Install Tomcat artifacts task ended with message: {u'msg': u'*
u'changed’: True, u'results': [u'Loaded plugins: product-id, search-disabled:
repos, subscription-manager\\nThis system is not registered to Red Hat
Subscription Management. You can use subscription-manager to
register.\\nResolving Dependencies\\n--> Running transaction check\\n--->
Package deno-tomcat-1.noarch @:SNAPSHOT-1 will be installed\\n--> Finished
Dependency Resolution\\n\\nDependencies
Resolved\\n\\
\n Package Arch Version
Repository
Size\\
sssssz=\\nInstalling:\\n deno-toncat-1 noarch SNAPSHOT-1
demo-repo1 7.1 M\\n\\nTransaction
Sunnary\\n=
Qerersepsine 19Ansible
\\ninstall 1 Package\\n\\nTotal download size: 7.1 M\\nInstalled
size: 7.9 M\\nDownloading packages:\\nRunning transaction check\\nRunning
transaction test\\nTransaction test succeeded\\nRunning transaction\\n
Installing : demo-tomcat-1-SNAPSHOT-1.noarch wa
\\n Verifying : demo-tomcat-1-SNAPSHOT-1.noarch
1/1 \\n\\nInstalled:\\n demo-tomcat-1.noarch @:SNAPSHOT-1
\\n\\nComplete!\\n"], u're’: 0}",
“Installed Tomcat artifacts - True”
TASK [install-tomcat : Clean DEMO environment]
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19
Tuesday 21 Novenber 2017 13:02:13 +0530 (0:00:00.057) 0:00:08.387 *
[WARNING]: when statements should not include jinja2 templating delimiters
such as {{ }} or (% %}. Found: {{installationoutput .changed}}
Using module file /usr/1ib/python2.7/site-
packages/ansible/modules/files/file.py
ESTABLISH LOCAL CONNECTION FOR USER: root
EXEC /bin/sh -c ‘echo ~ && sleep @°
EXEC /bin/sh -¢ ‘( umask 77 && mkdir -p "* echo
/root/.ansible/tnp/ansible-tmp-1511249534,13-128345805983963 ~" && echo
ansible-tmp-1511249534,13-128345805983963="" echo /root/.ansible/tmp/ansible-
‘tmp-1511249534,13-128345805983963 *" ) && sleep 0°
PUT /tmp/tmpdaxel7 TO /root/.ansible/tmp/ansible-tmp-1511249534.13-
128345805983963/File.py
EXEC /bin/sh -c ‘chmod usx /root/.ansible/tmp/ansible-tmp-
1511249534.13-128345805983963/ /root/.ansible/tmp/ansible-tmp-1511249534,13-
128345805983963/file.py && sleep 0°
EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-
1511249534. 13-128345805983963/file.py; rm -rf */root/.ansible/tmp/ansible-tmp-
1511249534, 13-128345805983963/" > /dev/null 2>81 8& sleep 0
changed: [servert] => {
"changed": true,
waite": {
wafter": {
"/users/demo/DEMO" ,
"absent"
tutorielepoint 20Ansible
be
path": “/users/demo/DENO" ,
state": “directory
vocation": {
“module_args": {
attributes": null,
null,
backu
content": null,
‘delimiter": null,
“diff_peek": null,
“directory_mode": null,
"follow": false,
“force”: false,
"group": null,
"mode": null,
“original_basename": null,
null,
“owner
“path: “/users/demo/DEMO",
“recurse": false,
regexp": null,
“remote_src*: null,
“selevel”: null,
“serole": null,
“setype": null,
“seuser": null,
"src": null,
“state”: “absent”,
“unsafe_writes": null,
“validate”: null
“path”: “/users/demo/DEMO",
“state”:
‘absent™
tutorialspoint
21Ansible
TASK [install-tomcat : debug]
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.257) 0:00:08.645 *#444+
ok: [servert] => {
“changed”:
false,
msg": [
‘Clean DEMO environment task ended with message :{u'diff': {u'after':
{u'path': u'/users/demo/DEMO', u'state': u'absent'}, u'before': {u'path
U'/users/deno/DEW0", u'state': u'directory'}}, u'state': u'absent", u'changed" :
True, u'path': u' /users/deno/DEMO')",
“check value :True"
TASK [install-tomcat : Copy Tomcat to user home]
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main. yml:37
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.055) 0:00:08.701 **444*
[WARNING]: when statements should not include jinja2 templating delimiters
such as {{ }} or {% %}. Found: {{installationoutput..changed}}
Using module file /usr/1ib/python2.7/site-
packages/ansible/modules/conmands/conmand. py
ESTABLISH LOCAL CONNECTION FOR USER: root
EXEC /bin/sh -c ‘echo ~ && sleep 0°
EXEC /bin/sh -c *( umask 77 8& mkdir -p "* echo
/root/ .ansible/tnp/ansible-tmp-1511249534..43-41077200718443 *" && echo ansible-
‘tnp-1511249534.43-41077200718443="" echo /root/.ansible/tmp/ansible-tmp-
1511249534.43-41077200718443 “" ) && sleep 0°
PUT /tmp/tmp25deWs TO /root/.ansible/tmp/ansible-tmp-1511249534.43-
41077200718443/ command. py
EXEC /bin/sh -c ‘chmod u+x /root/.ansible/tmp/ansible-tmp-
1511249534.43-41077200718443/ /root/.ansible/tmp/ansible-tmp-1511249534..43-
41077200718443/command.py && sleep 0°
EXEC /bin/sh -c ‘/usr/bin/python /root/.ansible/tmp/ansible-tmp-
1511249534.43-41077200718443/conmand.py; rm -rf */root/.ansible/tmp/ansible-
‘tmp-1511249534.43-41077200718443/" > /dev/null 2>81 && sleep 0°
changed: [servert] => {
22Ansible
/opt/ansible/toncat /demo"
"users /demo/DENO/"
20:20.017923"
1017-11-21 13:02:14.547633",
vocation": {
“module_args": {
‘cp -r /opt/ansible/tomcat/demo /users/demo/DEMO/",
false,
“chdir": null,
“creates”: null,
“executable”: null,
“removes”: null,
warn": true
"start": "2017-11-21 13:02:14.529710",
“stderr: **,
“stderr_lines": [],,
"stdout": **,
“stdout_lines*: []
TASK [install-tomcat : debug]
task path: /users/demo/vivek-playbook/roles/install-tomcat/tasks/main. yml:47
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.260) 0:00:08.961 *#****
ok: [servert] => {
“changed”: false,
“msg”: "Copy Tomcat to user home task ended with message {‘stderr_lines’:
(J, utchanged": True, u'end*: u'2017-11-21 13:02:14.547633", u'stdout’: u'',
u'cmd': [u'cp', u'-r', u'/opt/ansible/tomcat/demo", u' /users/demo/DEMO/"],,
u're’: @, u'start': u'2017-11-21 13:02:14.529710", u'stderr': u''
un, u'delta’:
u'@:08:00.017923', ‘stdout_lines': []}"
Qerersepsine 2Ansible
TASK [start-tomcat : Start Tomcat]
task path: /users/demo/vivek-playbook/roles/start-toncat/tasks/main.yml:5
Tuesday 21 November 2017 13:02:14 +0530 (0:00:00.044) 0:00:09.006 *#**4*
Using module file /usr/1ib/python2.7/site-
packages/ansible/modules/conmands/conmand. py
ESTABLISH LOCAL CONNECTION FOR USER: root
EXEC /bin/sh
EXEC /bin/sh -c ‘( umask 77 && mkdir -p "* echo
/root/ .ansible/tmp/ansible-tmp-1511249534,63-46501211251197 *" && echo ansible-
‘tmp-1511249534.63-46501211251197="" echo /root/.ansible/tmp/ansible-tmp-
1511249534.63-46501211251197 ~" ) && sleep 0°
PUT /tmp/tmp9¥96MQ TO /root/.ansible/tmp/ansible-tmp-1511249534.63-
4650121251197 /conmand. py
EXEC /bin/sh -c ‘chmod usx /root/.ansible/tmp/ansible-tmp-
1511249534.63-46501211251197/ /root/.ansible/tmp/ansible-tmp-1511249534..63-
46501211251197/command.py && sleep 0°
EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-
1511249534.63-46501211251197/command.py; rm -rf */root/.ansible/tmp/ansible-
‘tmp-1511249534.63-46501211251197/" > /dev/null 2>81 && sleep 0°
“echo ~ && sleep 0°
changed: [servert] => {
"changed": true,
"end": [
*/users/demo/DEMO/bin/startup. sh"
iL
“delta”: "0:00:00.020024",
‘end:
1017-11-21 13:02:14.741649",
"invocation": {
"module_args": {
‘Jusers/demo/DEMO/bin/startup. sh",
: false,
“chdir": null,
“creates”: null,
“executable”: null,
“pemoves": null,
warn": true
ny
tutorielepoint 24Ansible
“stdout_lines": [
‘Tomcat started
TASK [start-tomcat : debug]
task path: /users/demo/vivek-playbook/roles/start-tomcat/tasks/main. yml:10
00.150) 0:00:09.156 ****4*
Tuesday 21 November 2017 13:
114 +0530 (0:
‘Start Tomcat task ended with message: {"stderr_lines’: [], u'changed':
True, u'end': u'2017-11-21 13:02:14.741649', u'stdout': u'Tomcat started.",
utemd': [u' /users/demo/DEMO/bin/startup.sh"], u'rc': @, u'start': u'2017-11-21
13:02:14.721625', u'stderr': u'', u'delta’: u'0:00:00.020024", ‘stdout_lines’:
[u'Tomcat started. *]}",
“Tomcat started - True”
}
META: ran handlers
META: ran handlers
PLAY RECAP
server1 : ok=9 changed=4 —unreachable=@ —failed=@
Tuesday 21 Novenber 2017 13:
install-tomcat : Install Tomcat artifacts
Jusers/deno/vivek-playbook/roles/install-toncat/tasks/main.yml:5. ~
Gathering Facts ~~Ansible
install-tomcat : Copy Tomcat to user home
Jusers/deno/vivek-playbook/roles/install-tomcat/tasks/main.yml:37 -~
install-tomcat : Clean DEMO environment --
Jusers/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:19 -~
start-tomcat : Start Tomcat --
Jusers/demo/vivek-playbook/roles/start-toncat/tasks/main.yml:5 ~
install-tomcat : debug
/users/deno/vivek-playbook/roles/install-tomcat/tasks/main.yml:11 ~
install-tomcat : debug
Jusers/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:29 -~
install-tomcat : debug --
Jusers/demo/vivek-playbook/roles/install-tomcat/tasks/main.yml:47 -~
start-tomcat : debug
Jusers/demo/vivek-playbook/roles/start-toncat/tasks/nain.yml:10
Hit the following URL and you will be directed to a page as shown below:
http://10.76.0.134:11677/HelloWorld/HelloWorl
Tarr te
oma 1000
The deployed war just has a servlet which displays “Hello World”. The detailed output
shows the time taken by each and every task because of the entry added in ansible.cfg
file:
[defaults]
callback _whitelist = profile tasks
Qerersepsine 267. Ansible — Variables
Variable in playbooks are very similar to using variables in any programming language.
It helps you to use and assign a value to a variable and use that anywhere in the playbook.
One can put conditions around the value of the variables and accordingly use them in the
playbook.
Example
= hosts :
vars:
tomcat_port : 8080
In the above example, we have defined a variable name tomeat_port and assigned the
value 8080 to that variable and can use that in your playbook wherever needed.
Now taking a reference from the example shared. The following code is from one of the
roles (install-tomcat):
block:
- name: Install Tomcat artifacts
action: >
yum name="demo-tomcat-1" state=present
register: Output
always:
= debug:
msg:
= "Install Tomcat artifacts task ended with message:
- “Installed Tomcat artifacts - {{Output.changed}}"
{{output})"
Here, the output is the variable used.
Let us walk through all the keywords used in the above code:
+ block:
insible syntax to execute a given block.
* name: Relevant name of the block - this is used in logging and helps in debugging
that which all blocks were successfully executed,
* action: The code next to action tag is the task to be executed. The action again
is a Ansible keyword used in yaml.
GyereristepsinsAnsible
+ register: The output of the action is registered using the register keyword and
Output is the variable name which holds the action output.
+ always: Again a Ansible keyword , it states that below will always be executed.
* msg: Displays the message.
Usage of variable - {{Output}} -->
This will read the value of variable Output. Also as it is used in the msg tab, it will print
the value of the output variable.
Additionally, you can use the sub properties of the variable as well. Like in the case
checking {{Output.changed}} whether the output got changed and accordingly use it.
Exception Handling in Playbooks
Exception handling in Ansible is similar to exception handling in any programming
language. An example of the exception handling in playbook is shown below.
tasks:
= name: Name of the task to be executed
block:
- debug: msg="Just a debug message , relevant for logging’
- command:
rescue:
= debug: msg='There was an exception.
- command: output.stdout_lines gives us the line by line
output and then we loop on the output with the with_items command of Ansible.
Attaching the example output just to make one understand how we used the stdout_lines
in the with_items command.
a#Tsting
- hosts: tomcat-node
tasks:
~ name: Install Apache
shell: "1s *.war"
register: output
args:
chdir: /opt/ansible/tomcat/demo/webapps
- file:
src: ' /opt/ansible/tomcat/demo/webapps/{{ item }}"
dest: '/users/demo/vivek/{{ item }}"
state: link
with_items: "{{output.stdout_lines}}"
Blocks
The playbook in totality is broken into blocks. The smallest piece of steps to executs
written in block. Writing the specific instruction in blocks helps to segregate functionality
and handle it with exception handling if needed.
Example of blocks is covered in variable usage,exception handling and loops above.
Qerersepsine 29Ansible
Conditionals
Conditionals are used where one needs to run a specific step based on a condition.
a#Tsting
- hosts: all
vars:
testi: “Hello Vivek"
tasks:
= name: Testing Ansible variable
“Hello Vivek"
In this case, Equals will be printed as the test variable is equal as mentioned in the when
condition. when can be used with a logical OR and logical AND condition as in all the
programming languages.
CondisonalsOutputtx
t
Just change the value of test variable from Hello Vivek to say Hello World and see the
output.
Ganged
ConditonalsOutputte
Qerersepsine x08. Ansible — Advanced Execution
In this chapter, we will learn what is advanced execution with Ansible.
How to Limit Execution by Tasks
This is a very important execution strategy where one needs to execute only one execution
and not the entire playbook. For example, suppose you only want to stop a server (in
case a production issue comes) and then post applying a patch you would like to only start
the server.
Here in original playbook stop and start were a part of different roles in the same playbook
but this can be handled with the usage of tags. We can provide different tags to different
roles (which in turn will have tasks) and hence based on the tags provided by the executor
only that specified role/task gets executed. So for the above example provided, we can
add tags like the following:
- {role: start-tomcat, tags: [‘install"]}}
The following command helps in using tags:
ansible-playbook -i hosts --tags “install” -vw
With the above command, only the start-tomcat role will be called. The tag provided is
case-sensitive. Ensure exact match is being passed to the command
How to Limit Execution by Hosts
There are two ways to achieve the execution of specific steps on specific hosts. For a
specific role, one defines the hosts - as to which specific hosts that specific role should be
run.
Example
= hosts:
environment: “{{your env}}"
pre_tasks:
= debug: msg="Started deployment. Current time is
{{ansible_date_time.date}} {{ansible_date_time.time}} *
roles:
- {role: , tags: [‘']}
Gyereristepsins zAnsible
post_tasks:
= debug: msg="Completed deployment. Current time is
{{ansible_date_time.date}} {{ansible_date_time.time}}"
= hosts:
pre_tasks:
- debug: msg="started.... Current time is {{ansible_date_time.date}}
({ansible_date_tine.tine}) *
roles:
- {role: , tags: [‘' ]}
post_tasks:
= debug: msg="Completed the task.. Current time is
{{ansible_date_time.date}} {{ansible_date_time.time)
As per the above example, depending on the hosts provided, the respective roles will only
be called. Now my hosts A and B are defined in the hosts (inventory file).
Alternate Solution
A different solution might be defining the playbook's hosts using a variable, then passing
in a specific host address via --extra-vars:
# file: user.yml (playbook)
= hosts: "{{ target }}*
user:
playbook contd...
Running the Playbook
ansible-playbook user.yml --extra-vars “target="*
If {{ target }} isn't defined, the playbook does nothing. A group from the hosts file can
also be passed through if need be. This does not harm if the extra vars is not provided.
Playbook targeting a single host
$ ansible-playbook user.yml --extra-vars “target=" --list-
hosts
Qerersepsine 29. Ansible — Troubleshooting
‘The most common strategies for debugging Ansible playbooks are using the modules given
below:
Debug and Register
These two are the modules available in Ansible. For debugging purpose, we need to use
the two modules judiciously. Examples are demonstrated below.
Use Verbosity
With the Ansible command, one can provide the verbosity level. You can run the
commands with verbosity level one (-v) or two (-wv).
Important Points
In this section, we will go through a few examples to understand a few concepts.
If you are not quoting an argument that starts with a variable. For example,
vars:
age_path: {{vivek.name}}/demo/
{{vivek.name}}
This will throw an error.
Solution
vars:
age_path:
{{vivek.name}}/demo/ - marked in yellow is the fix
How to use register > Copy this code into a yml file say test.yml and run it
a#Tsting
= hosts: tomcat-node
tasks:
= shell: /usr/bin/uptime
register: myvar
Gyereristepsins 53Ansible
= name: Just debugging usage
debug: var=myvar
When I run this code via the command Ansible-playbook -i hosts test.ymi, I get the output
as shown below.
If you see the yaml , we have registered the output of a command into a variable ~ myvar
and just printed the output.
The text marked yellow, tells us about property of the variable ~myvar that can be used
for further flow control. This way we can find out about the properties that are exposed of
a particular variable. The following debug command helps in this.
$ ansible-playbook -i hosts test.yml
PLAY [toncat-node]
TASK [Gathering Facts]
Monday @5 February 2018 17:33:14 +0530 (@:00:00.051) 0:00:00.051 t#44444
ok: [servera]
TASK [command]
Monday @5 February 2018 17:33:16 +0530 (0:00:01.697) 0:00:01.748 *#44444
changed: [server1]
TASK [Just debugging usage]
Monday @5 February 2018 17:33:16 +0530 (@:00:00.226) 0:00:01.974 *#44944
ok: [servert] => {
wmyvar": {
“changed”: true,
“cmd
/usr/bin/uptime" ,
:00.011306",
2018-02-05 17:33:16.424647",
“delta”: "
tutorielepoint 34Ansible
ro": @,
start": "2018-02-05 17:33:16.413341",
stderr”:
‘stderr_lines": [],
stdout": " 17:33:16 up 7 days, 35 min, 1 user, load average: 0.18,
0.15, 0.14",
“stdout_lines": [
"17:33:16 up 7 days, 35 min, 1 user, load average: 0.18, 0.15,
0.14"
PLAY RECAP
server
changed=1 _unreachable-8 —failed=0
Common Playbook Issues
In this section, we will learn about the a few common playbook issues. The issues are:
= Quoting
* Indentation
Playbook is written in yaml format and the above two are the most common issues in
yaml/playbook.
Yami does not support tab based indentation and supports space based indentation, so
one needs to be careful about the same.
Note - once you are done with writing the yaml , open this site(https://editor.swagger.io/)
and copy paste your yaml on the left hand side to ensure that the yaml compiles properly.
This is just a tip.
‘Swagger qualifies errors in warning as well as error.
Qerersepsine 3