Ansible循环中无外部主机文件的SSH远程执行命令及凭证配置问询
Ansible Tower循环远程执行SSH命令的配置问题
我需要通过Ansible以SSH方式远程执行Shell命令,但不使用外部主机文件。主机信息来自循环中的当前item,因此需在循环中为每个item执行远程命令,我已有循环但不确定SSH相关代码的写法。用户名和密码为Ansible Tower中的变量,可通过
{{username}}和{{password}}调用。现有代码如下:- name: Connect to remote servers via SSH hosts: "{{item}}" gather_facts: no connection: ssh tasks: - name: Run command on remote server command: uptime register: uptime_output请问这段代码是否正确?应在哪里配置凭证?
代码问题说明
你的现有代码不正确,核心问题是Play层面的hosts参数无法直接引用循环变量{{item}}——Play是Ansible的执行单元,启动时就需要确定目标主机列表,无法在Play运行过程中动态循环hosts。
修正方案与凭证配置
方案1:任务层面循环+delegate_to
把循环逻辑放在任务级别,通过delegate_to指定每台目标主机,同时直接在任务或Play中配置SSH凭证:
- name: Run commands on remote servers hosts: localhost gather_facts: no vars: target_hosts: ["host1.example.com", "host2.example.com"] # 替换为你的循环主机列表 tasks: - name: Execute uptime on each remote host command: uptime register: uptime_output delegate_to: "{{item}}" vars: ansible_user: "{{username}}" ansible_password: "{{password}}" ansible_ssh_common_args: "-o StrictHostKeyChecking=no" # 可选,跳过首次连接的主机密钥检查 with_items: "{{target_hosts}}" - name: Print command output debug: msg: "Host {{item.item}} uptime: {{item.stdout}}" with_items: "{{uptime_output.results}}"
方案2:动态添加主机再执行Play
先通过add_host模块把循环中的主机添加到临时主机组,再针对该组执行任务,凭证可随主机一起配置:
- name: Add target hosts dynamically hosts: localhost gather_facts: no vars: target_hosts: ["host1.example.com", "host2.example.com"] tasks: - name: Add hosts to temporary group add_host: name: "{{item}}" groups: temp_remote_hosts ansible_user: "{{username}}" ansible_password: "{{password}}" ansible_ssh_common_args: "-o StrictHostKeyChecking=no" with_items: "{{target_hosts}}" - name: Run commands on dynamic hosts hosts: temp_remote_hosts gather_facts: no connection: ssh tasks: - name: Execute uptime command command: uptime register: uptime_output - name: Show result debug: msg: "{{inventory_hostname}} uptime: {{uptime_output.stdout}}"
Ansible Tower专属凭证配置方式
除了在Playbook中直接调用变量,还可以用Tower的原生能力管理凭证:
- 关联Machine凭证:在Tower中创建一个「Machine」类型的凭证,填入用户名和密码,然后在对应的Job Template中关联该凭证。Tower会自动将凭证信息注入到Playbook的执行环境中,无需在Playbook中显式配置。
- 存入Tower变量库:把
username和password添加到Tower的项目变量、团队变量或组织变量中,Playbook直接调用即可,无需额外编写凭证配置逻辑。
内容的提问来源于stack exchange,提问作者LJS
相关产品推荐
相关产品推荐

