0% found this document useful (0 votes)
19 views91 pages

Ansible Training

Uploaded by

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

Ansible Training

Uploaded by

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

Ansible Training

Quiz - Pretest
• Please open this page for pre-test quiz
• https://forms.gle/pZ1ybsegpioKRJvw9
Get Access To Lab
• Connect to Wi-Fi: IBM-JTI
• Login with your VPN Username & Password
• Enter this command on cmd as administrator (Windows)
• route ADD 192.168.201.0 MASK 255.255.255.0 192.168.200.1
• Enter this command on terminal (MacOS)
• sudo route –n add -net 192.168.201.0/24 192.168.200.1
• Connect to JTI VPN (must have access first)
• Alternatively, create four CentOS 8 VM in your own laptop using
VirtualBox or similar software, connect them in one network (private
NAT)
Lab Access
• Each person will have 4 VMs
• Control Node
• Managed Node 1 -> ansible1
• Managed Node 2 -> ansible2
• Managed Node 3 -> ansible3
• Person 1 = ansible-training01-04
• Person 2 = ansible-training05-08
• IP Address: 192.168.201.1xx
• Where xx is the hostname number
Managed
Person Control Node Node
1 01 02 03 04
2 05 06 07 08
3 09 10 11 12
4 13 14 15 16
5 17 18 19 20
6 21 22 23 24
7 25 26 27 28
8 29 30 31 32
9 33 34 35 36
10 37 38 39 40
11 41 42 43 44
12 45 46 47 48
13 49 50 51 52
14 53 54 55 56
15 57 58 59 60
16 61 62 63 64
17 65 66 67 68
18 69 70 71 72
19 73 74 75 76
Lessons
• Installing Ansible
• Set Up Ansible Managed Environment
• Using Ad Hoc Commands
• Getting Started With Playbooks
• Working With Variables and Facts
What is Ansible?
• IT Automation System
• Configure System
• Deploy Software
• Rolling Update
• Many more
What is Ansible?
• Scripts on Steroids
• If we want to automate a task, we can script it and run it
• But what if we are running it on 10 server?
• No problem, we can log-in to each machine and it will take a short time
• But what about 100 servers? 500 servers? 1000 servers?
Ansible Concept

• One Control Node that talks to many machines using SSH


• Playbook will always give the same result, even if the current condition is different
• The managed nodes will need python because ansible will generate a python script
and run it inside the nodes
Lesson 1
Installing Ansible
Installing Ansible
• Ansible can be installed from the package repository, or using
Python’s pip installer
• In this course, we will use the pip method
Installing Ansible
• Example: 4 VMs
• Control Node – ansible-control
• Managed Node 01 – ansible1
• Managed Node 02 – ansible2
• Managed Node 03 – ansible3
• Ansible cannot be used with root account
• Must create any normal user (but same across all nodes) and set a
sudoers file for administrative tasks
• Set passwordless ssh from control nodes to managed nodes
Installing Ansible
1. Create a dedicated Ansible user
2. Create appropriate sudo permission for Ansible
3. Set up passwordless SSH between the control nodes and the
managed nodes
4. Install python and ansible
Installing Ansible
• All nodes:
• adduser ansible
• passwd ansible
• Control Node
• echo “ansible ALL=(ALL) NOPASSWD: ALL” > /etc/sudoers.d/ansible
• scp /etc/sudoers.d/ansible [other nodes]:/etc/sudoers.d/
• su ansible
• ssh-keygen
• ssh-copy-id [other nodes]
• sudo yum install -y python3
• pip3 install ansible --user
Lesson 2
Set Up Ansible
Environment
Inventory
• Usually, machines in the network can be referred via DNS or
/etc/hosts
• In Ansible, the list of machines are referred in an inventory file
• There are two kinds of inventory:
• Static Inventory
• Dynamic Inventory
Static Inventory
• A static inventory is a list of hostnames and IP Addresses that can be
managed by Ansible
• You can group multiple hosts, to make it easier to refer multiple hosts
at once
• A host can be a member of multiple groups
• It is also possible to make a nested group
• Ranges can be used, examples:
• Server[1:20] = Server1, Server2, Server3, ...., Server20
• 192.168.[4:5].[0:255] = Two Class C Subnets from 192.168.4.0 – 192.168.5.255
Inventory File Locations
• /etc/ansible/hosts is the default location, but it’s not used a lot
• Alternative location can be set through the ansible.cfg config file
• Or, run ansible with -i [inventory] option to specify which inventory
file to be used
• Common Practice is to put inventory in current project directory
(more on this later)
• Everything you do with Ansible, you separate it between projects
Example of Static Inventory file
[webservers]  group
web1.example.com
web2.example.com

