Sybie
Sybie

Reputation: 71

ansible correct way of calling + creating the variable

I run into a problem and was hoping I could get some help.
I am trying to create a file based on a variable name, that contains a variable.
app-inputs/app1.yml

---
app_name: "labo.{{ environment }}.eng.inet.com"
environment:
  - int
  - lab

when I try to create the file:
roles/buld_config/tasks/main.yml

---
- name: create destination file
  file:
    path: "{{ folder_path ~ item[0] }}/{{ item[1] }}.yml"
  with_nested:
    - "{{ config_folders }}"
    - "{{ app_name }}"

I encounter the following problem:
"msg": "file (/etc/scripts/app-configs/[].labo.eng.inet.com.yml) is absent, cannot continue"
The variable {{environment}} does not get populated.

I see the problem: nowhere, do i tell them to loop over the environments, but I don't see, how to do this correctly.

The final goal is to create a file for lab in the lab directory, based on a jinja2 template, create the config. Next it would be int environment, etc...

The environments are not fixed and can be different per app, hence they are defined in the -e @app-inputs/app1.yml file

I was hoping I could get some help of people more knowledgeable than me with ansible, as it's one of my first attempts.

Your help would be greatly appreciated!

Upvotes: 0

Views: 54

Answers (1)

BinaryMonster
BinaryMonster

Reputation: 1208

Hey I understand the situation. There are several ways one can resolve this, it also depends on what we would be achieving by ansible.

So from the above situation, I could suggest one small simple solution. But, like I said there are several ways one can do it, and this is one of them. Maybe, you will see everyone contributing to this question.

Here is one solution:

app-inputs/app1.yml variables would look like

---
app_name: "labo.eng.inet.com"
environment:
  - int
  - lab

roles/buld_config/tasks/main.yml your task would look like

---
- name: create destination file
  file:
    path: "{{ item[0] }}/{{ item[2] }}.{{ item[1] }}.yml"
  with_nested:
    - "{{ config_folders }}"
    - "{{ app_name }}"
    - "{{ environment }}"

Hope this helps, but this is some what looks like hack. I can suggest some more based on your comment.

Update

Based on the comment here is the updated answer, again there are several ways one can achieve this.

app-inputs/app1.yml variables would look like

---
app_name_lab: "labo.eng.lab.inet.com"
app_name_int: "labo.eng.int.inet.com"
#I am aware environment is a reserved keyword in ansible, use your own word.
environment: 
  - int
  - lab

roles/build_config/tasks/main.yml your task would look like

---
- name: create destination file
  file:
    path: "{{ item[0] }}/{{ vars['app_name_'+item[1] ] }}.yml"
  with_nested:
    - "{{ config_folders }}"
    - "{{ environment }}"

Hope this solves your problem. Again this is not the only possible solution, there are several ways one can achieve this.

Upvotes: 1

Related Questions