Tags Archives: Ansible

How to Install Ansible on Ubuntu

The procedure for installing Ansible on Ubuntu versions 18.04, 20.04, and 22.04 LTS is as follows

 

 

First, remove the default version supplied by the official Ubuntu repository:

 

sudo apt remove ansible
sudo apt –purge autoremove

 

Next, update the Ubuntu repository and apply all current patches:

 

sudo apt update
sudo apt upgrade

 

Then install the software-properties-common package on Ubuntu and enable PPA support for the ansible repository:

 

sudo apt -y install software-properties-common
sudo apt-add-repository ppa:ansible/ansible

 

Next install the latest version of Ansible for Ubuntu:

 

sudo apt install ansible

 

 

Finally, set up Ansible bash completion support:

sudo apt install python3-argcomplete
sudo activate-global-python-argcomplete3

 

 

You should now be able to run ansible-playbook and other ansible commands.

 

 

 

Continue Reading

Using Ansible Molecule

Prerequisites for installing Molecule

 

You need to have Python 3, venv, and Docker installed and correctly configured.

 

First create a virtual environment to test Ansible with Molecule.

 

Login as your non-root user and create a new virtual environment:

 

python3 -m venv my_env

 

(molecule-venv) kevin@asus:~/DATAVOLUME/ANSIBLECODE$ python3 -m venv my_env
(molecule-venv) kevin@asus:~/DATAVOLUME/ANSIBLECODE$

 

 

Activate it to ensure your actions are restricted to that environment:

 

source my_env/bin/activate

 

(molecule-venv) kevin@asus:~/DATAVOLUME/ANSIBLECODE$ source my_env/bin/activate
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE$

 

 

Next, in this activated environment, install the wheel package. this provides the bdist_wheel setuptools extension that pip requires to install Ansible:

 

python3 -m pip install wheel

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE$ python3 -m pip install wheel
Collecting wheel
Using cached wheel-0.40.0-py3-none-any.whl (64 kB)
Installing collected packages: wheel
Successfully installed wheel-0.40.0
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE$

 

You can now install molecule and docker with pip.

 

Ansible will be automatically installed as a dependency for Molecule:

 

python3 -m pip install molecule docker

 

description of the packages that will be installed:

 

molecule: the main Molecule package you will use to test roles. Installing molecule automatically installs Ansible, plus the dependencies required, and enables the use of Ansible playbooks for executing roles and tests.

 

