In Ansible, how to get a variable from another variable and then fetch it's value

546 views
Skip to first unread message

Arbab Nazar

unread,
Dec 27, 2015, 2:20:57 PM12/27/15
to Ansible Project

Here is my problem I need to use one variable 'RDS_SG_NAME' and then append '_id' to it's value to get another variable name which value I want/need. My simple playbook look like this:

---
- hosts: localhost
  connection: local
  gather_facts: no 
  vars:
    abc_id: 'some-value'
    RDS_SG_NAME: 'abc'
    RDS_SG_ID: "{{ RDS_SG_NAME +'_id' }}"
  tasks:
    - debub: msg="{{ RDS_SG_NAME }}"
    - debub: msg="{{ RDS_SG_ID }}"

when I run this playbook, it give the values like this: RDS_SG_NAME: abc RDS_SG_ID: abc_id But I want the some-value againt it, can someone point me to the right direction.

Thanks in advance

Pradeep Reddy

unread,
Dec 28, 2015, 4:19:50 AM12/28/15
to Ansible Project
I do this generally, if I want to use a variable name as a value to another variable


---

- hosts: localhost
  connection: local
  gather_facts: no
  pre_tasks:
  - set_fact:
      abc_id: 'some-value'
      RDS_SG_NAME: 'abc'


- hosts: localhost
  connection: local
  gather_facts: no
  pre_tasks:
  vars:
    RDS_SG_ID: "{{ hostvars[inventory_hostname][RDS_SG_NAME+'_id']}}"
  tasks:
    - debug: var=RDS_SG_NAME
    - debug: var=RDS_SG_ID

Pradeep Reddy

unread,
Dec 28, 2015, 4:23:11 AM12/28/15
to Ansible Project
Ignore pre_tasks in second play.
The thing to note is the usage of hostvars.


On Monday, December 28, 2015 at 12:50:57 AM UTC+5:30, Arbab Nazar wrote:
Reply all
Reply to author
Forward
0 new messages