[fileservers]  group
file1.example.com
file2.example.com
file3.example.com

[servers:children]  nested group


webservers
fileservers
Example Usage of Host Groups
• Functional Host Groups
• Web
• LAMP
• Regional Host Groups
• Europe
• America
• Asia
• PrimaryDC
• SecondaryDC
• Staging Host Groups
• Test
• Development
• UAT
• Production
Creating Inventory File
• Control node
• Create a project directory; example: install
mkdir install
• Create a new inventory file
vi inventory
Creating Inventory File
[web]
ansible1

[db]
ansible2
Testing The Inventory File
• ansible -i inventory all --list-hosts
• ansible -i inventory ungrouped --list-hosts
• No ungrouped hosts in the inventory file
• ansible all --list-hosts
• No inventory were specified (by default it will look at /etc/ansible/hosts)
Dynamic Inventory
• Static inventory is nice, but when we have a big environment, it will
be time consuming to maintain it
• Dynamic Inventory that can be used to discover inventory in dynamic
environments, such as cloud
• Many community-provided inventory scripts are available
• These scripts are used in the same way we use the Static Inventory,
but they must have execute permission
• You can easily write dynamic inventory scripts too
• https://github.com/ansible/ansible/tree/devel/contrib/inventory
Ansible Configuration Files
• ansible.cfg
[defaults]
inventory = inventory  Look for inventory file named “inventory” in current working directory
remote_user = ansible  User that ansible use for ssh
host_key_checking = false  Disable the checks for ssh keys so ansible is more tolerant

[privilege_escalation]
become = True  Run task as somebody else
become_method = sudo  Method to do the privilege escalation
become_user = root  Target user to become
become_ask_pass = False  Do not ask for password when changing user
• Settings are organized into two sections
• [defaults] sets the default settings
• [privilege_escalation] specifies how Ansible runs commands on managed hosts
Connecting to Remote Hosts
• The default protocol to connect to the remote host is SSH
• Key based authentication is the common approach, but you can also use
password based auth
• To generate SSH keys, use ssh-keygen and use ssh-copy-id to copy the public
key to the managed hosts
• There are other methods as well:
• To manage Windows, use ansible_connection: winrm and ansible_port: 5986
• But if you are taking RHCE exam, Windows management is not part of the
objectives
Escalating Privileges
• sudo is the default mechanism, su can also be used but it’s
uncommon
• Password can also be asked for, but it’s more common to do a
password-less escalation
• echo “ansible ALL=(ALL) NOPASSWD: ALL” > /etc/sudoers.d/ansible
Localhost connection
• Ansible has an implicit localhost entry to run ansible commands
• Usually it’s the control node itself
• When connecting to localhost, the default become settings aren’t
going to be used, the account that ran the ansible command would be
used instead
• Ensure that the user has appropriate permission to sudo
Managing Ansible Config Files
• The ansible.cfg file is considered in order of precedence:
• /etc/ansible/ansible.cfg (default)
• ~/.ansible.cfg (if exists, will replace the default configured above)
• ./ansible.cfg (configuration in the current directory, will always take precedence
if exists)
• If ANSIBLE_CONFIG environment variable exists to refer to a specific
config file, then this will have the highest priority
• To check which file is being used, run ansible --version
• It makes more sense to put Ansible configuration in the project directory
because when you are managing Linux and Windows machine, the
configuration file will be different
Lab 2
• Create an environment with this requirement
• Set up a user named ansible management tasks on managed hosts: ansible1
& ansible2
• Inventory is set up on control host
• ansible.cfg configured with sudo privilege escalation
• SSH-key based login has been configured on ansible1 & ansible 2
• Skip ansible3 for now because we will use it in the next lab
Lesson 3
Using Ad Hoc
Commands
Using Ad Hoc Commands
• To run task on Ansible, typically we will use Playbooks
• A playbook is a YAML file in which tasks can be defined
• But for some tasks, a playbook is too complicated and too much work
• In such cases, we will use an ad-hoc command
• Ad hoc commands are also useful for testing if your playbooks are
successful
Understanding Ansible Modules
• As previously shown, modules is the key function in Ansible
• Ansible comes with a lot of modules that allow you to perform specific tasks on
managed hosts
• When using Ansible, you’ll always use modules to tell Ansible what you want it to
do, whether it’s in ad hoc commands or in a playbook
• By default Ansible has provided many modules, but you can also develop your own
• To list available modules, use this command: ansible-doc –l
• ansible-doc is like manpage for ansible modules, all the arguments needed for
each modules are explained there
• Modules are idempotent, meaning that when running them, it will give the same
result, if a task is already done, it won’t touch it.
Ad Hoc Commands Ingredients
• The basic structure is ansible hosts –m module [-a ‘module arguments’] [-i
inventory]
• The hosts part specifies on which host the command should be performed
• The module part indicates which ansible module to use; following the modules,
you can specify the module argument
• Inventory needs only be specified in the command if it’s not already exists
• Example:
• ansible all –m user –a “name=lisa”
• Run ansible in all host, run module user, with an argument name, value lisa
• It will create a user lisa in all ansible host (module user is used to create user)
• Verification: ansible all –m command –a “id lisa”
• It will run a shell command “id lisa” in all the hosts (module command is used to run shell commands in
each target machine)
Understanding Ansible Modules
• ansible all –m user –a “name=lisa state=absent”
• What does this command do?
• Verify the result with: ansible all –m command –a “id lisa”

