Search code examples
sshansiblecommand

SSH connection from Ansible for the current "item" (from the loop) and with credentials


I have to execute some shell commands remotely (via SSH) from Ansible, but without external hosts file.

Host information is actually current "item" from the loop, so I have to execute some commands remotely while in this loop (for each item). I already have a loop, but I'm not sure about the code for ssh.

Username and password are variables from Ansible Tower that I can call in this task i.e. "{{username}}" and "{{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

Is this code correct and where do I put credentials in it?

Thanks.


Solution

  • I understand your question that you are looking for

    • How to connect to a host not in inventory file?
    • How to connect to Linux VMs using variables?

    As already commented this is a use case for add_host module – Add a host (and alternatively a group) to the ansible-playbook in-memory inventory. The following minimal example shows a solution approach.

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
      - add_host:
          hostname: "{{ item }}"
          group: vcenter_vms
        loop: "{{ LIST_OF_VMS }}"
    
    - hosts: vcenter_vms
      become: false
      gather_facts: false
      remote_user: "{{ username }}"
      ansible_ssh_pass: "{{ password }}"
    
      tasks:
    
      - name: Show hostname
        shell:
          cmd: "hostname && who am i"
        register: result
    
      - name: Show result
        debug:
          var: result
    

    You need only take care of the difference between your initial playbook running ansible_user and the later used remote_user (annot.: which is only an alias for better understanding, see Ansible ansible_user vs remote_user), as well the ansible_ssh_pass, the remote_password.

    Similar Q&A

    I like also to recommend other Stack sites with more advanced examples.

    You can also just search with tag [ansible] and keyword add_host for more examples.