How to create a file locally with ansible templates on the development machine

六眼飞鱼酱① 提交于 2019-12-12 09:29:41

问题


I'm starting out with ansible and I'm looking for a way to create a boilerplate project on the server and on the local environment with ansible playbooks.

I want to use ansible templates locally to create some generic files. But how would i take ansible to execute something locally?

I read something with local_action but i guess i did not get this right.

This is for the webbserver...but how do i take this and create some files locally?


- hosts: webservers
      remote_user: someuser
- name: create some file
    template: src=~/workspace/ansible_templates/somefile_template.j2 dest=/etc/somefile/apps-available/someproject.ini

回答1:


You can delegate tasks with the param delegate_to to any host you like, for example:

- name: create some file
  template: src=~/workspace/ansible_templates/somefile_template.j2 dest=/etc/somefile/apps-available/someproject.ini
  delegate_to: localhost

See Playbook Delegation in the docs.

If your playbook should in general run locally and no external hosts are involved though, you can simply create a group which contains localhost and then run the playbook against this group. In your inventory:

[local]
localhost

and then in your playbook:

hosts: local



回答2:


Ansible has a local_action directive to support these scenarios which avoids the localhost and/or ansible_connection workarounds and is covered in the Delegation docs.

To modify your original example to use local_action:

- name: create some file
    local_action: template src=~/workspace/ansible_templates/somefile_template.j2 dest=/etc/somefile/apps-available/someproject.ini

which looks cleaner.




回答3:


If you cannot do/allow localhost SSH, you can split the playbook on local actions and remote actions.

The connection: local says to not use SSH for a playbook, as shown here: http://docs.ansible.com/ansible/playbooks_delegation.html#local-playbooks

Example:

# myplaybook.yml

- hosts: remote_machines
  tasks:
  - debug: msg="do stuff in the remote machines"

- hosts: 127.0.0.1
  connection: local
  tasks:
  - debug: msg="ran in local ansible machine"

- hosts: remote_machines
  tasks:
  - debug: msg="do more stuff in remote machines"


来源:https://stackoverflow.com/questions/31383693/how-to-create-a-file-locally-with-ansible-templates-on-the-development-machine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!