How Do You Get an Ansible Variable to Not Add Single Quotes or Brackets when the Variable Is Substituted?

Problem scenario
You are using an Ansible-supported method of a variable in a playbook. This variable will substitute a string or line number that the playbook is run on with the IP address of the host. You notice that this substitution includes an opening-and-closing single quote mark "'" and a pair of opening-and-closing brackets "[]". That is, single quotes and brackets are being introduced into the string you want to build with the Ansible playbook.

The playbook (aka .yaml file) has lines like these:

vars:
ip_address: "{{ ansible_all_ipv4_addresses }}"

The string that is later being created shows IP addresses like these:

['12.34.56.78']

You want it to be like this: 12.34.56.78

How do you get the playbook to work without adding these quote and bracket characters?

Solution
Rather than use the format (or syntax above), use this format below in your playbook:
vars:
ip_address: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"

YoYou may also want to see How Do You Get an Ansible Variable to Not Add Single Quotes or Brackets when the Variable Is Substituted?.

Leave a comment

Your email address will not be published. Required fields are marked *