ONLY FOR SELF STUDY, NO COMMERCIAL USAGE!!!
Chapter 3. Managing Variables and Facts
Managing Variables
Variables provide a convenient way to manage dynamic values for a given environment in your Ansible project. Examples of values that variables might contain include:
- Users to create
- Packages to install
- Services to restart
- Files to remove
- Archives to retrieve from the internet
Naming Variables
Variable names must start with a letter, and they can only contain letters, numbers, and underscores.
The following table illustrates the difference between invalid and valid variable names.
Table 3.1. Examples of Invalid and Valid Ansible Variable Names
| Invalid variable names | Valid variable names |
|---|---|
web server |
web_server |
remote.file |
remote_file |
1st file |
file_1``file1 |
remoteserver$1 |
remote_server_1 or remote_server1 |
Defining Variables
The following simplified list shows ways to define a variable, ordered from the lowest precedence to the highest:
-
Group variables defined in the inventory (lowest)
-
Group variables defined in files in a
group_varssubdirectory in the same directory as the inventory or the playbook -
Host variables defined in the inventory
-
Host variables defined in files in a
host_varssubdirectory in the same directory as the inventory or the playbook -
Host facts, discovered at runtime
-
Play variables in the playbook (
varsandvars_files)-
One common method is to place a variable in a
varsblock at the beginning of a play:- hosts: all vars: user: joe home: /home/joe or - hosts: all vars_files: - vars/users.yml -
Using Variables in Playbooks
Variables are referenced by placing the variable name in double braces (
{ { }}). Ansible substitutes the variable with its value when the task is executed.(quotes are mandatory if the variable is the first element to start)vars: user: joe n tasks: # This line will read: Creates the user joe - name: Creates the user { { user }} user: # This line will create the user named Joe name: "{ { user }}"
-
-
Task variables
-
Extra variables defined on the command line (highest)
-
by using the
--extra-varsor-eoption and specifying those variables -
[user@demo ~]$ ansible-navigator run main.yml -e "package=apache"
-
For the Directories to Populate Host and Group Variables
The following examples illustrate this approach in more detail. Consider a scenario where you need to manage two data centers, and the data center hosts are defined in the ~/project/inventory inventory file:
[datacenter1]
demo1.example.com
demo2.example.com
[datacenter2]
demo3.example.com
demo4.example.com
[datacenters:children]
datacenter1
datacenter2
-
If you need to define a general value for all servers in both data centers, set a group variable for the
datacentershost group:[admin@station project]$ cat ~/project/group_vars/datacenters package: httpd -
If you need to define difference values for each data center, set a group variable for each data center host group:
[admin@station project]$ cat ~/project/group_vars/datacenter1 package: httpd [admin@station project]$ cat ~/project/group_vars/datacenter2 package: apache -
If you need to define different values for each managed host in every data center, then define the variables in separate host variable files:
[admin@station project]$ cat ~/project/host_vars/demo1.example.com package: httpd [admin@station project]$ cat ~/project/host_vars/demo2.example.com package: apache [admin@station project]$ cat ~/project/host_vars/demo3.example.com package: mariadb-server [admin@station project]$ cat ~/project/host_vars/demo4.example.com package: mysql-server
The directory structure for the example project, project, if it contained all the example files above, would appear as follows:
project
├── ansible.cfg
├── group_vars
│ ├── datacenters
│ ├── datacenters1
│ └── datacenters2
├── host_vars
│ ├── demo1.example.com
│ ├── demo2.example.com
│ ├── demo3.example.com
│ └── demo4.example.com
├── inventory
└── playbook.yml
Using Dictionaries as Variables
For example, consider the following snippet:
user1_first_name: Bob
user1_last_name: Jones
user1_home_dir: /users/bjones
user2_first_name: Anne
user2_last_name: Cook
user2_home_dir: /users/acook
This could be rewritten as a dictionary called users:
users:
bjones:
first_name: Bob
last_name: Jones
home_dir: /users/bjones
acook:
first_name: Anne
last_name: Cook
home_dir: /users/acook
You can then use the following variables to access user data:
# Returns 'Bob'
users.bjones.first_name
# Returns '/users/acook'
users.acook.home_dir
Because the variable is defined as a Python dictionary, an alternative syntax is available.
# Returns 'Bob'
users['bjones']['first_name']
# Returns '/users/acook'
users['acook']['home_dir']
Capturing Command Output with Registered Variables
You can use the register statement to capture the output of a command or other information about the execution of a module.
The following play demonstrates how to capture the output of a command for debugging purposes:
---
- name: Installs a package and prints the result
hosts: all
tasks:
- name: Install the package
ansible.builtin.dnf:
name: httpd
state: installed
register: install_result
- debug:
var: install_result
When you run the play, the debug module dumps the value of the install_result registered variable to the terminal.
[user@demo ~]$ ansible-navigator run playbook.yml -m stdout
PLAY [Installs a package and prints the result] ****************************
TASK [setup] ***************************************************************
ok: [demo.example.com]
TASK [Install the package] *************************************************
ok: [demo.example.com]
TASK [debug] ***************************************************************
ok: [demo.example.com] => {
"install_result": {
"changed": false,
"msg": "",
"rc": 0,
"results": [
"httpd-2.4.51-7.el9_0.x86_64 providing httpd is already installed"
]
}
}
PLAY RECAP *****************************************************************
demo.example.com : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
REFERENCES
How to build your inventory — Ansible Documentation
Using Variables — Ansible Documentation
Variable precedence: Where should I put a variable?
YAML Syntax — Ansible Documentation
Data-variable example
---
- name: Deploy and start Apache HTTPD service
hosts: webserver
vars:
web_pkg: httpd
firewall_pkg: firewalld
web_service: httpd
firewall_service: firewalld
rule: http
tasks:
- name: Required packages are installed and up to date
ansible.builtin.dnf:
name:
- "{
{ web_pkg }}"
- "{
{ firewall_pkg }}"
state: latest
- name: The {
{
firewall_service }} service is started and enabled
ansible.builtin.service:
name: "{
{ firewall_service }}"
enabled: true
state: started
- name: The {
{
web_service }} service is started and enabled
ansible.builtin.service:
name: "{
{ web_service }}"
enabled: true
state: started
- name: Web content is in place
ansible.builtin.copy:
content: "Example web content"
dest: /var/www/html/index.html
- name: The firewall port for {
{
rule }} is open
ansible.posix.firewalld:
service: "{
{ rule }}"
permanent: true
immediate: true
state: enabled

最低0.47元/天 解锁文章
1319

被折叠的 条评论
为什么被折叠?



