Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a var in a var in Ansible (lookup) - aws_ssm plugin

I'm trying to use a var in a var declaration on Ansible (2.7.10)

I'm using aws_ssm lookup plugin (https://docs.ansible.com/ansible/latest/plugins/lookup/aws_ssm.html)

Working example (hardcoded values):

var: "{{ lookup('aws_ssm', '/path/server00', region='eu-west-3') }}"

I want to use variables for the server name and the AWS region, but all my tentatives went on errors.

What I've tried so far:

var: "{{ lookup('aws_ssm', '/path/{{ server }}', region={{ region }}) }}"
var: "{{ lookup('aws_ssm', '/path/{{ server }}', region= + region) }}"
    - name: xxx
      debug: msg="{{ lookup('aws_ssm', '/path/{{ server }}', region='{{ region }}' ) }}"
      register: var

Without any success yet, thanks for your help,

like image 495
zoph Avatar asked Oct 30 '25 12:10

zoph


1 Answers

You never nest {{...}} template expressions. If you're already inside a template expression, you can just refer to variables by name. For example:

var: "{{ lookup('aws_ssm', '/path/' + server, region=region) }}"

(This assumes that the variables server and region are defined.)

You can also take advantage of Python string formatting syntax. The following will all give you the same result:

  • '/path/' + server
  • '/path/%s' % (server)
  • '/path/{}'.format(server)

And instead of + you can use the Jinja ~ concatenation operator, which acts sort of like + but forces arguments to be strings. So while this is an error:

  • 'some string' + 1

This will result in the text some string1:

  • 'some string' ~ 1
like image 59
larsks Avatar answered Nov 01 '25 13:11

larsks