Ansible playbook variables (basic usage of variables)

王林
Release: 2024-02-18 16:45:09
forward
678 people have browsed it

Ansible is an open source automated configuration management and deployment tool that helps administrators automate tasks on multiple servers.

In Ansible, Playbook is a YAML file used to describe automation tasks.

Using variables (variables) is an important part of Playbook functionality, which can make your Playbook more flexible, reusable and easy to maintain.

Ansible playbook变量(变量基本用法)

The following are some basic uses of variables in Ansible Playbook:

Define variables:

Variables can be defined in Playbooks, inventory files, vars files, or on the command line using the -e parameter.

example:

Define variables in Playbook:

---
- name: Set up web server
hosts: webservers
vars:
http_port: 80
max_clients: 200
Copy after login

Define variables in the inventory file:

[webservers]
web1.example.com http_port=80 max_clients=200
web2.example.com http_port=8080 max_clients=100
Copy after login

Use variables:

Variables can be used in tasks, templates, conditional statements, etc.

example:

- name: Ensure Apache is running
ansible.builtin.service:
name: httpd
state: started
enabled: yes
when: http_port == 80
Copy after login

Register variables:

After a task is executed, the result can be saved to a variable through the register keyword.

example:

- name: Check if package is installed
ansible.builtin.package_facts:
register: package_info

- name: Display package information
ansible.builtin.debug:
var: package_info
Copy after login

Use special variables:

Ansible provides some built-in special variables, such as inventory_hostname, ansible_facts, etc.

example:

- name: Display the current host's name
ansible.builtin.debug:
var: inventory_hostname
Copy after login

Variable priority:

In Ansible, the priority of variables from low to high is: default value, variables defined in the inventory file, variables in the Playbook, and command line parameters. Variable values ​​with higher priority override variable values ​​with lower priority.

After understanding the basic concepts and usage of Ansible Playbook variables, you can flexibly use variables according to actual needs to optimize your automation tasks.

The above is the detailed content of Ansible playbook variables (basic usage of variables). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:mryunwei.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template