如何区分分段/生产与动态库存?

Eln*_*mov 6 ansible ansible-playbook

我被卡住了.用网络搜索地狱,无法找到答案.

我多年来一直在使用Ansible,但总是使用静态库存.针对不同的环境,如分期和生产区分开来,我用不同的静态清单文件,stagingproduction分别.当我需要配置登台服务器时,我会这样做:

ansible-playbook site.yml -i staging
Run Code Online (Sandbox Code Playgroud)

当我想为生产做同样的事情时,我会这样做:

ansible-playbook site.yml -i production
Run Code Online (Sandbox Code Playgroud)

分段和生产都需要具有不同值的变量,所以我有group_vars/staginggroup_vars/production.一切都很好,并根据最佳实践.

现在,我需要在AWS中配置EC2实例.我正在使用此AWS指南.我有一个有两个剧本的剧本.第一个是localhost在AWS中运行,创建/查找所需的EC2实例,并使用填充组add_host.第二个游戏使用该组来对抗在第一个游戏中发现的EC2实例.全部根据该指南.

除了一件事,这一切都很有效.我不知道如何指定要配置的环境,因此未加载所需的变量group_vars/(staging|production).基本上,我想要的是类似于-i (staging|production)我多年来使用静态库存的东西,但似乎现在使用-i没有意义,因为库存是动态的.我希望有一种方法可以从任何一个group_vars/staginggroup_vars/production基于ansible-playbook我运行它时传递给的参数加载变量.

我怎么做?什么是最佳做法?

Tym*_*aul 4

While I am not sure how to do it with ansible EC2 moduel as we don't use it to build boxes from ansible level, there is a simple way to get what you want with ec2 external inventory script and simple settings in your inventories/main. What you need to do is set up the ec2.py and ec2.ini inside of your inventories so it will be used as source of instances. Make sure to uncomment group_by_tag_keys = True inside of ec2.ini.

Next step is to differentiate which instance goes where. While there are many selection methods available in ec2.py, I prefer to specifically tag each instance accordingly. So all my instances have a tag called environment which is filled accordingly (in your case it would be either staging or production). Then all is left is to handle it inside of your inventories/main, and here is a small example how to do it.

First you must define empty group for tags you want to use:

[tag_environment_staging]

[tag_environment_production]
Run Code Online (Sandbox Code Playgroud)

so we can later reference to them. After that all there is left to do is specify those groups as children for appropriate stages. So after that our minimal file will look like that:

[tag_environment_staging]

[tag_environment_production]

[staging:children]
tag_environment_staging

[production:children]
tag_environment_production
Run Code Online (Sandbox Code Playgroud)

就这样吧。从现在开始,通过带有环境标签的动态库存脚本从 ec2 拉取的每个实例都将与group_vars. 您必须记住,在处理动态清单时,您希望-i指向inventories目录而不是特定文件,以便它正常工作。