将播放簿信息保存到主机文件

Sim*_*ton 3 ansible

我有一个使用Ansible内置核心模块在DigitalOcean上创建新Droplet的手册:

- name: Provision droplet on DigitalOcean
  local_action: digital_ocean
    state=present
    ssh_key_ids=1234
    name=mydroplet
    client_id=ABC
    api_key=ABC
    size_id=1
    region_id=2
    image_id=3
    wait_timeout=500
  register: my_droplet
- debug: msg="ID is {{ my_droplet.droplet.id }}"
- debug: msg="Your droplet has the IP address of {{ my_droplet.droplet.ip_address }}"
Run Code Online (Sandbox Code Playgroud)

我运行它(注意本地参数):

ansible-playbook playbooks/create_droplet.yml -c local -i playbooks/hosts
Run Code Online (Sandbox Code Playgroud)

我的hosts文件最初看起来像这样:

[production]
TBA

[localhost]
localhost
Run Code Online (Sandbox Code Playgroud)

当上面的剧本完成后,我可以在STDOUT中看到调试信息:

ok: [localhost] => {
    "msg": "Your droplet has the IP address of 255.255.255.255"
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让这个剧本保留my_droplet.ip_address变量并将TBA保存在hosts文件中,而不必手动复制 - 在那里拼写它?我问,因为我想将这个配置剧本添加到ruby脚本中,随后用另一个剧本引导VPS.

小智 7

我正在做同样的事情,写了一个从dict创建服务器的游戏(一次约53个服务器,动态创建一个完整的测试环境).要使用静态主机文件,我添加以下内容:

- name: Create in-memory inventory
  add_host:
    name: "{{ item.value.ServerName }}"
    groups: "{{ item.value.RoleTag }},tag_Environment_{{ env_name }}"
  when: item.value.template is defined 
  with_dict: server_details  

- name: create file
  become: yes
  template:
    src: ansible-hosts.j2
    dest: "{{ wm_inventory_file }}"
Run Code Online (Sandbox Code Playgroud)

ansible-hosts.j2模板很简单:

{% for item in groups %}

[{{item}}]
{%   for entry in groups[item] %}
{{ entry }}
{%   endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)