How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -
i trying ip address of vm , trying use establish ssh vm. following script:
--- - hosts: localhost become: yes connection: local gather_facts: false serial: 1 vars_files: - createvmvars.yml tasks: - name: gathering vm info. vsphere_guest: vcenter_hostname: "{{vcenter_hostname}}" username: "{{vcenter_username}}" password: "{{vcenter_password}}" guest: "{{guest_name}}" vmware_guest_facts: yes register: var - debug: msg="{{var.ansible_facts.hw_eth0.ipaddresses[0]}}" - name: establishing ssh connection. script: /home/shasha/devops/scripts/ssh_configure.sh "{{var.ansible_facts.hw_eth0.ipaddresses[0]}}"
following content of ssh_configure.sh :
#!/bin/sh ssh-keygen -t rsa ssh-copy-id $1
but when running playbook, getting following error while executing third task:
error! 'var' undefined
but debug module(second task) printing ip address.
what can possible problem or can done way ?
you should list version of ansible you're using best help. answer question, need quote whole command string:
- name: establishing ssh connection. script: "/home/shasha/devops/scripts/ssh_configure.sh {{var.ansible_facts.hw_eth0.ipaddresses[0]}}"
this should fix undefined variable issue.
that said you're doing won't work because assuming newly provisioned vm, ssh-copy-id going prompt password can login , newly created (possibly) pub key added authoized_keys. assuming know ssh password new vm here's suggest.
1 - facts vm
2 - dynamically add host inventory using add_host. using ip got fact gathering. make sure add ansible_ssh_password can login without being prompted.
- add_host: name="{{guest_name}}" ansible_ssh_host="{{var.ansible_facts.hw_eth0.ipaddresses[0]}}" ansible_ssh_pass="{{guest_password}}" groups=dynamic_hosts
use built-in ansible modules move public key over (for future playbook use), copy , execute them in shell. example next play like:
- hosts: dynamic_hosts tasks: - name: move on public key authorized_key: user=foo key="{{ lookup('file', '~/.ssh/id_rsa.pub') }}" - name: copy on script files copy: src=scripts/{{item}} dest=scripts/{{items}} with_items: - foo.bash - bar.py - thing.pl - name: run script files shell: "scripts/{{item}}" with_items: - foo.bash - bar.py - thing.pl
Comments
Post a Comment