Concatenate strings using with_items and assign to a variable in Ansible

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

why dont you…concatenate strings to a list and then join the list instead to make the string?

Few things come to mind when looking at your code

  1. Why are you using iptables? Security groups would take away a lot of problems especially the dynamics that you seem to working around with iptables.

  2. If you need to restrict access between ec2 instances, why do you use public interfaces for communication?

If you let us know what high level goal you are trying to achieve with your playbook? There might be better/easier ways to achieve it.

Dick