是否可以在Ansible主机上运行命令?
我的场景是,我想从内部托管的git服务器(在公司防火墙之外无法访问)进行签出。然后,我想将签出(压缩)上传到生产服务器(外部托管)。
目前,我正在考虑运行一个执行签出的脚本,tarball它,然后运行部署脚本-但如果我可以将其集成到Ansible,那将是更可取的。
是否可以在Ansible主机上运行命令?
我的场景是,我想从内部托管的git服务器(在公司防火墙之外无法访问)进行签出。然后,我想将签出(压缩)上传到生产服务器(外部托管)。
目前,我正在考虑运行一个执行签出的脚本,tarball它,然后运行部署脚本-但如果我可以将其集成到Ansible,那将是更可取的。
当前回答
你可以使用delegate_to在你的Ansible主机(管理主机)上运行命令,从那里你正在运行你的Ansible play。例如:
删除Ansible主机上已经存在的文件:
- name: Remove file if already exists
file:
path: /tmp/logfile.log
state: absent
mode: "u+rw,g-wx,o-rwx"
delegate_to: 127.0.0.1
在Ansible主机上创建一个新文件:
- name: Create log file
file:
path: /tmp/logfile.log
state: touch
mode: "u+rw,g-wx,o-rwx"
delegate_to: 127.0.0.1
其他回答
你可以使用delegate_to在你的Ansible主机(管理主机)上运行命令,从那里你正在运行你的Ansible play。例如:
删除Ansible主机上已经存在的文件:
- name: Remove file if already exists
file:
path: /tmp/logfile.log
state: absent
mode: "u+rw,g-wx,o-rwx"
delegate_to: 127.0.0.1
在Ansible主机上创建一个新文件:
- name: Create log file
file:
path: /tmp/logfile.log
state: touch
mode: "u+rw,g-wx,o-rwx"
delegate_to: 127.0.0.1
扩展@gordon的回答,这里有一个可读的语法和参数通过shell/命令模块传递的示例(这些与git模块的不同之处是,有必需的但自由形式的参数,如@ander所述)
- name: "release tarball is generated" local_action: module: shell _raw_params: git archive --format zip --output release.zip HEAD chdir: "files/clones/webhooks"
我想分享Ansible可以通过shell在localhost上运行:
Ansible all -i "localhost ", -c local -m shell -a 'echo hello world'
这可能对简单的任务或Ansible的一些实践学习有帮助。
代码示例摘自这篇好文章:
在本地主机运行ansible playbook
使用ansible-playbook -i "localhost," -c local your_file_name.yml
注意,“localhost”后面必须有逗号。
例子:
我们正在使用shell模块在localhost中运行' echo hello world '。现在让我们写一个剧本helloworld.yml
---
- hosts: all
tasks:
- shell: echo "hello world"
运行剧本:
ansible-playbook -i "localhost," -c local helloworld.yml
输出:
PLAY [all] *********
GATHERING FACTS *********
ok: [localhost]
TASK: [shell echo "hello world"] *********
changed: [localhost]
PLAY RECAP *********
localhost : ok=2 changed=1 unreachable=0 failed=0
引用:
在本地主机运行ansible playbook: https://web.archive.org/web/20180513205612/http://ansible.pickle.io/post/86598332429/running-ansible-playbook-in-localhost
恕我直言,我发现了一些其他的方法来写这些东西,它们更容易读。
- name: check out a git repository
local_action:
module: git
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path
OR
- name: check out a git repository
local_action: git
args:
repo: git://foosball.example.org/path/to/repo.git
dest: /local/path