ansible read ip address from hosts - ansible

I need to set date to remote host, so I read localhost date then need to get the otherhost "ipv4_address" that is defined in hosts file of ansible.
- hosts: localhost
become_user : root
tasks:
- name: align datetime
shell: |
data="$(date +'%Y/%m/%d +%H:%m:00')"
ssh user#{{ otherhost.ipv4_address }} "sudo date -s $data"
- hosts: otherhost
become: true
his tasks....
but it seems that is not the correct way to get the ipv4:
fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option
with an undefined variable. The error was: 'otherhost.ipv4_address ' is
undefined\n\nThe error appears to be in
ansible --version
ansible 2.9.2
config file = None
configured module search path = ['/home/tec1/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/tec1/.local/share/virtualenvs/sniperx-EdPGXWMw/lib/python3.7/site-packages/ansible
executable location = /home/tec1/.local/share/virtualenvs/sniperx-EdPGXWMw/bin/ansible
python version = 3.7.3 (default, Apr 3 2019, 05:39:12) [GCC 8.3.0]

The problem is that {{ otherhost.ipv4_address }} is not available at the time you are using it as ansible hasnt gathered facts about otherhost.
A few options are available to you:
Gather facts before you start using the data, for example
---
- hosts: all
gather_facts: true
# here you gather facts about otherhost
- hosts: localhost
tasks:
- debug: var=hostvars["otherhost"].ansible_all_ipv4_addresses
# and here you can access those facts about
Run the playbook at the remote host and delegate the localhost time before hand, for example
- hosts: otherhost
tasks:
- name: get localhost time
shell: date +'%Y/%m/%d +%H:%m:00'
become: false
register: local_date
- name: set the date on the server
shell: sudo date -s '{{ local_date.stdout_lines[0] }}'
This takes advantage of ansibles way of auto-ssh-ing into the target box and you dont have to manual ssh.

Related

Ansible module lineinfile doesn't properly write all the output

I've written a small playbook to run the sudo /usr/sbin/dmidecode -t1 | grep -i vmware | grep -i product command and write the output in a result file by usign the following code as a .yml:
# Check if server is vmware
---
- name: Check if server is vmware
hosts: all
become: yes
#ignore_errors: yes
gather_facts: False
serial: 50
#become_flags: -i
tasks:
- name: Run uptime command
#become: yes
shell: "sudo /usr/sbin/dmidecode -t1 | grep -i vmware | grep -i product"
register: upcmd
- debug:
msg: "{{ upcmd.stdout }}"
- name: write to file
lineinfile:
path: /home/myuser/ansible/mine/vmware.out
create: yes
line: "{{ inventory_hostname }};{{ upcmd.stdout }}"
delegate_to: localhost
#when: upcmd.stdout != ""
When running the playbook against a list of hosts I get different weird results so even if the debug shows the correct output, when I check the /home/myuser/ansible/mine/vmware.out file I see only part of them being present. Even weirder is that if I run the playbook again, I will correctly populate the whole list but only if I run this twice. I have repeated this several times with some minor tweaks but not getting the expected result. Doing -v or -vv shows nothing unusual.
You are writing to the same file in parallel on localhost. I suspect you're hitting a write concurrency issue. Try the following and see if it fixes your problem:
- name: write to file
lineinfile:
path: /home/myuser/ansible/mine/vmware.out
create: yes
line: "{{ host }};{{ hostvars[host].upcmd.stdout }}"
delegate_to: localhost
run_once: true
loop: "{{ ansible_play_hosts }}"
loop_control:
loop_var: host
From your described case I understand that you like to find out "How to check if a server is virtual?"
The information will already be collected by the setup module.
---
- hosts: linux_host
become: false
gather_facts: true
tasks:
- name: Show Gathered Facts
debug:
msg: "{{ ansible_facts }}"
For an under MS Hyper-V virtualized Linux system, the output could contain
...
bios_version: Hyper-V UEFI Release v1.0
...
system_vendor: Microsoft Corporation
uptime_seconds: 2908494
...
userspace_architecture: x86_64
userspace_bits: '64'
virtualization_role: guest
virtualization_type: VirtualPC
and having already the uptime in seconds included
uptime
... up 33 days ...
For just only a virtual check one could gather_subset resulting into a full output of
gather_subset:
- '!all'
- '!min'
- virtual
module_setup: true
virtualization_role: guest
virtualization_type: VirtualPC
By Caching facts
... you have access to variables and information about all hosts even when you are only managing a small number of servers
on your Ansible Control Node. In ansible.cfg you can configure where and how they are stored and for how long.
fact_caching = yaml
fact_caching_connection = /tmp/ansible/facts_cache
fact_caching_timeout = 86400 # seconds
This would be a minimal and simple solution without re-implementing functionality which is already there.
Further Documentation and Q&A
Ansible facts
What is the exact list of Ansible setup min?

How to manually pass host name to ansible tower template at runtime

I am have a requirement like passing a server hostname at runtime to ansible tower template. the issue i faced is we dont know the hostname before running the template so we cant configure hostname in the ansible tower inventory. I tired googling but haven't found a solution yet.
my main.yaml file starting will be looking like this
- name: Execution server
hosts: <hostname>
gather_facts: false
serial: 1
the erroer i am getting is
1 plays in main.yml
[WARNING]: Could not match supplied host pattern, ignoring: <hostname>
You can use the target_host variable. I like setting a default with this
- name: Execution server
hosts: "{{ target_host | default('all') }} "
gather_facts: false
serial: 1
Define target_host in a job template's limit:

`remote_user` is ignored in playbooks and roles

I have defined the following in my ansible.cfg
# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
remote_user = ansible
However I have a playbook bootstrap.yaml where I connect with root rather than ansible
---
- hosts: "{{ target }}"
become: no
gather_facts: false
remote_user: root
vars:
os_family: "{{ osfamily }}}"
roles:
- role: papanito.bootstrap
However it seems that remote_user: root is ignored as I always get a connection error, because it uses the user ansible instead of root for the ssh connection
fatal: [node001]: UNREACHABLE! => {"changed": false,
"msg": "Failed to connect to the host via ssh:
ansible#node001: Permission denied (publickey,password).",
"unreachable": true}
The only workaround for this I could find is calling the playbook with -e ansible_user=root. But this is not convenient as I want to call multiple playbooks with the site.yaml, where the first playbook has to run with ansible_user root, whereas the others have to run with ansible
- import_playbook: playbooks/bootstrap.yml
- import_playbook: playbooks/networking.yml
- import_playbook: playbooks/monitoring.yml
Any suggestions what I am missing or how to fix it?
Q: "remote_user: root is ignored"
A: The playbook works as expected
- hosts: test_01
gather_facts: false
become: no
remote_user: root
tasks:
- command: whoami
register: result
- debug:
var: result.stdout
gives
"result.stdout": "root"
But, the variable can be overridden in the inventory. For example with the inventory
$ cat hosts
all:
hosts:
test_01:
vars:
ansible_connection: ssh
ansible_user: admin
the result is
"result.stdout": "admin"
Double-check the inventory with the command
$ ansible-inventory --list
Notes
It might be also necessary to double-check the role - role: papanito.bootstrap
See Controlling how Ansible behaves: precedence rules
I faced a similar issue, where ec2 instance required different username to ssh with. You could try with below example
- import_playbook: playbooks/bootstrap.yml
vars:
ansible_ssh_user: root
Try this
Instead of “remote_user: root”use “remote_user: ansible” and additional “become: yes” ,”become_user: root”,”become_method: sudo or su”

vars_prompt not working in role - Ansible

I'm trying to automate hostname creation for 10x machines using ansible roles. What I want when executing playbook, as this wait for enter the user name manually.
I tried with vars_prompt module for satisfying the requirement. But here for a single *.yml file, I'm able to see the expected results
Without role - I can see the input is taken to variable host. but this works fine.
#host.yml .
---
- hosts: ubuntu
user: test
sudo: yes
vars_prompt:
- name: host
prompt: "Specify host name?"
private: no
tasks:
- debug:
msg: ' log as {{ host }}'
- name: Changing hostname
hostname:
name: '{{ host }}'
With role, < this is not working > { vars_prompt not working }
#role.yml
---
- hosts: ubuntu
user: test
sudo: yes
roles:
# - hostname
#hostname/tasks/main.yml
- name: testing prompt
vars_prompt:
- name: host
prompt: "Specify host name?"
- name: Ansible prompt example
debug:
msg: "{{ host }}"
#Changing hostname
- name: Changing hostname
hostname:
name: "{{ host }}"
Here I'm getting error as
ERROR! no action detected in task. This often indicates a misspelled module name, or incorrect module path.
The error appears to have been in '/root/roles/hostname/tasks/main.yml': line 1, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: testing prompt
^ here
My expectation is to set some parameters need to set manually as input while the execution of playbook. Need to work this vars_prompt module in role.
Run 1st play with serial: 1 and enter the hostnames. 2nd play (in the same playbook) will use the facts.
- hosts: ubuntu
serial: 1
user: test
sudo: yes
tasks:
- pause:
prompt: "Specify hostname for {{ inventory_hostname }}?"
echo: yes
register: result
- set_fact:
host: "{{ result.user_input }}"
- hosts: ubuntu
user: test
sudo: yes
roles:
- hostname

How to permanently set environment variable?

Host is Ubuntu 16.04
I'm trying to set environment variable for user, with:
- hosts: all
remote_user: user1
tasks:
- name: Adding the path in the bashrc files
lineinfile: dest=/home/user1/.bashrc line='export MY_VAR=TEST' insertafter='EOF' state=present
- name: Source the bashrc file
shell: . /home/user1/.bashrc
- debug: msg={{lookup('env','MY_VAR')}}
Unfortunately it outputs:
TASK [debug] *******************************************************************
ok: [xxxxx.xxx] => {
"msg": ""
}
How can I export variable so next time I run some tasks on this machine I can use {{ lookup('env', 'MY_VAR') }} to get value of this variable?
Because lookups happen locally, and because each task runs in it's own process, you need to do something a bit different.
- hosts: all
remote_user: user1
tasks:
- name: Adding the path in the bashrc files
lineinfile: dest=/home/user1/.bashrc line='export MY_VAR=TEST' insertafter='EOF' state=present
- shell: . /home/user1/.bashrc && echo $MY_VAR
args:
executable: /bin/bash
register: myvar
- debug: var=myvar.stdout
In this example I am sourcing the .bashrc and checking the var in the same command, and storing the value with register
All lookups in Ansible are local. See documentation for details:
Note
Lookups occur on the local computer, not on the remote computer.

Resources