• ansible all –m ping


• What does this command do?
Using ansible-doc To Get Module
Documentation
• ansible-doc shows you documentation of modules
• Use ansible-doc –l to get the list of all modules
• There are a lot of modules because every vendor who wants to get their products to
work with Ansible are providing their own modules
• For specific module, you can use this command:
ansible-doc modulename
• Example
• ansible-doc user
• The argument that starts with ‘=‘ is a mandatory argument, everything else is optional
• At the end of the document we can also see an example on how to use the module in
a YAML notation to be used in a playbook
Understanding Module Status
• Modules are very actively developed by the community, and the
status field in documentation indicate the current status
• stableinterface: the module is stable and safe to use
• preview: the module is in tech preview; keywords may change in the future
• deprecated: the module should not be used anymore, will be removed in the
future
• removed: the module is already removed, and it is there to help users
migrate to its new replacement
• Ansible is very dynamic, some old playbooks may stop working in future ansible release
because of changes in the modules. This documentation will help to fixN these problems.
Understanding Module Support Status
• The field supported_by in the documentation indicates who
maintains and responsible for supporting a module
• core: Maintained by core Ansible developers
• curated: Primarily supported by partners in the community, but is reviewed
by core developers
• community: Only supported by the community
Essential Ansible Modules
• ping: verifies the ability to log in and that python is installed
• ansible all –m ping
• service: checks if a service is currently running
• ansible all –m service -a “name=httpd state=started”
• command: runs a command, but not through a shell (no environment variable)
• ansible all –m command –a “/sbin/reboot –t now”
• shell: runs a command through shell (with environment variable)
• ansible all –m shell –a set
• raw: runs a command on a remote host without having to install python (example:
devices that doesn’t have python out of the box, or haven’t been installed)
• copy: copies a file to the managed hosts
• ansible all –m copy –a ’content=“Hello World” dest=/etc/motd’
Lab 3
• Use ping module in ad hoc command to verify that all hosts have
been set up successfully
• Install python using ad-hoc command on all the managed hosts,
including those that doesn’t have python & ansible yet

Tip:
Don’t forget to set ansible.cfg & inventory!
Use ansible instead of manual SSH
Solution – Lab 3
• Create config file
vi /home/ansible/lab3/ansible.cfg

