title: Concatenate strings using with_items and assign to a variable in Ansible
body: <p>I need to save two 2 IPs to a variable in a vars_file when launching ec2_instances, which are used later during deployment.</p>
  
  <p>This is how I am saving a single server ip:</p>
  
  <pre><code>- 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
  </code></pre>
  
  <p>The output I have in dynamic_ips file is <strong><code>server_public_ip: xxx.xxx.xx.x</code></strong></p>
  
  <p>Now I have 2 servers launched and registered as servers.</p>
  
  <p>I need to save this as <strong><code>server_public_ips: xxx.xx.x.xx , xxx.x.xx.x</code></strong></p>
  
  <p>I tried to declare an empty string and append ips to it, something like this, but I am getting errors.</p>
  
  <pre><code>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}}"
  </code></pre>
  
  <p>I think it can be done using lineinfile insertafter and regex.</p>
  
  <p>Finally, I need this to do this in a different server,</p>
  
  <pre><code>- 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
  </code></pre>