docker: This is a Python library version used by Molecule to interface with Docker, as this is used by Molecule as the default driver.

 

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE$ python3 -m pip install molecule docker
Collecting molecule
Using cached molecule-5.0.1-py3-none-any.whl (239 kB)
Collecting docker
Downloading docker-6.1.3-py3-none-any.whl (148 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 148.1/148.1 KB 2.0 MB/s eta 0:00:00
Collecting ansible-core>=2.12.10
Using cached ansible_core-2.15.0-py3-none-any.whl (2.2 MB)
Collecting enrich>=1.2.7

 

… .. .. … ..

Successfully installed Jinja2-3.1.2 MarkupSafe-2.1.3 PyYAML-6.0 ansible-compat-3.0.2 ansible-core-2.15.0 arrow-1.2.3 attrs-23.1.0 binaryornot-0.4.4 certifi-2023.5.7 cffi-1.15.1 chardet-5.1.0 charset-normalizer-3.1.0 click-8.1.3 click-help-colors-0.9.1 cookiecutter-2.1.1 cryptography-41.0.1 docker-6.1.3 enrich-1.2.7 idna-3.4 jinja2-time-0.2.0 jsonschema-4.17.3 markdown-it-py-2.2.0 mdurl-0.1.2 molecule-5.0.1 packaging-23.1 pluggy-1.0.0 pycparser-2.21 pygments-2.15.1 pyrsistent-0.19.3 python-dateutil-2.8.2 python-slugify-8.0.1 requests-2.31.0 resolvelib-1.0.1 rich-13.4.1 six-1.16.0 subprocess-tee-0.4.1 text-unidecode-1.3 urllib3-2.0.2 websocket-client-1.5.2
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE$

 

 

Now your environment is set up you can create a basic role in Molecule to test an installation of Apache.

 

This role will create the directory structure and runs some initial tests, and specifies Docker as the driver for Molecule.

 

Create a new role called ansible.apache:

 

molecule init role -r ansible.apache

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule$ molecule init role ansible.apache
INFO Initializing new role apache…
No config file found; using defaults
– Role apache was created successfully
localhost | CHANGED => {“backup”: “”,”changed”: true,”msg”: “line added”}
INFO Initialized role in /media/kevin/STORAGEVOLUMELUKS/DATAVOLUME/ANSIBLECODE/molecule/apache successfully.
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule$

 

 

Change into the directory of the newly created role:

 

cd apache

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ ls -l
total 40
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 defaults
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 files
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 handlers
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 meta
drwxrwxr-x 3 kevin kevin 4096 Jun 5 16:20 molecule
-rw-rw-r– 1 kevin kevin 1328 Jun 5 16:20 README.md
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 tasks
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 templates
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 tests
drwxrwxr-x 2 kevin kevin 4096 Jun 5 16:20 vars
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$

 

 

 

Test the default role to check if Molecule has been set up properly:

 

molecule test

 

You will see output listing each of the default test actions. Before starting the test, Molecule validates the config file molecule.yml to check everything is in order.

 

It also prints this test matrix, which specifies the order of test actions:

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ molecule test
INFO default scenario test matrix: dependency, cleanup, destroy, syntax, create, prepare, converge, idempotence, side_effect, verify, cleanup, destroy
INFO Performing prerun with role_name_check=0…
INFO Set ANSIBLE_LIBRARY=/home/kevin/.cache/ansible-compat/d7e04c/modules:/home/kevin/.ansible/plugins/modules:/usr/share/ansible/plugins/modules
INFO Set ANSIBLE_COLLECTIONS_PATH=/home/kevin/.cache/ansible-compat/d7e04c/collections:/home/kevin/.ansible/collections:/usr/share/ansible/collections
INFO Set ANSIBLE_ROLES_PATH=/home/kevin/.cache/ansible-compat/d7e04c/roles:/home/kevin/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles
INFO Using /home/kevin/.cache/ansible-compat/d7e04c/roles/ansible.apache symlink to current repository in order to enable Ansible to find the role using its expected full name.
INFO Running default > dependency
WARNING Skipping, missing the requirements file.
WARNING Skipping, missing the requirements file.
INFO Running default > cleanup
WARNING Skipping, cleanup playbook not configured.
INFO Running default > destroy

 

PLAY [Destroy] *****************************************************************

 

TASK [Populate instance config] ************************************************
ok: [localhost]

 

TASK [Dump instance config] ****************************************************skipping: [localhost]

 

PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

 

INFO Running default > syntax

 

playbook: /media/kevin/STORAGEVOLUMELUKS/DATAVOLUME/ANSIBLECODE/molecule/apache/molecule/default/converge.yml
INFO Running default > create

 

PLAY [Create] ******************************************************************

 

TASK [Populate instance config dict] *******************************************
skipping: [localhost]

 

TASK [Convert instance config dict to a list] **********************************
skipping: [localhost]

 

TASK [Dump instance config] ****************************************************
skipping: [localhost]

 

PLAY RECAP *********************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0

 

INFO Running default > prepare
WARNING Skipping, prepare playbook not configured.
INFO Running default > converge

 

PLAY [Converge] ****************************************************************

 

TASK [Include ansible.apache] **************************************************

 

PLAY RECAP *********************************************************************

 

INFO Running default > idempotence

 

PLAY [Converge] ****************************************************************

 

TASK [Include ansible.apache] **************************************************

 

PLAY RECAP *********************************************************************

 

INFO Idempotence completed successfully.
INFO Running default > side_effect
WARNING Skipping, side effect playbook not configured.
INFO Running default > verify
INFO Running Ansible Verifier

 

PLAY [Verify] ******************************************************************

 

TASK [Example assertion] *******************************************************

ok: [instance] => {
“changed”: false,
“msg”: “All assertions passed”
}

 

PLAY RECAP *********************************************************************
instance : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

 

INFO Verifier completed successfully.
INFO Running default > cleanup
WARNING Skipping, cleanup playbook not configured.
INFO Running default > destroy

 

PLAY [Destroy] *****************************************************************

 

TASK [Populate instance config] ************************************************
ok: [localhost]

 

TASK [Dump instance config] ****************************************************
skipping: [localhost]

 

PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

 

INFO Pruning extra files from scenario ephemeral directory
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ 1

 

 

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ molecule list
INFO Running default > list

╷ ╷ ╷ ╷ ╷
Instance Name │ Driver Name │ Provisioner Name │ Scenario Name │ Created │ Converged
╶───────────────┼─────────────┼──────────────────┼───────────────┼─────────┼───────────╴
instance │ delegated │ ansible │ default │ false │ false
╵ ╵ ╵ ╵ ╵
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$

 

 

 

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ molecule converge
INFO default scenario test matrix: dependency, create, prepare, converge
INFO Performing prerun with role_name_check=0…
INFO Set ANSIBLE_LIBRARY=/home/kevin/.cache/ansible-compat/d7e04c/modules:/home/kevin/.ansible/plugins/modules:/usr/share/ansible/plugins/modules
INFO Set ANSIBLE_COLLECTIONS_PATH=/home/kevin/.cache/ansible-compat/d7e04c/collections:/home/kevin/.ansible/collections:/usr/share/ansible/collections
INFO Set ANSIBLE_ROLES_PATH=/home/kevin/.cache/ansible-compat/d7e04c/roles:/home/kevin/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles
INFO Using /home/kevin/.cache/ansible-compat/d7e04c/roles/ansible.apache symlink to current repository in order to enable Ansible to find the role using its expected full name.
INFO Running default > dependency
WARNING Skipping, missing the requirements file.
WARNING Skipping, missing the requirements file.
INFO Running default > create

PLAY [Create] ******************************************************************

TASK [Populate instance config dict] *******************************************
skipping: [localhost]

TASK [Convert instance config dict to a list] **********************************
skipping: [localhost]

TASK [Dump instance config] ****************************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0

INFO Running default > prepare
WARNING Skipping, prepare playbook not configured.
INFO Running default > converge

PLAY [Converge] ****************************************************************

TASK [Include ansible.apache] **************************************************

PLAY RECAP *********************************************************************

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$

 

 

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ molecule test
INFO default scenario test matrix: dependency, cleanup, destroy, syntax, create, prepare, converge, idempotence, side_effect, verify, cleanup, destroy
INFO Performing prerun with role_name_check=0…
INFO Set ANSIBLE_LIBRARY=/home/kevin/.cache/ansible-compat/d7e04c/modules:/home/kevin/.ansible/plugins/modules:/usr/share/ansible/plugins/modules
INFO Set ANSIBLE_COLLECTIONS_PATH=/home/kevin/.cache/ansible-compat/d7e04c/collections:/home/kevin/.ansible/collections:/usr/share/ansible/collections
INFO Set ANSIBLE_ROLES_PATH=/home/kevin/.cache/ansible-compat/d7e04c/roles:/home/kevin/.ansible/roles:/usr/share/ansible/roles:/etc/ansible/roles
INFO Using /home/kevin/.cache/ansible-compat/d7e04c/roles/ansible.apache symlink to current repository in order to enable Ansible to find the role using its expected full name.
INFO Running default > dependency
WARNING Skipping, missing the requirements file.
WARNING Skipping, missing the requirements file.
INFO Running default > cleanup
WARNING Skipping, cleanup playbook not configured.
INFO Running default > destroy

PLAY [Destroy] *****************************************************************

TASK [Populate instance config] ************************************************
ok: [localhost]

TASK [Dump instance config] ****************************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

INFO Running default > syntax

playbook: /media/kevin/STORAGEVOLUMELUKS/DATAVOLUME/ANSIBLECODE/molecule/apache/molecule/default/converge.yml
INFO Running default > create

PLAY [Create] ******************************************************************

TASK [Populate instance config dict] *******************************************
skipping: [localhost]

TASK [Convert instance config dict to a list] **********************************
skipping: [localhost]

TASK [Dump instance config] ****************************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=0 skipped=3 rescued=0 ignored=0

INFO Running default > prepare
WARNING Skipping, prepare playbook not configured.
INFO Running default > converge

PLAY [Converge] ****************************************************************

TASK [Include ansible.apache] **************************************************

PLAY RECAP *********************************************************************

INFO Running default > idempotence

PLAY [Converge] ****************************************************************

TASK [Include ansible.apache] **************************************************

PLAY RECAP *********************************************************************

INFO Idempotence completed successfully.
INFO Running default > side_effect
WARNING Skipping, side effect playbook not configured.
INFO Running default > verify
INFO Running Ansible Verifier

PLAY [Verify] ******************************************************************

TASK [Example assertion] *******************************************************
ok: [instance] => {
“changed”: false,
“msg”: “All assertions passed”
}

PLAY RECAP *********************************************************************
instance : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

INFO Verifier completed successfully.
INFO Running default > cleanup
WARNING Skipping, cleanup playbook not configured.
INFO Running default > destroy

PLAY [Destroy] *****************************************************************

TASK [Populate instance config] ************************************************
ok: [localhost]

TASK [Dump instance config] ****************************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

INFO Pruning extra files from scenario ephemeral directory
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$

 

 

 

 

Let’s now modify the role to configure Apache and firewalld.

 

 

Configuring Apache and Firewalld

 

First create a tasks file for the role which specifies the packages to install and services to be enabled.

 

These details are obtained from a variables file and template which will generate our default Apache index page.

 

 

cd to the molecule role apache directory and create a tasks file for the role:

 

nano tasks/main.yml

 

Delete the default existing file and replace it with the following code:

 

 

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$ cat tasks/main.yml

– name: “Ensure required packages are present”
yum:
name: “{{ pkg_list }}”
state: present

 

– name: “Ensure latest index.html is present”
template:
src: index.html.j2
dest: /var/www/html/index.html

 

– name: “Ensure httpd service is started and enabled”
service:
name: “{{ item }}”
state: started
enabled: true
with_items: “{{ svc_list }}”

 

– name: “Whitelist http in firewalld”
firewalld:
service: http
state: enabled
permanent: true
immediate: true
(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache$

 

 

This playbook contains 4 tasks:

 

“Ensure required packages are present”:

 

This installs the packages listed in the variables file under pkg_list.

 

The variables file will be located at ~/apache/vars/main.yml and it will be created at the end of this step.

 

“Ensure latest index.html is present”:

 

This task will copy a template page, index.html.j2 in place of the default index file, /var/www/html/index.html, which is generated by Apache. This step will also create the new template.

 

“Ensure httpd service is started and enabled”:

 

This task starts and enables the services listed in svc_list in the variables file.

 

“Whitelist http in firewalld”:

 

This task whitelists the http service in firewalld.

 

Firewalld is the firewall system used by default on CentOS servers.

 

So that the http service can work, you need to open the required ports. Instructing firewalld to whitelist a service ensures it opens the ports that the service requires.

 

 

 

Next create a templates directory for the index.html.j2 template page:

 

mkdir templates

 

(this is actually already present in our molecule roles directory)

 

Then create the page:

 

nano templates/index.html.j2

 

enter the following code into the file:

 

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache/templates$ cat index.html.j2
<div style=”text-align: center”>
<h2>Managed by Ansible</h2>
</div>

 

(my_env) kevin@asus:~/DATAVOLUME/ANSIBLECODE/molecule/apache/templates$

 

 

 

Finally, create the variables file to provide the names of the packages and services for our main role playbook, adding the following code to specify the pkg_list and svc_list:

 

 

nano vars/main.yml

 

 

~/ansible-apache/vars/main.yml

 


pkg_list:
– httpd
– firewalld
svc_list:
– httpd
– firewalld

 

 

These lists contain the following:

 

pkg_list: These are the names of the packages the role will install namely httpd and firewalld.
svc_list: This contains the names of the services the role will start and enable: ie httpd and firewalld.

 

NOTE: make sure there are no blank lines in the variables file or the lint test will fail!

 

Now we have created the role we can now configure Molecule to test whether it will work as expected.

 

Continue Reading

Using Ansible Galaxy

Ansible is a popular open-source configuration management tool that automates software provisioning, configuration management, and application deployment on machines.

 

Ansible Galaxy by contrast is a public repository where users can share and download Ansible roles for server configuration. Ansible Galaxy can be found at https://galaxy.ansible.com/

 

Roles are a means of breaking large playbooks down into a smaller more manageable structure.

 

 

An Overview of the Ansible Role Structure

 

 

README.md – This is the Readme document for the role

 

tasks – contains all tasks to be executed by the Role can be stored here. /tasks/Main.yml is the entry point for the role.

handlers – contains handlers that are used by the role.

defaults – contains the fefault variables for the role.

vars – contains other variables in addition to the defaults for the role.

files – contains the files which can be deployed by the role.

templates – contains templates which can be deployed by the role.

meta – You can define metadata for the role here.

tests – this contains any CI tests to be executed.

library – this contains embedded Modules and Plugins for the role which are not created by the init command.

 

 

How To Create Roles With Ansible Galaxy

 

The ansible-galaxy command comes pre-installed with Ansible.

 

 

You initialize a new galaxy role with:

 

ansible-galaxy init

 

A role can also be installed directly from the Ansible Galaxy repo with the command:

 

ansible-galaxy install <name of role>

 

Some commonly used ansible-galaxy commands

 

ansible-galaxy -> Displays all the options available with Galaxy

 

ansible-galaxy list: Displays a list of the currently installed roles

ansible-galaxy remove <role>: Removes an installed role

ansible-galaxy info: Displays information about Galaxy

ansible-galaxy init: Creates a role template for submission to Galaxy

ansible-galaxy import: This galaxy command requires a login to import a role from Galaxy

ansible-galaxy install: Installs a role from Galaxy repository

 

Galaxy also allows you to host your own internal Galaxy server. To use the internal Galaxy server, edit the default configuration in Ansible.cfg file to point to the server address of the Galaxy internal server. By default Galaxy points to the server address galaxy.ansible.com, so you need to change this.

 

 

Begin with the init command (ansible-galaxy-init) and create a role.

 

For example:

 

kevin@asus:~/DATAVOLUME/ANSIBLECODE$ ansible-galaxy init testing
– Role testing was created successfully
kevin@asus:~/DATAVOLUME/ANSIBLECODE$

ansible-galaxy

If you wish to use a MySQL server Ansible role, search for it on the Galaxy website and click on the filter button.

 

You will see for example that user geerlingguy has a very popular MySQL role that you can use.

 

Click on geerlingguy MySQL

 

Then enter on your terminal:

 

ansible-galaxy-mysql

 

This will display the installation command to install this role using ansible-galaxy.

 

ansible-galaxy install geerlingguy.mysql

 

Run the command to download and install the MySQL server role on your machine.

 

In this case:

 

kevin@asus:~/DATAVOLUME/ANSIBLECODE$ansible-galaxy install geerlingguy.mysqll
Starting galaxy role install process
kevin@asus:~/DATAVOLUME/ANSIBLECODE$

 

Before you can use Galaxy roles in Ansible playbooks, you first have to download the role. They will by default be placed in the default Ansible roles directory at /etc/ansible/roles.

 

 

Ansible content can also be distributed using collections. These are used for packaging and distributing playbooks, together with roles, modules, and plugins.

 

Here’s an example of an Ansible Galaxy structure:

 

collection/
├── docs/
├── galaxy.yml
├── plugins/
│ ├──
modules/
│ │ └── module1.py
│ ├──
inventory/
│ └── …/
├── README.md
├── roles/
│ ├──
role1/
│ ├──
role2/
│ └── …/
├── playbooks/
│ ├──
files/
│ ├──
vars/
│ ├──
templates/
│ └── tasks/
└── tests/

 

Creating a Collection Structure

 

To install a collection on your machine, use the ansible-galaxy collection installation command:

init: Creates a basic collection structure based on Ansible’s default template or a template of your own

build: Creates a collection artifact for uploading to Galaxy or to your own repository

publish: Instructs Galaxy to publish a built collection artifact

install: Installs one or more collections

 

Continue Reading

Using Ansible – Getting Started

 

ansible virtualmachines -m ping -i inventory.yaml

 

ansible-inventory -i inventory.yaml –list

 

ansible-playbook -i inventory.yml playbook-01.yml -u kevin

 

root@asus:/home/kevin# ansible –version
ansible 2.10.8
config file = None
configured module search path = [‘/root/.ansible/plugins/modules’, ‘/usr/share/ansible/plugins/modules’]
ansible python module location = /usr/lib/python3/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0]
root@asus:/home/kevin#

 

ansible example -m ping -u [username]

 

…where [username] is the user  to log into the server. If everything worked, you will see a
message that shows www.example.com | success >>, followed by the result of your ping.

 

If that didn’t work, run the command again using -vvvv on the end to display more verbose output.

 

 

 

 

Ansible assumes you’re using passwordless (key-based) login for SSH connections (e.g. you login by
entering ssh username@example.com – without typing a password).

 

If you’re still logging into your machines with a username and password,  add the –ask-pass (-k) flag to
Ansible commands. You may need to install the sshpass package for this to work properly.

 

Define your hosts in in /etc/ansible/hosts  

You have to define your hosts in the /etc/ansible/hosts file on your control server:

 

root@asus:/etc/ansible# cat hosts
[labhosts]
192.168.122.101
192.168.122.102
192.168.122.103
[vpnhosts]
10.147.18.1
10.147.18.14
10.147.18.72

 

 

 

Then, you need to place the hosts in your inventory file as well:

 

 

kevin@asus:~/LOCAL/WORK/AnsibleLab/mylan$ cat inventory.yml
vpnhosts:
hosts:
asusvpn:
ansible_host: 10.147.18.14
lenvpn:
ansible_host: 10.147.18.1
kevinvm1vpn:
ansible_host: 10.147.18.72
children:
webservers:
hosts:
kevinvm1vpn:
laptops:
hosts:
asusvpn:
lenvpn:
kevin@asus:~/LOCAL/WORK/AnsibleLab/mylan$

 

root@asus:/etc/ansible#

 

then we can do:

 

kevin@asus:~/LOCAL/WORK/AnsibleLab/mylan$ ansible vpnhosts -a “hostname”
[DEPRECATION WARNING]: Distribution ubuntu 22.04 on host 10.147.18.14 should use /usr/bin/python3, but is using /usr/bin/python for backward compatibility
with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See
https://docs.ansible.com/ansible/2.10/reference_appendices/interpreter_discovery.html for more information. This feature will be removed in version 2.12.
Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
10.147.18.14 | CHANGED | rc=0 >>
asus
10.147.18.72 | CHANGED | rc=0 >>
ip-172-31-82-94
10.147.18.1 | UNREACHABLE! => {
“changed”: false,
“msg”: “Failed to connect to the host via ssh: ssh: connect to host 10.147.18.1 port 22: No route to host”,
“unreachable”: true
}
kevin@asus:~/LOCAL/WORK/AnsibleLab/mylan$

 

 

The above is correct since 10.147.18.1 the lenvpn is switched off right now.

 

ansible has found two machines – the aws server and the asus laptop, via the vpn lan network.

 

 

another ad-hoc command:

 

kevin@asus:~/LOCAL/WORK/AnsibleLab/mylan$ ansible vpnhosts -a “free”
[DEPRECATION WARNING]: Distribution ubuntu 22.04 on host 10.147.18.14 should use /usr/bin/python3, but is using /usr/bin/python for backward compatibility
with prior Ansible releases. A future Ansible release will default to using the discovered platform python for this host. See
https://docs.ansible.com/ansible/2.10/reference_appendices/interpreter_discovery.html for more information. This feature will be removed in version 2.12.
Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.
10.147.18.14 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 18368156 6803544 1201804 183504 10362808 11027232
Swap: 2097148 19712 2077436

 

10.147.18.1 | UNREACHABLE! => {
“changed”: false,
“msg”: “Failed to connect to the host via ssh: ssh: connect to host 10.147.18.1 port 22: No route to host”,
“unreachable”: true
}
10.147.18.72 | CHANGED | rc=0 >>
total used free shared buff/cache available
Mem: 989388 442784 69928 69884 476676 291700
Swap: 0 0 0
kevin@asus:~/LOCAL/WORK/AnsibleLab/mylan$

 

 

 

Continue Reading