[defaults]
inventory=inventory
remote_user=ansible
host_key_checking=false

[privilege_escalation]
become=true
become_user=root
become_method=sudo
become_ask_pass=false
Solution – Lab 3
• Create inventory file
vi /home/ansible/lab3/inventory

[web]
ansible1

[db]
ansible2

ansible3
Solution – Lab 3
• Do the adhoc commands
• ansible –all –m ping
• ansible3 will fail
• ansible -u root –i inventory ansible3 --ask-pass -m raw –a “yum install
python3 –y”
• It will ask for SSH password
Lesson 4
Ansible Playbooks
Why Playbooks?
• Ad-hoc commands can be used to run one or few tasks
• Ad-hoc commands are convenient to test, or when a complete
managed infrastructure isn’t set up yet
• Ansible Playbooks are used to run multiple tasks against managed
hosts in a scripted way
• In Playbooks, one or multiple plays are started
• Each play runs one or more tasks
• In these tasks, different modules are used to perform the actual work
• Playbooks are written in YAML, with .yml or .yaml as their extension
YAML? What is That?
• An easy to read format to structure tasks / items that need to be
created
• In YAML files, items are using indentation with white spaces to
indicate the structure of data
• Data Elements at the same level should have the same indentation
• Child items are indented more than the parent items
• No strict requirement about the amount of spaces, but two spaces is
common
Example Playbook in YAML
---
- name : deploy vsftpd
hosts: ansible2.local
tasks:
- name: install vsftpd
yum: name=vsftpd
- name: enable vsftpd
service: name=vsftpd enabled=true
- name: create readme file
copy:
content: “free downloads for everybody!”
dest: /var/ftp/pub/README
force: no
mode: 0444

Running Playbook
• Use this command: ansible-playbook filename.yml
• A successful run requires the inventory and become parameters to be
set correctly, and also requires access to an inventory file
• The output of the ansible-playbook command will show what exactly
has happened
• Playbooks in general are idempotent; meaning that running the same
playbook again and again should produce the same result
• Warning: there are no easy way to undo changes made by a playbook
Example Output
[ansible@ansible-control lab4]$ ansible-playbook vsftpd.yml
PLAY [deploy vsftpd] ***********************************************************
TASK [Gathering Facts] *********************************************************
ok: [ansible2]
TASK [install vsftpd] **********************************************************
changed: [ansible2]
TASK [enable vsftpd] ***********************************************************
changed: [ansible2]
TASK [create readme file] ******************************************************
changed: [ansible2]
PLAY RECAP *********************************************************************
ansible2 : ok=4 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Example Output 2
[ansible@ansible-control lab4]$ ansible-playbook vsftpd.yml
PLAY [deploy vsftpd] ***********************************************************
TASK [Gathering Facts] *********************************************************
ok: [ansible2]
TASK [install vsftpd] **********************************************************
ok: [ansible2]
TASK [enable vsftpd] ***********************************************************
ok: [ansible2]
TASK [create readme file] ******************************************************
ok: [ansible2]
PLAY RECAP *********************************************************************
ansible2 : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Verifying Playbook Syntax
• ansible-playbook --syntax-check filename.yml will perform a syntax check
• Use –v[vvv] to increase output verbosity
• -v will show task result
• -vv will show task results and configuration
• -vvv also shows information about connections to managed hosts
• -vvvv adds information about plug-ins, users that being used to run scripts, and
names of scripts that are executed
• Using –C option to perform a dry run, tries to do the playbook without
doing anything
• But if there is a dependency between the current task and the next task, it may
not run correctly
Writing A Multiple-Play Playbooks:
What is a Play?
• A play is a series of tasks that are executed against selected hosts from the
inventory, using specific credentials
• Using multiple plays allows running tasks on different hosts, using different
credentials from the same playbook
• Within a play definition, escalation parameters can be defined:
• remote_user: the name of the remote user
• become: to enable or disable privilege escalation
• become_method: to allow using alternative escalation solution
• become_user: The target user used for privilege escalation
• The parameters are similar with those in the ansible.cfg, but the parameters
defined in the playbook will take precedence before ansible.cfg
Example:
---
- name: enable webserver
hosts: ansible1
tasks:
- name: install httpd and firewalld
yum:
name:
- httpd
- firewalld
state: latest
- name: install welcome page
copy:
content: "hello world”
dest: /var/www/html/index.html
- name: start web services
service:
name: httpd
enabled: true
state: started
- name: start firewalld services
service:
name: firewalld
enabled: true
state: started
- name: open http port in firewalld
firewalld:
service: http
permanent: true
state: enabled
immediate: yes

