Ansible - Variables đĄ
Description đ
Variables store information that varies with each host. Variables can be used to store information about a host, such as its IP address, hostname, or operating system.
Variables can also be used to store information about a group of hosts, such as the name of a database server or the name of a web server.
To use a variable, you must enclose the variable name in double curly braces
- i.e
Basics đ
-
inventory variables
# inventory.txt [<group-name>] <host> [<group-name>:vars] <variableX>=<valueY> -
playbook variables
# playbook.yml - name: <play name> hosts: <host-pattern> # variables are stored under the `vars` key using the `key: value` format vars: <variableX>: <valueY> tasks: - <module>: <key>: <value> -
separate variables file
# vars.yml <variableX>: <valueY>- variable files named after hosts/groups allows ansible to load the variables when the host/group is referenced
Examples đ§Š
-
inventory variables
# inventory.txt [web] host1.example.com host2.example.com [web:vars] http_port=80 maxRequestsPerChild=8080host1.example.comandhost2.example.comare both members of thewebgrouphttp_portandmaxRequestsPerChildare variables that are defined for thewebgroup
-
playbook variables
# playbook.yml - name: Add a DNS server to /etc/resolv.conf hosts: localhost # variables are stored under the `vars` key using the `key: value` format vars: dns_server: 10.1.250.10 tasks: - lineinfile: path: /etc/resolv.conf line: 'nameserver ' -
separate variables file
# vars.yml variable1: value1 variable2: value2 -
playbook using variables in variables file
# inventory.txt [web] host1.example.com host2.example.com# web.yml # can be used whenever the host is part of the `web` group http_port: 80 snmp_port: 161-162 inter_ip_range: 192.0.2.0# playbook.yml - name: Set Firewall Configuration hosts: web tasks: - firewalld: service: https permanent: true state: enabled - firewalld: port: "/tcp" permanent: true state: disabled - firewalld: port: "/udp" permanent: true state: enabled - firewalld: source: "/24" Zone: internal state: enabled