Ansible 6 of 9: Variables

Background

Use variables to store and reference values that can be used throughout playbooks, templates, and other Ansible configuration files. Variables can be used against a single host or a group of hosts.

1 of 12. Open Cloud9 Environment.

2 of 12. Check the hosts inventory file

We have already been using ansible variables.

pwd cat ./hosts

3 of 12. Create a new playbook for testing variables

This playbook will be inside the 'ansible-tasks' folder.

pwd touch variables-example.yml - name: Example Playbook hosts: localhost vars: http_port: 80 https_port: 443 packages: - git - mysql-client - curl - wget appserver: hostname: webapp01 ipaddress: 192.168.1.202 os: Windows Server 2019 tasks: - name: Display the single variable debug: var: http_port, https_port - name: Display the list variable debug: var: packages - name: Display the dictionary variable debug: var: appserver

4 of 12. Examining variables-example.yml: -name and hosts

This just defines the playbook name, and where it will run.

- name: Example Playbook hosts: localhost

5 of 12. Examining variables-example.yml: vars:

This part of the file defines singular variables

vars: http_port: 80 https_port: 443

6 of 12. Examining variables-example.yml: packages:

This part of the file defines a LIST variable, packages

packages: - git - mysql-client - curl - wget

7 of 12. Examining variables-example.yml: appserver:

This part of the file defines a DICTIONARY variable, appserver.

appserver: hostname: webapp01 ipaddress: 192.168.1.202 os: Windows Server 2019

8 of 12. Examining variables-example.yml: tasks:

This part of the file defines tasks that will run

tasks:

9 of 12. Examining variables-example.yml: debug single variable

This task uses debug to display the contents of the single variables: http_port and https_port.

- name: Display the single variable debug: var: http_port, https_port

10 of 12. Examining variables-example.yml: debug list variable

This task uses debug to display the contents of the list variable: packages.

- name: Display the list variable debug: var: packages

11 of 12. Examining variables-example.yml: debug dictionary variable

This task uses debug to display the contents of the dictionary variable: appserver.

- name: Display the dictionary variable debug: var: appserver

12 of 12. Run the playbook: variables-example.yml:

Running the playbook should return debug output per the explanations above.

pwd ansible-playbook variables-example.yml

References

Using Ansible playbooks - Ansible documentation

Using variables - Ansible documentation

Defining variables in a play

Simple variables

List variables

Dictionary variables

ansible.builtin.debug module - Print statements during execution - Ansible Documentation

Comments

Popular posts from this blog

Orphaned No More: Adopting AWS Lambda

Containing the Chaos! | A Three-Part Series Demonstrating the Usefulness of Containerization to HumanGov