- name: test webserver access


hosts: localhost
become: no
tasks:
- name: connect to the webserver
uri:
url: http://ansible1
return_content: yes
status_code: 200
...
Lab 4
• Write a Playbook to install HTTPD package on ansible2
• Ensure that the service has been started and firewall is opened
• Also create a file in /var/www/html/index.html with some text
• Create a separate playbook to undo all those modifications
• In ansible, there is no easy undo, so you must write a new playbook that does
the opposite of the changes that you have done.

Tip: Use ansible-doc for getting references on how to use Ansible modules!
Solution – Install HTTPD
---
- name: enable web server
hosts: ansible2
tasks:
- name: install httpd
yum:
name: httpd
state: latest
- name: enabled httpd service
service:
name: httpd
state: started
enabled: true
- name: open firewall port
firewalld:
service: http
state: enabled
immediate: true
- name: create welcome message
copy:
content: Welcome to Ansible Demo
dest: /var/www/html/index.html
force: no
mode: 0644
...
Solution – Undo Changes
---
- name: disable web server
hosts: ansible2
tasks:
- name: remove welcome message
file:
path: /var/www/html/index.html
state: absent
- name: close firewall port
firewalld:
service: http
state: disabled
immediate: true
- name: disable httpd service
service:
name: httpd
state: stopped
enabled: false
- name: remove httpd
yum:
name: httpd
state: removed
...

Verify: ansible ansible2 –m shell –a ”rpm –qa | grep http”


Lesson 5
Working With Variables
and Facts
Understanding Variables
• Case:
• Say you are managing an environment with more than one Linux
Distribution; e.g. Ubuntu and Red Hat
• You are writing a playbook to install a web server, with the package
module
• The problem is, the web server package in Ubuntu and Red Hat are
different.
• How can you make that playbook work with two different
environment like this?
Understanding Variables
• A variable is a label that is assigned to a specific value to make it easy
to refer to that value throughout the playbook
• Variable can be defined at different levels
• A fact: special type of variable, that refers to the current state of the
system that are managed by Ansible
• Variables are particularly useful when dealing with managed hosts
where specifics are different:
• Set a variable web_service on Ubuntu and Red Hat
• Refer to that variable web_service instead of specific package name
Using Variables
• Variables can be set at different levels
• In a playbook
• In inventory (deprecated)
• In inclusion files
• Variables names have some requirements:
• The name must start with a letter
• Variable names can only contain letters, numbers, and underscores
Defining Variables
• Variables can be defined in a vars block in the beginning of a playbook

- hosts: all
vars:
web_package: httpd
But, a better way to put the variables is to put it in a separate variable file, which will
be included from the Playbook

- hosts: all
vars_files:
- vars/users.yml
Defining Variables
• After defining variables, it can be used later in the playbook
• Notice that order does matter! The variable must be defined first
before the task
• Refer to the variable as {{ web_server }}
• If the variable is the only value, quotes are mandatory!
Example
---
- name: create a user using a variable
hosts: all
vars:
user: lisa
tasks:
- name: create a user {{ user }}
user:
name: "{{ user }}"
...

P.S: this is useless, for creating one user, just ditch the variable.
Understanding Variable Precedence & Scope
• Variables can be set with different types of scope
• Global scope: variable set from the inventory or the command line
• Play scope: applied when it is set from a play
• Host scope: This is applied when set in the inventory or using a host variable
inclusion file
• When the same variable is set at different levels, the most specific
level gets precedence
• When a variable is set from a command line, it will overwrite anything
else
• ansible-playbook site.yml –e “web_package=apache”
Understanding Built-In Variables
Some variables are built in and cannot be used for anything else:
• hostvars
• inventory_hostname
• inventory_hostname_short
• groups
• group_names
• ansible_check_mode
• ansible_play_batch
• ansible_play_hosts
• ansible_version

