local_action
在针对一组主机运行剧本时,是否可以在 ansible 中使任务仅运行一次?
问题如下:
hosts:
- macbooks
- localhost
tasks:
#...<some_remote_tasks>...#
- local_action: command
ssh-keygen -o -a 100 -t ed25519 -f {{ ssh_key }} -q -N ''
become: yes
结果:
fatal: [laptop -> localhost]: FAILED! => {"changed": true, "cmd": ["ssh-keygen", "-o", "-a", "100", "-t", "ed25519", "-f", "/etc/ssh/id_ed25519-HostCA", "-q", "-N", "", "-C", "SSH Host Certificate Authority for cypherpunk.synology.me"], "delta": "0:00:00.014818", "end": "2018-06-01 17:02:41.599111", "msg": "non-zero return code", "rc": 1, "start": "2018-06-01 17:02:41.584293", "stderr": "", "stderr_lines": [], "stdout": "/etc/ssh/id_ed25519-HostCA already exists.\nOverwrite (y/n)? ", "stdout_lines": ["/etc/ssh/id_ed25519-HostCA already exists.", "Overwrite (y/n)? "]}
changed: [localhost -> localhost]
这是有道理的,因为剧本中的任何任务都必须为每个托管主机运行。
但因为它是一个本地操作,所以它第一次按预期运行并创建密钥文件。第二次运行该文件已经存在,ansible 收到错误:"/etc/ssh/id_ed25519-HostCA already exists. Overwrite (y/n)?"
with return code 1
。所以实际上它只能运行一次(至少在这种情况下)。
我可以做类似的事情:
- local_action: shell >
[[ ! -f {{ ssh_key }} ]] && \
ssh-keygen -o -a 100 -t ed25519 -f {{ ssh_key }} -q -N ''; \
exit 0
become: yes
但我想知道是否有 ansible 推荐的解决方案?你们将如何解决这个问题?
答案1
也许你应该检查:run_once&delegate_to
- command: /opt/application/upgrade_db.py
run_once: true
delegate_to: web01.example.org
文件:https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html
亲切的问候,
C