Concatenate strings using with_items and assign to a variable in Ansible

房东的猫 提交于 2020-12-06 12:31:06

问题


I need to save two 2 IPs to a variable in a vars_file when launching ec2_instances, which are used later during deployment.

This is how I am saving a single server ip:

- name: Save server public IP to vars file
  lineinfile: line="server_public_ip{{':'}} {{ item.public_ip }}"
              dest="{{ansible_env.HOME}}/dynamic_ips_{{ec2_environment}}"
  with_items: server.instances  #server is registered in previous task

The output I have in dynamic_ips file is server_public_ip: xxx.xxx.xx.x

Now I have 2 servers launched and registered as servers.

I need to save this as server_public_ips: xxx.xx.x.xx , xxx.x.xx.x

I tried to declare an empty string and append ips to it, something like this, but I am getting errors.

set_fact:
   ips: ""
set_fact:
   ips: " {{ ips }} + {{ item.public_ip}} "
with_items: servers.instances  #servers is registered in previous task
lineinfile: line="server_public_ips{{':'}} {{ ips }}"
            dest="{{ansible_env.HOME}}/dynamic_ips_{{ec2_environment}}"

I think it can be done using lineinfile insertafter and regex.

Finally, I need this to do this in a different server,

- name: Restrict access to outside world
  command: iptables INPUT {{ item }} ACCEPT
  with_items: {{ server_public_ips }}.split(,) #grant access for each ip 
  command: iptables INPUT DROP

回答1:


set_fact:
   ips: " {{servers.instances | join(',') }} "

should actually work when servers.instances is a list.



来源:https://stackoverflow.com/questions/42904705/concatenate-strings-using-with-items-and-assign-to-a-variable-in-ansible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!