使用with_items连接字符串并分配给Ansible中的变量 [英] Concatenate strings using with_items and assign to a variable in Ansible

查看:152
本文介绍了使用with_items连接字符串并分配给Ansible中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启动ec2_instances时,我需要将两个2个IP保存到vars_file中的一个变量中,稍后将在部署过程中使用它们.

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

这是我保存单个服务器IP的方式:

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

dynamic_ips文件中的输出为 server_public_ip:xxx.xxx.xx.x

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

现在我启动了2台服务器,并注册为服务器.

Now I have 2 servers launched and registered as servers.

我需要将其另存为 server_public_ips:xxx.xx.x.xx,xxx.x.xx.x

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

我试图声明一个空字符串并在其后附加ips,类似这样,但是我遇到了错误.

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}}"

我认为可以使用lineinfile insertafter和regex来完成.

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

推荐答案

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

当servers.instances是一个列表时,应该实际上可以工作.

should actually work when servers.instances is a list.

这篇关于使用with_items连接字符串并分配给Ansible中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