Miantian
Miantian

Reputation: 1075

Is it possible to set variable in variable with ansible?

For example, set a username for each different service as

    - name: Add the user 'user_xxx' with password
      ansible.builtin.user:
        name: "{{ user_name_{{svc_name}} }}"
        password: "{{ user_password_{{svc_name}} | password_hash('sha512') }}"

In order to set dynamic values to name and password, use thess variables in group_vars:

user_name_a
user_name_b
user_name_c
user_password_a
user_password_b
user_password_c

But want to read a, b, c from an environment variable as:

export SERVICE_NAME=a

playbook:

vars:
  svc_name: "{{ lookup('env', 'SERVICE_NAME') }}"

Then compile 2 kinds of variables together to make a final value.

When I tried to do it, I got

fatal: [server]: FAILED! => {"msg": "template error while templating string: expected token 'end of print statement', got '{'. String: {{ user_name_{{svc_name}} }}"}

Upvotes: 4

Views: 1188

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

For example, given the group_vars

shell> cat group_vars/all.yml
user_name_a: userA
user_name_b: userB
user_name_c: userC
user_password_a: psswdA
user_password_b: psswdB
user_password_c: psswdC

the playbook

shell> cat playbook.yml
- hosts: localhost
  vars:
    svc_name: "{{ lookup('env', 'SERVICE_NAME') }}"
  tasks:
    - debug:
        msg: "name: {{ lookup('vars', 'user_name_' ~ svc_name) }},
              pswd: {{ lookup('vars', 'user_password_' ~ svc_name) }}"

gives

shell> SERVICE_NAME=b ansible-playbook playbook.yml 

PLAY [localhost] ****************************************************************

TASK [debug] ********************************************************************
ok: [localhost] => 
  msg: 'name: userB, pswd: psswdB'

  ...

Upvotes: 4

Related Questions