I have to process output from CloudFormation Outputs
that is:
Ansible code that produces this output:
- debug:
var: stack.stack_outputs
Output:
ok: [localhost] => {
"stack.stack_outputs": {
"Roles": "webserver balancer dbserver",
"dbserver": "54.0.1.1 54.0.1.2",
"balancer": "54.0.2.3",
"webserver": "54.0.2.5 54.0.2.7 54.0.3.1"
}}
With that, I want to create 3 (dynamic number!) groups named accordingly filled with appropriate IPs.
Ansible code that I want to HELP WITH:
- name: fill roles with proper hosts
local_action: add_host hostname={{item}} groupname={{role}}
with_whatever: ?...?
In pseudo ansible python it would look like this:
for role in stack.stack_outputs.Roles.split(): # Python
for ip in stack.stack_outputs[role].split(): # Python
local_action: add_host hostname={{ip}} groupname={{role}} # Ansible
Note:
The way to do it for these three roles statically is obviously:
- name: fill role WEBSERVER
local_action: add_host hostname={{item}} groupname=webserver
with_items: stack.stack_outputs.webserver.split()
- name: fill role DBSERVER
local_action: add_host hostname={{item}} groupname=dbserver
with_items: stack.stack_outputs.dbserver.split()
- name: fill role BALANCER
local_action: add_host hostname={{item}} groupname=balancer
with_items: stack.stack_outputs.balancer.split()
I want to do it dynamically, is it even possible in Ansible?
Yes, I can use shell module
to hack it putting everything in temporary file and then looping over that; but is there a better solution?
Thanks for any suggestions.
Best Answer
It can be done using nested loops and includes, example of working script
test.yml
:dynamic.yml
:Example of running using
ansible-playbook 2.1.2.0
:You need Ansible 2.1 or above to run it.