我在AWS中使用多个ec2实例并在这些实例上安装cassandra。 我在cassandra文件中动态更新这些实例的IP地址。
我尝试使用set facts模块在不同的播放之间传递变量,它正在更新所有文件中由三个ec2实例构建的最后一台机器的ip地址。 我的用例是更新文件中关于该ec2实例的IP地址。
###########################################################
Here is my playbook which consists of two plays:
#### Play1 - to spin 3 ec2 instances in AWS##########
- name: Play1
hosts: local
connection: local
gather_facts: True
vars:
key_location: "path to pem file location"
server_name: dbservers
private_ip: item.private_ip
tasks:
- name: create ec2 instance
ec2:
key_name: {{ my_key_name}}
region: us-east-1
instance_type: t2.micro
image: ami-8fcee4e5
wait: yes
group: {{ my_security_group_name}}
count: 3
vpc_subnet_id: {{ my_subnet_id }}
instance_tags:
Name: devops-i-cassandra1-d-1c-common
Stack: Ansible
Owner: devops
register: ec2
- name: set facts ## to capture the ip addresses of the ec2 instances, but only last ip is being captured
set_fact:
one_fact={{ item.private_ip }}
with_items: ec2.instances
- name: debugging private ip value
debug: var=one_fact
- name: Add the newly created EC2 instance(s) to the dbservers group in the inventory file
local_action: lineinfile
dest="/home/admin/hosts"
regexp={{ item.private_ip }}
insertafter="[dbservers]" line={{ item.private_ip }}
with_items: ec2.instances
- name: Create Host Group to login dynamically to EC2 Instance
add_host:
hostname={{ item.private_ip }}
groupname={{ server_name }}
ansible_ssh_private_key_file={{ key_location }}
ansible_ssh_user=ec2-user
ec2_id={{ item.id }}
with_items: ec2.instances
- name: Wait for SSH to come up
local_action: wait_for
host={{ item.private_ip }}
port=22
delay=60
timeout=360
state=started
with_items: ec2.instances
####################Play2-Installing and Configuring Cassandra on Ec2 Instances
- name: Play2
hosts: dbservers
remote_user: ec2-user
sudo: yes
vars:
private_ip: "{{ hostvars.localhost.one_fact }}"
vars_files:
- ["/home/admin/vars/var.yml"]
tasks:
- name: invoke a shell script to install cassandra
script: /home/admin/cassandra.sh creates=/home/ec2-user/cassandra.sh
- name: configure cassandra.yaml file
template: src=/home/admin/cassandra.yaml dest=/etc/dse/cassandra/cassandra.yaml owner=ec2-user group=ec2-user mode=755
#
提前致谢
答案 0 :(得分:1)
使用ansible 2.0+,您可以刷新剧本中间的动态库存,如下所示:
- meta: refresh_inventory
要扩展一下,如果你的剧本中的缓存出现问题,那么你可以像这样使用它:
- name: Refresh the ec2.py cache
shell: "./inventory/ec2.py --refresh-cache"
changed_when: no
- name: Refresh inventory
meta: refresh_inventory
其中./inventory
是动态广告资源的路径,请相应调整。
在创建EC2实例期间,您已向其添加了标记,您现在可以使用动态清单来配置这些实例。你的第二场比赛将是这样的:
- name: Play2
hosts: tag_Name_devops-i-cassandra1-d-1c-common
remote_user: ec2-user
sudo: yes
tasks:
- name: ---------
希望这会对你有所帮助。