Introduction to Ansible core
- WHAT?
Ansible is an IT automation tool that simplifies configuration management, application deployment and task orchestration by enabling you to define infrastructure as code in a simple way.
- WHY?
Learn how to automate IT infrastructure with Ansible, from installation and configuration, to creating inventory files and a playbooks.
- EFFORT
The average reading time of this article is approximately 40 minutes.
- REQUIREMENTS
Linux fundamentals: Understanding basic Linux commands, file permissions, directory structures and use of the command line.
Networking: Ansible connects to remote machines via SSH so knowledge of IP addresses, SSH, host names and ports is required.
YAML: Ansible playbooks are written in YAML, so knowing how to structure a YAML file is essential.
1 What is Ansible core? #
Ansible core is an open source IT automation engine that automates provisioning, configuration management, application deployment and other IT processes. It is has agent less architecture, which means no dedicated connection software is required on the managed nodes. It operates on the following concepts:
Control node: The machine where Ansible is installed and executed.
Managed nodes: The target servers or devices that Ansible manages.
Inventory: A file that defines and groups your managed nodes.
Module: A small program that performs actions on a managed node.
Task: A single execution of an Ansible module on a managed node.
Playbooks: Ansible playbooks provide a repeatable, reusable, simple configuration management and multi-machine deployment system.
Collection: A collection of Ansible roles or modules focusing on a specific area.
Role: A standard, self-contained and portable unit of automation that organizes related tasks, variables and files into a predictable directory structure for easy reuse.
Ansible Core is the foundational software package that includes command-line tools like
ansibleandansible-playbookand the execution engine. It provides the essential libraries and basic modules needed to connect to managed nodes and execute tasks.Ansible automation components are the content that defines the logic, packaged into playbooks, roles and collections. These assets provide the instructions for the core engine, with collections serving as a distribution format that bundles reusable roles, modules and plug-ins.
Ansible Orchestration is handled by higher-level tools that provide a UI, API and workflow engine to centrally manage and visually chain multiple automation playbooks together for complex multi-system processes.
2 Installing Ansible #
Ansible is available for installation from SLES for SAP 16.0 base system.
Refresh the repository and install Ansible.
>sudozypper refresh>sudozypper install ansibleTo verify:
>ansible --versionansible [core 2.18.3] config file = None configured module search path = ['/home/amrita/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3.13/site-packages/ansible ansible collection location = /home/amrita/.ansible/collections:/usr/share/ansible/collections executable location = /usr/bin/ansible python version = 3.13.5 (main, Jun 12 2025, 00:40:24) [GCC] (/usr/bin/python3.13) jinja version = 3.1.6 libyaml = True
3 Understanding Ansible configuration #
Ansible supports several sources for configuring its behavior, including an INI file named ansible.cfg, environment variables, command-line options and playbook keywords.
The standard configuration is usually sufficient for most users.
The ansible-config utility provides users with a comprehensive view of all available configuration settings, including their default values,
instructions on how to set them and the origin of their current values. Ansible processes the following list and uses the first file found. All others are ignored.
ANSIBLE_CONFIGenvironment variable if setansible.cfglocated in the current directory~/.ansible.cfglocated in the home directory/etc/ansible/ansible.cfg
You can generate a sample ansible.cfg file either with a fully commented out file or
a more complete file that includes the existing plug-in. For example:
>sudoansible-config init --disabled > ansible.cfg
>sudoansible-config init --disabled -t all > ansible.cfg
4 Structure of an inventory file #
An Ansible inventory file defines the hosts or servers on which Ansible commands and playbooks will run.
It can be in either INI or YAML format and is a fundamental component of an Ansible project.
An Ansible project is a directory structure containing all the files necessary to automate a specific IT goal, such as deploying an application or configuring a multi-tier infrastructure.
Ansible uses several built-in variables to connect to and manage hosts, which are often defined in the inventory file. The most common ones are:
ansible_host:Specifies the IP address or DNS name of the host.ansible_userThe user account to use for SSH connections.ansible_port:The connection port number if not the default,22for SSH.ansible_private_key_file:Specifies the path to the SSH private key file that Ansible should use to authenticate with and connect to the remote managed nodes.ansible_python_interpreter:Specifies the path to the Python interpreter on the remote host if it is not the default.
4.1 INI format #
The INI format is the more traditional and widely used format for inventory files.
Hosts can be listed individually or grouped together.
- Individual hosts
You can list either the IP addresses or host names. For example:
host1.example.com 192.168.1.50
- Groups
Groups are defined using
[]brackets. You can apply tasks to multiple hosts simultaneously. A host can belong to multiple groups. For example:[webservers] web1.example.com web2.example.com [databases] db1.example.com
- Group variables
Variables can be assigned to all hosts within a specific group. These are defined under the group name using a
:varssuffix. For example:[webservers:vars] ansible_user=test http_port=80
- Child groups
You can create a group of groups, known as a parent group, using the
:childrensuffix. This is useful for combining different host types for a single task. For example:[all_servers:children] webservers databases
4.2 YAML format #
YAML offers a structured and hierarchical way to represent the inventory. It is often preferred for its readability and ability to handle complex data structures.
- Host and group structure:
The inventory is defined under the
allkeyword, which contains hosts and children. For example,all: hosts: host1.example.com: 192.168.1.50: children: webservers: hosts: web1.example.com: web2.example.com: databases: hosts: db1.example.com:- Group and host variables
Variables are defined under a
varsdictionary within the host or group. For example:webservers: hosts: web1.example.com: web2.example.com: vars: http_port: 80 server_type: nginx max_connections: 500- Child groups
You can create a group of groups, known as a parent group, using the
:childrensuffix. This is useful for combining different host types for a single task. For example:all: children: webservers: hosts: web1.example.com: ansible_user: test vars: http_port: 80
5 Basic usage of Ansible #
Ansible provides ad hoc commands and several utilities to perform various operation and automation
tasks. Ad hoc commands in Ansible are useful for performing quick and one-off tasks that do not need to be saved for future use.
They are single-line commands executed directly from the command line. Ad hoc commands use the ansible CLI tool.
In contrast, playbooks are a more powerful and scalable solution for defining complex, multi-step IT automation tasks.
They are written in YAML and contain a list of plays, with each play associating a group of hosts with a series of tasks.
The ansible-playbook CLI tool is used to execute these playbooks. This approach promotes reusability, version control
and collaboration, making it the preferred method for managing and deploying applications at scale.
You can use either ad hoc commands or create a playbook to automate your IT infrastructure based on your use case.
5.1 Ad hoc commands #
Ad-hoc commands are a quick way to run a single task on one or more managed hosts directly from the command line. Ideal for simple operations like checking system uptime or rebooting a server.
They are useful for quickly managing servers by performing actions like rebooting, copying files and managing packages and users. You can use any of the available Ansible modules in an ad hoc task. Like playbooks, ad hoc tasks use a declarative model, where you define the desired final state. Ansible then automatically calculates and executes the necessary steps to achieve that state. This approach ensures the task can be run multiple times without causing unintended changes, as Ansible first checks the current state of the host and only performs an action if it differs from the specified final state. Some examples include:
> ansible webservers -m ansible.builtin.service -a "name=httpd state=started"> ansible all -m ansible.builtin.setup5.2 Ansible command-line tools #
Ansible provides the following command-line tools:
ansibleA simple tool or framework for remote tasks; this command-line tool allows you to define and run a single task playbook against a set of hosts.
>ansible -husage: ansible [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD] [--become-user BECOME_USER] [-K | --become-password-file BECOME_PASSWORD_FILE] [-i INVENTORY] [--list-hosts] [-l SUBSET] [-P POLL_INTERVAL] [-B SECONDS] [-o] [-t TREE] [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER] [-c CONNECTION] [-T TIMEOUT] [--ssh-common-args SSH_COMMON_ARGS] [--sftp-extra-args SFTP_EXTRA_ARGS] [--scp-extra-args SCP_EXTRA_ARGS] [--ssh-extra-args SSH_EXTRA_ARGS] [-k | --connection-password-file CONNECTION_PASSWORD_FILE] [-C] [-D] [-e EXTRA_VARS] [--vault-id VAULT_IDS] [-J | --vault-password-file VAULT_PASSWORD_FILES] [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR] [--task-timeout TASK_TIMEOUT] [-a MODULE_ARGS] [-m MODULE_NAME] pattern Define and run a single task 'playbook' against a set of hosts [...]ansible-configUsed to manage and view Ansible's configuration settings.
>ansible-config -husage: ansible-config [-h] [--version] [-v] {list,dump,view,init,validate} ... View ansible configuration. positional arguments: {list,dump,view,init,validate} list Print all config options dump Dump configuration view View configuration file init Create initial configuration validate Validate the configuration file and environment variables. By default it only checks the base settings without accounting for plugins (see -t). options: --version show program's version number, config file location, configured module search path, module location, executable location and exit -h, --help show this help message and exit -v, --verbose Causes Ansible to print more debug messages. Adding multiple -v will increase the verbosity, the builtin plugins currently evaluate up to -vvvvvv. A reasonable level to start is -vvv, connection debugging might require -vvvv. This argument may be specified multiple times.ansible-consoleAn interactive command-line tool or Read-Eval-Print Loop (REPL) that lets you run Ansible ad hoc commands in a persistent real-time shell environment. It is a great tool for quickly testing modules, exploring your inventory and debugging issues without having to run a new command for every action.
>ansible-console -husage: ansible-console [-h] [--version] [-v] [-b] [--become-method BECOME_METHOD] [--become-user BECOME_USER] [-K | --become-password-file BECOME_PASSWORD_FILE] [-i INVENTORY] [--list-hosts] [-l SUBSET] [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER] [-c CONNECTION] [-T TIMEOUT] [--ssh-common-args SSH_COMMON_ARGS] [--sftp-extra-args SFTP_EXTRA_ARGS] [--scp-extra-args SCP_EXTRA_ARGS] [--ssh-extra-args SSH_EXTRA_ARGS] [-k | --connection-password-file CONNECTION_PASSWORD_FILE] [-C] [-D] [--vault-id VAULT_IDS] [-J | --vault-password-file VAULT_PASSWORD_FILES] [-f FORKS] [-M MODULE_PATH] [--playbook-dir BASEDIR] [-e EXTRA_VARS] [--task-timeout TASK_TIMEOUT] [--step] [pattern] REPL console for executing Ansible tasks. [...]ansible-docA command-line tool that provides documentation for all Ansible's installed modules and plug-ins. It is an essential utility for anyone writing playbooks or ad hoc commands. You can look up a module's purpose, parameters, return , and even usage examples directly from your terminal.
>ansible-doc -husage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH] [--playbook-dir BASEDIR] [-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,vars,module,strategy,test,filter,role,keyword}] [-j] [-r ROLES_PATH] [-e ENTRY_POINT | -s | -F | -l | --metadata-dump] [--no-fail-on-errors] [plugin ...] plugin documentation tool [...]ansible-galaxyA command-line tool that comes with Ansible and is used for managing and sharing roles.
>ansible-galaxy -hPerform various Role and Collection related operations. positional arguments: TYPE collection Manage an Ansible Galaxy collection. role Manage an Ansible Galaxy role. options: --version show program's version number, config file location, configured module search path, module location, executable location and exit -h, --help show this help message and exit -v, --verbose Causes Ansible to print more debug messages. Adding multiple -v will increase the verbosity, the builtin plugins currently evaluate up to -vvvvvv. A reasonable level to start is -vvv, connection debugging might require -vvvv. This argument may be specified multiple times.ansible-inventoryIs a command-line tool that helps you inspect, validate and understand your inventory.
>ansible-inventory -husage: ansible-inventory [-h] [--version] [-v] [-i INVENTORY] [-l SUBSET] [--vault-id VAULT_IDS] [-J | --vault-password-file VAULT_PASSWORD_FILES] [--playbook-dir BASEDIR] [-e EXTRA_VARS] [--list] [--host HOST] [--graph] [-y] [--toml] [--vars] [--export] [--output OUTPUT_FILE] [group] Show Ansible inventory information, by default it uses the inventory script JSON format [...]ansible-playbookIs the primary command-line tool used to run Ansible's automation blueprints, also known as playbooks, against an inventory of target hosts.
>ansible-playbook -husage: ansible-playbook [-h] [--version] [-v] [--private-key PRIVATE_KEY_FILE] [-u REMOTE_USER] [-c CONNECTION] [-T TIMEOUT] [--ssh-common-args SSH_COMMON_ARGS] [--sftp-extra-args SFTP_EXTRA_ARGS] [--scp-extra-args SCP_EXTRA_ARGS] [--ssh-extra-args SSH_EXTRA_ARGS] [-k | --connection-password-file CONNECTION_PASSWORD_FILE] [--force-handlers] [--flush-cache] [-b] [--become-method BECOME_METHOD] [--become-user BECOME_USER] [-K | --become-password-file BECOME_PASSWORD_FILE] [-t TAGS] [--skip-tags SKIP_TAGS] [-C] [-D] [-i INVENTORY] [--list-hosts] [-l SUBSET] [-e EXTRA_VARS] [--vault-id VAULT_IDS] [-J | --vault-password-file VAULT_PASSWORD_FILES] [-f FORKS] [-M MODULE_PATH] [--syntax-check] [--list-tasks] [--list-tags] [--step] [--start-at-task START_AT_TASK] playbook [playbook ...] Runs Ansible playbooks, executing the defined tasks on the targeted hosts. [...]ansible-vaultIs a command-line tool that allows you to encrypt sensitive data, such as passwords, API keys and other secrets and store them securely within your playbooks and other configuration files.
>ansible-vault -husage: ansible-vault [-h] [--version] [-v] {create,decrypt,edit,view,encrypt,encrypt_string,rekey} ... encryption/decryption utility for Ansible data files [...]
5.3 Configuring SSH #
By default, Ansible assumes SSH keys are being used between a control and managed nodes to establish a connection. To set up SSH key-based authentication from the control node to the managed nodes:
Generate a key pair on the control node.
It is recommended to use a dedicated SSH key that is clearly defined in the variable
ansible_ssh_private_key_file.Copy the public key to the managed node.
>ssh-copy-id -i PATH_TO_PUBLIC_KEY TARGET_USER@IP_ADDRESS/HOSTNAMEThis onetime setup allows Ansible to connect securely without prompting for credentials during automation.
Add the private key to the control node.
>ssh-add PATH_TO_PRIVATE_KEY
5.4 Creating a playbook #
An Ansible playbook is a YAML file that defines a series of tasks to be executed on one or more hosts.
This topic covers the creation of a simple playbook.
Define an inventory file, for example:
[all] 192.168.122.154 ansible_user=user1Although Ansible uses
/etc/ansible/hostsby default. It is a best practice to maintain a separate inventory file and specify it using the--inventoryflag.Verify your inventory file, for example:
>ansible-inventory --inventory test.ini --listTest the connection between the control node and managed nodes with the Ansible ad hoc command:
>ansible all -i test.ini -m pingIf the configuration is correct, the following message is displayed:
[WARNING]: Platform linux on host 192.168.122.73 is using the discovered Python interpreter at /usr/bin/python3.13, but future installation of another Python interpreter could change the meaning of that path. See https://docs.ansible.com/ansible-core/2.18/reference_appendices/interpreter_discovery.html for more information. 192.168.122.73 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3.13" },This confirms Ansible can reach the managed nodes securely via SSH.
Playbooks are
YAMLfiles that define the tasks Ansible should perform. For example, create a file namedinstall.ymlto define a task to install common packages on all managed SUSE systems:- name: Ensure essential packages are present hosts: all become: true gather_facts: true tasks: - name: Install vim and curl ansible.builtin.package: name: - suseconnect - curl state: presentRun the playbook in check mode:
>ansible-playbook install.yml --checkCheck mode is a simulation. It does not generate output for tasks. It validates a configuration management playbook and is useful for simple playbooks.
Run the playbook:
>ansible-playbook -i hosts.ini install.ymlAnsible connects to each host in your inventory and executes the defined tasks using the system's package manager.
5.5 Understanding roles #
Roles allow you to easily reuse and share your Ansible automation by using a known file structure to automatically load all related artifacts, including tasks, variables, files, and handlers.
5.5.1 Using roles #
You can use the role in the following ways:
At the play level with the
roles: This is the default way of using roles in a play.At the task level with
ansible.builtin.import_role: You can reuse roles dynamically anywhere in thetaskssection of a play usingansible.builtin.import_role.At the task level with
ansible.builtin.import_role: You can reuse roles dynamically anywhere in thetaskssection of a play usingansible.builtin.import_role.As a dependency of another role.
A play is the fundamental execution unit within an Ansible playbook.
5.5.2 Importing roles #
You can reuse roles statically anywhere in the tasks section of a play by using import_role. For example:
---
- hosts: webservers
tasks:
- name: Print a message
ansible.builtin.debug:
msg: "before we run our role"
- name: Apply standard user and group setup from 'base_users' role
ansible.builtin.import_role:
name: base_users
- name: Print a message
ansible.builtin.debug:
msg: "after we ran our role"You can use other keywords, for example:
---
- hosts: webservers
tasks:
- name: Import the foo_app_instance role
ansible.builtin.import_role:
name: test_app_instance
vars:
dir: '/opt/a'
app_port: 50005.6 About variables #
With Ansible, you can run tasks and playbooks with a single command. Variables are placeholders for values that allow you to make your playbooks dynamic, reusable, and flexible. For example, instead of hard-coding values like a username, port number, or a list of packages, directly into your tasks, you can use a variable. You can define these variables using standard YAML syntax (including lists and dictionaries) in your playbooks, inventories, roles, or at the command line. You can also create new variables dynamically during a playbook run.
5.6.1 Variable placement #
When you define the same variable in multiple locations, Ansible uses variable precedence to determine which value to apply. This fixed order governs how different variable sources override one another during execution. Variable precedence is defined in the following order, from least to greatest (the last listed variable overrides all other variables):
Command-line values
Role defaults
Inventory file or script group vars
Inventory
group_vars/allPlaybook
group_vars/allInventory
group_vars/*Playbook
group_vars/*Inventory file or script host vars
Inventory
host_vars/*Playbook
host_vars/*Host facts and cached
set_factsPlay
varsPlay
vars_promptPlay
vars_filesRole vars
Block vars
Task vars
include_varsRegistered vars and
set_factsRole and
include_roleparamsinclude params
extra vars
Ansible gives precedence to variables defined more recently, more active and with more explicit scope. Variables inside the default
folder are easily overridden. Anything in the vars directory of the role overrides previous versions
of that variable in the namespace.
5.6.2 Setting variables #
You can define variables in an inventory, in playbooks, in reusable files, in roles and at the command line. Ansible loads all the variables it finds and then chooses which variable to apply based on variable precedence.
Defining variables in an inventory: You can either define different variables for each host or set shared variables for a group of hosts in your inventory. For example, if all systems in the
manhattangroup usemanhattan.ntp.example.comas an NTP server, you can use a group variable.Defining variables in a play: You can define variables directly in a play. When you define variables directly, they are visible only to the tasks executed in that play.
Defining variables in include files and roles: You can define variables in reusable variable files or reusable roles. If you define variables in reusable variable files or roles, the sensitive variables are separated from playbooks. This separation enables you to store your playbooks in a source control software and even share the playbooks, without the risk of exposing passwords or other sensitive and personal data. For example:
--- - hosts: all remote_user: root vars: favcolor: blue vars_files: - /vars/test.yml tasks: - name: This is just a placeholder ansible.builtin.command: /bin/echo fooThe content of each variable file is a simple YAML dictionary. For example,
/vars/test.yml:- name: Show foo and bar ansible.builtin.debug: msg: foo: "{{ foo }}" bar: "{{ bar }}"
6 Ansible best practices #
To get the most out of Ansible and Ansible playbooks , here are some best practices you can follow:
Group by roles: A system can belong to multiple groups, a powerful concept exemplified by naming groups descriptively, such as
webserversanddbservers. This structure enables playbooks to target machines based on their role and to assign role-specific variables through the group variable system.Describe the tasks: It is recommended to provide a clear, descriptive
namefor thetasks. This description explains why the task is being performed and is displayed when the playbook executes.Use the
namedirective: It is a good practice to use thenamedirective to name your plays, tasks and blocks.Simplicity: Keep it simple and use only the Ansible features you need.
6.1 Protect sensitive data with the ansible-vault command-line tool #
With Vault, you can encrypt variables and files so you can protect sensitive content such as passwords or keys rather than leaving it visible as plaintext in playbooks or roles. Some best practices include:
Managing Vault passwords: To keep track and manage your Vault , it is best to have a strategy. For example, for a small project or a few sensitive values, you can use a single password for encryption. You can use multiple passwords for a large project or many sensitive values. You can distinguish between different passwords with Vault IDs. Based on your use case, you might want a different password for each encrypted file, for each directory, or for each environment. There are two options within Ansible, to store Vault passwords: in files or using a third-party tool, such as a system keyring or a secret manager. For passwords stored in a third-party tool, you need a vault password client script to retrieve them from within Ansible.
Encrypting individual variables or files: The two types of encryption content in Ansible are variables and files. Encrypted content is identified with the
!vaulttag, which tells Ansible and YAML that the content needs to be decrypted. The|character is used for multi-line strings. Ansible Vault can encrypt any structured data file used by Ansible and the encryption is done in the Vault.Using encrypted individual variables or files: You must provide passwords for encrypted variables or files when running a task or playbook that uses them. You can supply these passwords either directly at the command line or by configuring a default password source using a configuration option or an environment variable. For a single password , use
--ask-vault-passor--vault-password-fileoptions. When you use multiple vaults in a single inventory, use the--vault-id option.You can also use multiple--vault-idoptions to specify the Vault IDs.
7 Ansible support coverage #
The support matrix for Ansible and Python compatibility:
Control node:
Python 3.11 - 3.13
ansible-core 2.18
Ansible 11
Managed node:
Python 3.11 - 3.13
Python and Ansible versions in the control and managed nodes must be compatible.
Third-party software is not supported.
Only versions provided in packages that install into System Python are supported.
Python Virtual Environment or alternatives like pyenv are not supported.
8 More information #
To learn more about Ansible, refer to The official source for Ansible core.
9 Legal Notice #
Copyright© 2006–2025 SUSE LLC and contributors. All rights reserved.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or (at your option) version 1.3; with the Invariant Section being this copyright notice and license. A copy of the license version 1.2 is included in the section entitled “GNU Free Documentation License”.
For SUSE trademarks, see https://www.suse.com/company/legal/. All other third-party trademarks are the property of their respective owners. Trademark symbols (®, ™ etc.) denote trademarks of SUSE and its affiliates. Asterisks (*) denote third-party trademarks.
All information found in this book has been compiled with utmost attention to detail. However, this does not guarantee complete accuracy. Neither SUSE LLC, its affiliates, the authors, nor the translators shall be held liable for possible errors or the consequences thereof.