Be careful when naming variables! Variables like groups or group_names may be considered when you are
writing a playbook, take note that they are a built-in variables and you should be using other names such as
mygroups
Using Host Variables
• Variables can be assigned to hosts and to groups of hosts
• The old way of doing so is through inventory, but this is now
deprecated, because it mixes two types of information in one file
• Instead, you should use two directories to populate host and group
variables
Defining Host Variables Through Inventory
• A variable can be assigned directly to a host
[servers]
web1.example.com web_package=httpd

• Alternatively, variables can be set for host groups


[servers:vars]
web_package=httpd
Using Include Files
• To define host and host group variables, directories should be created
in the current project directory
• Use projectdir/host_vars/web1.example.com to include host specific
variables
• Use projectdir/group_vars/webservers to include host group specific
variables
• Notice that you don’t have to define the variables inside your
playbook, they will be defined automatically
Example
• Suppose a project directory is laid out like this:
 ansible.cfg
 group_vars
lamp
inventory
site.yml

• group_vars/lamp content:
web_package: httpd
web_service: httpd
Example
• site.yml content:
---
- name: configure web services
hosts: lamp
tasks:
- name: this is the {{ web_package }} package
debug:
msg: "Installing {{ web_package }}"
- name: this is the {{ web_service }} package
debug:
msg: "Starting {{ web_service }} "
...
Understanding Multi-Valued Variables
• Arrays can be used as Variables
• When doing so, with_items can be used to refer to all values of the
variable
• Specific items in the array can be referred to using dotted notation
• This is common in Ansible facts
Example
• An example yaml file
---
- name: show arrays
hosts: ansible1.example.com
vars_files:
- vars/users
tasks:
- name: print array values
debug:
msg: "User {{ users.linda.username }} has homedirectory {{ users.linda.homedir }} and
shell {{users.linda.shell}} "
...
Example
• vars/users
users:
linda:
username: linda
homedir: /home/linda
shell: /bin/bash
lisa:
username: lisa
homedir: /home/lisa
shell: /bin/bash
anna:
username: anna
homedir: /home/anna
shell: /bin/bash
Using Ansible Vault – Dealing with Sensitive
Data
• Some modules require sensitive data to be processed
• This may include: webkeys, passwords, etc
• To process sensitive data in a secure way, Ansible vault can be used
• Ansible Vault is used to encrypt and decrypt files
• Command used: ansible-vault
Create an Encrypted File
• To create an encrypted file, use ansible-vault create playbook.yml
• This command will prompt for a new vault password, and opens the file in vi
for further editing
• Alternatively, a vault password file can be used, but the password file must be
protected in another way:
ansible-vault create --vault-password-file=vault-pass playbook.yml
• To view vault encrypted file, use ansible-vault view playbook.yml
• To edit, use ansible-vault edit playbook.yml
• Use ansible-vault encrypt playbook.yml to encrypt an existing file, and use
ansible-vault decrypt playbook.yml to decrypt it
• To change the password on an existing file, use ansible-vault rekey
Using Playbooks with Vault
• To run a playbook that accesses Vault encrypted files, you need to use
the --vault-id @prompt option to be prompted for password
• Alternatively, you can store the password as a single line string in a
password file, and access that using the --vault-password-file=vault-
file option
Managing Vault Files
• When setting up projects with Vault encrypted files, it makes sense to use separate
files to store encrypted and non-encrypted variables
• To store a host or host-group related variable files, you can use the following structure:

|-group_vars
| |--dbservers
| |- vars
| |- vault

• This replaces the solution that was discussed earlier, where all variables are stored in a
file with the name of the host or host group
Example
• create-user.yml
---
- name: create a user
hosts: all
vars_files:
- secret.yml
tasks:
- name: create user
user:
name: "{{ username }}"
password: "{{ pwhash }}"
...
Example
• ansible-vault create secret.yml
• Enter new password & confirm password

