HomeBlogExploring Jinja2 Variable Syntax in Ansible
When working with Ansible playbooks and jinja2, you might notice different jinja2 syntax to access data. Some use square brackets (backup_commands['ios']) while others use dot notation (backup_commands.ios) when accessing data.
Both ways are valid and work fairly well, but some would say it’s safer to use [] bracket rather than . dot notation to access data in a production environment. For demo purposes, I tend to use the. notation just to type quicker but that won’t always work if accessing data from a variable.
Note: Other reasons to use square brackets:
When a variable name includes a hyphen (-)
When dynamically generating a dictionary key
Let’s look at a few examples and see why it’s not always possible to access data using the dot(.) notation and it’s always possible to access data using the square brackets([]).
Using Ansible to Access Dictionary Values
First let’s test this playbook called brackets_vs_dot.yml and run it.
A variable has been created under vars called backup_commands and nested, there are a few { "key": "value" } pairs with different vendors as keys and commands as values to access.
Four debug tasks have also been added that will print out each key in a nested dict of dicts. Two of the tasks will use bracket [] notation and the other two will use dot . notation.
Based on the output you can see that both bracket [] and . dot notation worked just fine with the same output results.
However, let’s say this time we want to access that same data, but through a variable. The results on this test will be a little different and will show why the . notation doesn’t always work.
This time vars_prompt has been added in a second play with a variable vendor_os to allow the user to pick an os and access the data through the debug tasks.
vars_prompt:-name: vendor_osprompt:"Enter Vendor OS"private: no
In this second play two tasks have been added using [] brackets and . dot notation to access the data based on the variable value entered through the prompt.
JINJA2 TEMPLATE – Accessing values through dict keys
A similar test to the first play of Ansible will be ran. This time instead of debug tasks, build a jinja2 template and add it in the TEMPLATE column of td4a.
In this example, each key will be accessed with square([]) bracket and dot (.) notation.
After adding the following jinja2 data into the TEMPLATE column, press the RENDER button on the top right of the middle column to view the results.
RESULT
You should see the following results, as expected from the jinja2 template showing that it has successfully accessed each value using both [] brackets and . notation.
Accessing KeysBracket Notation:ios: show runnxos: show runjunos: show configurationDot Notation:ios: show runnxos: show runjunos: show configuration
JINJA2 TEMPLATE – Accessing values through variables
This time run a test with jinja2 for loops, the first one accessing the values through [] brackets and the second one commented out with . notation for now so it doesn’t dispaly an error.
After pressing on the RENDER button again –> the following output should show up:
RESULT
The first two tests don’t change, the second two show the output as expected using the [] bracket and the . notation doesn’t show anything since it’s commented out.
Accessing KeysBracket Notation:ios: show runnxos: show runjunos: show configurationDot Notation:ios: show runnxos: show runjunos: show configurationAccessing VariablesBracket Notation:ios: show runnxos: show runjunos: show configurationDot Notation:
Finally it’s time to test the dot notation so remove the {##} comments from the jinja2 template to view the results using the . notation.
After pressing on the RENDER button one last time and viewing the results:
You should see the following error: Message: Issue found loading template. Details: Object has no attribute 'vendor_os' Line number: 22
Conclusion
Finally it has been proven that for good practice and sake of muscle memory, that maybe we should stick to using [] square brackets rather than . dot notation because you will always be able to access the data whether if it’s a key or a variable without any errors.
Does this all sound amazing? Want to know more about how Network to Code can help you do this, reach out to our sales team. If you want to help make this a reality for our clients, check out our careers page.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. In case of sale of your personal information, you may opt out by using the link Do not sell my personal information. Privacy | Cookies
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
__hssc
30 minutes
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.
__hssrc
session
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.
cookielawinfo-checkbox-advertisement
1 year
Set by the GDPR Cookie Consent plugin, this cookie records the user consent for the cookies in the "Advertisement" category.
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
CookieLawInfoConsent
1 year
CookieYes sets this cookie to record the default button state of the corresponding category and the status of CCPA. It works only in coordination with the primary cookie.
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Cookie
Duration
Description
__cf_bm
30 minutes
Cloudflare set the cookie to support Cloudflare Bot Management.
li_gc
5 months 27 days
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.
lidc
1 day
LinkedIn sets the lidc cookie to facilitate data center selection.
UserMatchHistory
1 month
LinkedIn sets this cookie for LinkedIn Ads ID syncing.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Cookie
Duration
Description
__hstc
5 months 27 days
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).
_ga
1 year 1 month 4 days
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.
_gat_gtag_UA_*
1 minute
Google Analytics sets this cookie to store a unique user ID.
_gid
1 day
Google Analytics sets this cookie to store information on how visitors use a website while also creating an analytics report of the website's performance. Some of the collected data includes the number of visitors, their source, and the pages they visit anonymously.
AnalyticsSyncHistory
1 month
Linkedin set this cookie to store information about the time a sync took place with the lms_analytics cookie.
CONSENT
2 years
YouTube sets this cookie via embedded YouTube videos and registers anonymous statistical data.
hubspotutk
5 months 27 days
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.
ln_or
1 day
Linkedin sets this cookie to registers statistical data on users' behaviour on the website for internal analytics.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Cookie
Duration
Description
bcookie
1 year
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.
bscookie
1 year
LinkedIn sets this cookie to store performed actions on the website.
li_sugr
3 months
LinkedIn sets this cookie to collect user behaviour data to optimise the website and make advertisements on the website more relevant.
VISITOR_INFO1_LIVE
5 months 27 days
YouTube sets this cookie to measure bandwidth, determining whether the user gets the new or old player interface.
YSC
session
Youtube sets this cookie to track the views of embedded videos on Youtube pages.
yt-remote-connected-devices
never
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
yt-remote-device-id
never
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.
yt.innertube::nextId
never
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.
yt.innertube::requests
never
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.