Interview Infrastructure as Code (Terraform, Ansible)

How does Ansible gather facts, and how do you use them in conditionals?

Infrastructure as Code (Terraform, Ansible) · Intermediate level

Answer

Ansible gathers facts with the setup module at the start of a play when gather_facts is true. Those facts are available under ansible_facts and commonly used in when clauses to branch by OS family, distribution version, network interface, or hardware capability.

Technical explanation

gather_facts can be disabled for speed when facts are not needed.

Fact names help write portable tasks such as ansible_facts['os_family'] == 'RedHat'.

For custom facts, use local facts or set_fact carefully.

Prefer idempotent modules over shell so repeated runs are safe and change reporting is meaningful.

Separate reusable role logic from inventory-specific variables so the same automation works across environments.

Run lint, syntax checks, check mode where useful, and staged rollouts before production-wide changes.

Hands-on example

1. Model variables and facts for: How does Ansible gather facts, and how do you use them in conditionals?

2. Create inventory variables:

group_vars/web.yml:

app_port: 8080

package_name_by_os:

RedHat: httpd

Debian: apache2

host_vars/web1.yml:

app_port: 9090

3. Use facts and variables in a task:

- name: Install OS-specific web package

ansible.builtin.package:

name: "{{ package_name_by_os[ansible_facts['os_family']] }}"

state: present

when: ansible_facts['os_family'] in package_name_by_os

4. Run ansible-playbook site.yml -e app_port=7070 in a lab to see extra vars override lower-precedence values.

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Infrastructure as Code (Terraform, Ansible) interview questions

← All Infrastructure as Code (Terraform, Ansible) questions