Skip to content

Instantly share code, notes, and snippets.

@dmccuk
Last active March 24, 2024 03:24

Ansible – Set_facts conditional example

In ansible, like any other programming language, at some point, we’ll want to set a variable for something. This is fairly simple to do when it’s just one value, but if we need to pick that value from the server we run ansible against, it gets a bit trickier.

Subscribe To Me On YouTube: https://bit.ly/lon_sub

Checkout the Youtube Video walkthrough here: https://youtu.be/NUGAQQ7p-Ho

Subscribe to my YouTube channel for more videos like this

For example: I’m running my playbook/role against a list of servers. I need to be able to identify which DC each server is in so I can apply the correct nameservers, timeservers, nfs mounts points, and anything else. I want my code to run on all the servers, set the fact based on something unique to that server, and then apply the configuration.

In this video I’ll show you the following:

  • How to generate static facts
  • How to use a conditional statement to set a fact
  • How to combine the facts into a string

The code:

---
- name: set fact/case example
  hosts: localhost
  tasks:

    - set_fact:
        one: hello
        two: "{{ ansible_domain }}"
        three: "{{ ansible_distribution_file_variety[3:6] }}"
        DC: "{% if ansible_domain == 'eu-west-1.compute.internal' %}DC1\
             {% elif ansible_domain == 'eu-west-2.compute.internal' %}DC2\
             {% else %}DC3\
             {% endif %}"

    - name: one
      debug:
        msg: "{{ one }}"

    - name: two
      debug:
        msg: "{{ two }}"

    - name: three
      debug:
        msg: "{{ three }}"

    - name: dc
      debug:
        msg: Your DC is {{ DC }}
      when: DC == 'DC2'

    - name: combine
      debug:
        msg: "{{ one }}-{{ two }}-{{ three }}-{{ DC }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment