问题描述
我需要在启动 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 中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!