username: lisa
pwhash: password

• ansible-playbook --ask-vault-pass create-user.yml


• But this way password would still be asked every time you run a playbook
Example
• You can also put password inside a file
• But make sure that only a certain user have read permission for the password
file!
• echo “password” > vault-pass
• chmod 600 vault-pass
• ansible-playbook –vault-password-file=vault-pass create-user.yml
Working With Facts
• Ansible Facts are variables that are automatically set and discovered
by Ansible on managed hosts
• Facts contain information about the managed hosts that can be used
in conditionals
• For instance, before installing a software, you can check what kernel
version is running on the managed hosts, which Linux distro, etc
Managing Fact Gathering
• By default, all playbook perform fact gathering before running the
actual plays
• You can run fact gathering in ad-hoc command using the setup
module
• To show facts, you can use debug module to print the value of the
ansible_facts variable
• Notice that in facts, a hierarchical relation is shown where you can
use the dotted format to refer to a fact, more specifically.
• To show all facts of managed host: ansible –m setup all
Managing Fact Gathering In A Playbook
---
- name: show facts
hosts: all
tasks: all
- name: print facts
debug:
var: ansible_facts
...
• This will show the content of variable ansible_facts, but it’s not fun right?
Managing Fact Gathering In A Playbook
---
- hosts: all
tasks:
- name: show IP address
debug:
msg: >
This host uses IP Address {{ansible_facts.default_ipv4_address}}
...
Working With Facts: Display Fact Names
• In older Ansible versions (2.4 and before), Ansible facts were stored as individual
variable, e.g. ansible_hostname and
• Starting from Ansible 2.5 and later, all facts are stored in one variable with the
name ansible_facts, and referring to specific facts this way:
• ansible_facts[‘hostname’] and ansible_facts[‘interfaces’]
• The old approach is referred to as “injecting facts as variables”, and this behavior
can be managed through the inject_facts_as_vars parameter
• Use inject_facts_as_vars=true in the [default] section of ansible.cfg to
specifically enable the old method
• This is only useful to run old playbooks that refer to facts as variables
Working With Facts: Turning Off Fact
Gathering
• If you are managing a lot of hosts at the same time, it could impact
the fact gathering speed
• In that case, disabling fact gathering may seriously speed up
playbooks, if you don’t need to deal with facts in your playbook
• Put gather_facts: no in the play header to disable
• Even if fact gathering is disabled, you can easily enable it again by
running the setup module in a task
Working With Facts: Display A Specific Fact
With Filter
• ansible –m setup –a ‘filter=ansible_default_ipv4’ all
• This will only display the “ansible_default_ipv4” fact
ansible1 | SUCCESS => {
"ansible_facts": {
"ansible_default_ipv4": {
"address": "192.168.201.36",
"alias": "ens192",
"broadcast": "192.168.201.255",
"gateway": "192.168.201.1",
"interface": "ens192",
"macaddress": "00:50:56:94:3a:17",
"mtu": 1500,
"netmask": "255.255.255.0",
"network": "192.168.201.0",
"type": "ether”
},
"discovered_interpreter_python": "/usr/libexec/platform-python”
},
"changed": false
}
To refer to a specific child object, use a dotted notation e.g.: ansible_default_ipv4.address. But this won’t work in a filter as shown
above
Using Custom Facts
• Custom facts allow administrators to dynamically generate variables
which are stored as facts
• Custom Facts are stored in an ini or json file in the /etc/ansible/facts.d
directory on the managed hosts
• The name of these files must end in .fact
• Custom facts are stored in ansible_facts.ansible_local variable
• Use ansible hostname –m setup –a “filter=ansible_local” to display
local facts
• Notice how fact filename and label are used in the fact
Custom Facts Example File: localfacts.yaml
[localfacts]
package = vsftpd
service = vsftpd
state = started
Lesson 5 Lab
• Create a Playbook that will first define local facts on the file servers.
These facts should define the name of the smbd service, and the
samba package
• Ensure the first play copies these facts to the file servers
• Next, in the same playbook, use a second play that will install and
enable the smbd server
Lab 5 - Solution

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy