Ansible host file how to provide # in ansible_ssh_pass - ansible

I am new to ansible. I am facing a problem in hosts file. error output is below.
My question is : How do I escape the # in the ansible_ssh_pass.
I tried with ansible_ssh_pass="airtel\#121" and ansible_ssh_pass=airtel\#121 without double quotes both ways. it is throwing the error.
ansible version: ansible-playbook 2.9.6
host file entry is as below:
[devices]
10.10.10.10 ansible_ssh_user="abcd" ansible_ssh_pass="airtel#121"
playbook is as below:
- name: Cisco show version example
hosts: devices
gather_facts: false
ansible_connection: ansible.netcommon.network_cli
ansible_network_os: cisco.ios.ios
ansible_become: yes
ansible_become_method: enable
tasks:
- name: run show version on the routers
ios_command:
commands:
- show version
register: output
- name: print output
debug:
var: output.stdout_lines
Getting error as below.
xxxx#xxxx:/etc/ansible/playbooks# ansible-playbook check_connectivity_temp.yml -vvvv
ansible-playbook 2.9.6
config file = /etc/ansible/ansible.cfg
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python3/dist-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0]
Using /etc/ansible/ansible.cfg as config file
setting up inventory plugins
host_list declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
auto declined parsing /etc/ansible/hosts as it did not pass its verify_file() method
Parsed /etc/ansible/hosts inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3/dist-packages/ansible/plugins/callback/default.py
PLAYBOOK: check_connectivity_temp.yml ***************************************************************************************
Positional arguments: check_connectivity_temp.yml
verbosity: 4
connection: smart
timeout: 10
become_method: sudo
tags: ('all',)
inventory: ('/etc/ansible/hosts',)
forks: 5
1 plays in check_connectivity_temp.yml
PLAY [Cisco show version example] *******************************************************************************************
META: ran handlers
TASK [run show version on the routers] **************************************************************************************
task path: /etc/ansible/playbooks/check_connectivity_temp.yml:14
<10.10.10.10> attempting to start connection
<10.10.10.10> using connection plugin ansible.netcommon.network_cli
<10.10.10.10> local domain socket does not exist, starting it
<10.10.10.10> control socket path is /root/.ansible/pc/aaec916454
<10.10.10.10> local domain socket listeners started successfully
<10.10.10.10> loaded cliconf plugin ansible_collections.cisco.ios.plugins.cliconf.ios from path /root/.ansible/collections/ansible_collections/cisco/ios/plugins/cliconf/ios.py for network_os cisco.ios.ios
<10.10.10.10> ssh type is set to auto
<10.10.10.10> autodetecting ssh_type
[WARNING]: ansible-pylibssh not installed, falling back to paramiko
<10.10.10.10> ssh type is now set to paramiko
<10.10.10.10>
<10.10.10.10> local domain socket path is /root/.ansible/pc/aaec916454
fatal: [10.10.10.10]: FAILED! => {
"changed": false,
"msg": "Failed to authenticate: Authentication failed."
}
PLAY RECAP ******************************************************************************************************************
10.10.10.10 : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
My question is : How do I escape the # in the ansible_ssh_pass.

Put the hash character '#' into an expression {{ '#' }}. For example,
- debug:
var: ssh_pass
vars:
ssh_pass: "airtel{{ '#' }}121"
gives
ssh_pass: airtel#121

Related

ansible telnet without username and password

I have to make an ansible playbook that connects to a brand new cisco router via a telnet connection to a terminal concentrator on a specefic telnet port.
This is my playbook so far
---
- name: Telnet test
hosts: localhost
connection: local
tasks:
- name: telnet test
telnet:
host: 10.145.0.200
port: 4009
send_newline: yes
prompts:
- '[>|#]'
command:
- enable
- term len 0
- show ver
My issue is that when the connection is made the playbook just stay in the task without sending any command to the cisco router, how can i connect to a device without username and password?
i had to cancel the playbook since it will just stay in the task forever
ansible-playbook 2.9.13
config file = /home/niclas/ansible/gc/ansible.cfg
configured module search path = ['/home/niclas/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/niclas/.local/lib/python3.8/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0]
Using /home/niclas/ansible/gc/ansible.cfg as config file
host_list declined parsing /home/niclas/ansible/gc/inventory.yml as it did not pass its verify_file() method
Parsed /home/niclas/ansible/gc/inventory.yml inventory source with ini plugin
PLAYBOOK: testTelnet.yml ***********************************************************************************************
1 plays in testTelnet.yml
PLAY [Telnet test] *****************************************************************************************************
META: ran handlers
TASK [telnet test] *****************************************************************************************************
task path: /home/niclas/ansible/gc/testTelnet.yml:6
^C [ERROR]: User interrupted execution
Edit error:
❯ ansible-playbook testTelnet.yml -vvv
ansible-playbook 2.9.13
config file = /home/niclas/ansible/gc/ansible.cfg
configured module search path = ['/home/niclas/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/niclas/.local/lib/python3.8/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0]
Using /home/niclas/ansible/gc/ansible.cfg as config file
host_list declined parsing /home/niclas/ansible/gc/inventory.yml as it did not pass its verify_file() method
Parsed /home/niclas/ansible/gc/inventory.yml inventory source with ini plugin
PLAYBOOK: testTelnet.yml ***********************************************************************************************
1 plays in testTelnet.yml
PLAY [Telnet test] *****************************************************************************************************
META: ran handlers
TASK [telnet test] *****************************************************************************************************
task path: /home/niclas/ansible/gc/testTelnet.yml:6
The full traceback is:
Traceback (most recent call last):
File "/home/niclas/.local/lib/python3.8/site-packages/ansible/executor/task_executor.py", line 147, in run
res = self._execute()
File "/home/niclas/.local/lib/python3.8/site-packages/ansible/executor/task_executor.py", line 665, in _execute
result = self._handler.run(task_vars=variables)
File "/home/niclas/.local/lib/python3.8/site-packages/ansible/plugins/action/telnet.py", line 59, in run
tn = telnetlib.Telnet(host, port, timeout)
File "/usr/lib/python3.8/telnetlib.py", line 218, in __init__
self.open(host, port, timeout)
File "/usr/lib/python3.8/telnetlib.py", line 235, in open
self.sock = socket.create_connection((host, port), timeout)
File "/usr/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
fatal: [localhost]: FAILED! => {
"msg": "Unexpected failure during module execution.",
"stdout": ""
}
PLAY RECAP *************************************************************************************************************
localhost : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
I think the ansible's command interpreter can't understand the promt from the cisco. I think you should use cisco.ios plugin instead which is described here: https://docs.ansible.com/ansible/latest/collections/cisco/ios/ios_command_module.html
UPDATE
Because the telnet task does not understand cisco.ios commands, then you should use another approach for connecting. Hope your cisco device support SSH, then you can make the connection.
In this case, I think your playbook should look like this:
ansible_connection: ansible.netcommon.network_cli
ansible_network_os: cisco.ios.ios
ansible_user: cisco
ansible_password: ciscopass
ansible_become: yes
ansible_become_method: enable
ansible_become_password: if_you_have_enable_password_define_it_here
---
- hosts: ansible.ini_defined_group_name_for_cisco_device
tasks:
- name: log into cisco device and init this commands
cisco.ios.ios_command:
commands:
- show version
- term len 0

How do I confirm the reason why the ansible task does not in running list

When I execute the playbook, only one task will be displayed
playbook: test.yaml
play #1 (lab): lab TAGS: []
tasks:
Install pip TAGS: []
And when I execute the playbook, it is indeed normal
PLAY [lab] *****************************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************
ok: [my_ipaddress]
TASK [Install pip] *********************************************************************************************************************
ok: [my_ipaddress]
PLAY RECAP *****************************************************************************************************************************
my_ipaddress : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
and in /var/log/ansible.log also look normal as same as Execution output
So the question is, do I have to do less settings? Why is there a task that is not in the execution list, or there are other debug outputs that can display more detailed output information?
here is my ansible configuration
OS version:Ubuntu 18.04.5 LTS
ansible version:
ansible 2.9.12
config file = /etc/ansible/ansible.cfg
configured module search path = ['/home/primula/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /home/primula/.local/lib/python3.6/site-packages/ansible
executable location = /home/primula/.local/bin/ansible
python version = 3.6.9 (default, Jul 17 2020, 12:50:27) [GCC 8.4.0]
my playbook:
---
- hosts: lab
roles:
- { role: apache2, become: yes }
- { role: pip, become: yes }
apache2 role configuration
path:/etc/ansible/roles/apache2/tasks/maim.yaml
---
- name: Install apache2
apt:
name: apache2
update_cache: yes
pip role configuration
path:/etc/ansible/roles/pip/tasks/main.yaml
---
- name: Install pip
apt:
name: python-pip
update_cache: yes
here is my ansible invotory & ansible.cfg
invotory
[lab]
<ipaddress> ansible_ssh_user=<user_name> ansible_ssh_pass='<ssh_pass>' ansible_become_user=<root_user> ansible_become=true ansible_become_pass='<root_pass>'
ansible.cfg
[defaults]
private_key_file = /root/.ssh/id_rsa
roles_path = /etc/ansible/roles
inventory = /etc/ansible/hosts
timeout = 10
log_path = /var/log/ansible.log
deprecation_warnings = False
strategy = debug
any_errors_fatal = True
The task that is not on your execution list when using ansible-playbook --list-tasks your_playbook.yml is the one related to fact gathering done by the setup module
It is an implicit automatic task that is turned on by default for all hosts in your play. If implicit, it is not reported by the above command.
You can control fact gathering at play level with the gather_facts play keyword, e.g.
---
- name: Some play without facts gathering
hosts: my_group
gather_facts: false
tasks:
- name: dummy demo task
debug:
msg: I am dummy task
Regarding your question about a more detailed output, you can turn on ansible(-playbook) verbose mode with the -v(vv) switch (the more vs, the more details).

Using Netbox Ansible Modules

I've been wanting to try out Ansible modules available for Netbox [1].
However, I find myself stuck right in the beginning.
Here's what I've tried:
Add prefix/VLAN to netbox [2]:
cat setup-vlans.yml
---
- hosts: netbox
tasks:
- name: Create prefix 192.168.10.0/24 in Netbox
netbox_prefix:
netbox_token: "{{ netbox_token }}"
netbox_url: "{{ netbox_url }}"
data:
prefix: 192.168.10.0/24
state: present
That gives me the following error:
ansible-playbook setup-vlans.yml
PLAY [netbox] *********************************************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************************************
ok: [NETBOX]
TASK [Create prefix 192.168.10.0/24 in Netbox] ************************************************************************************************
fatal: [NETBOX]: FAILED! => {"changed": false, "msg": "Failed to establish connection to Netbox API"}
PLAY RECAP ************************************************************************************************************************************
NETBOX : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
Can someone please point me where I am going wrong?
Note: The NetBox URL is an https://url setup with nginx and netbox-docker [3].
Thanks & Regards,
Sana
[1] https://github.com/netbox-community/ansible_modules
[2] https://docs.ansible.com/ansible/latest/modules/netbox_prefix_module.html
[3]
https://github.com/netbox-community/netbox-docker
I had the same. Apparently the pynetbox api has changed in instantiation (ssl_verify is now replaced by requests session parameters).
I had to force ansible galaxy to update to the latest netbox module with:
ansible-galaxy collection install netbox.netbox -f
The force option did the trick for me.
All playbooks using API modules like netbox (but this is the same for gcp or aws) must use as host not the target but the host that will execute the playbook to call the API. Most of the time this is localhost, but that can be also a dedicated node like a bastion.
You can see in the example on the documentation you linked that it uses hosts: localhost.
Hence I think your playbook should be
---
- hosts: localhost
connection: local
gather_facts: False
tasks:
- name: Create prefix 192.168.10.0/24 in Netbox
netbox_prefix:
netbox_token: "{{ netbox_token }}"
netbox_url: "{{ netbox_url }}"
data:
prefix: 192.168.10.0/24
state: present

Ansible is not picking the group_vars and host_vars

I am new to Ansible and couldn't figure out why the playbook is not picking up the group_vars/ and host_vars I have defined. According to the document:
You can also add group_vars/ and host_vars/ directories to your playbook directory. The ansible-playbook command looks for these directories in the current working directory by default.
My playbook, inventory, and other files structure are quite simple. It should be matching the default.
Inventory file:
dummy
[spider]
s0ra
s0ra_slave
The playbook:
- name: base mix release upgrade Prod.
hosts: spider
gather_facts: false
# vars_files:
# - vars/s0ra_sup.yaml
tasks:
- name: check release bin
stat:
path: "{{ sh_lastrel }}"
register: rel_bin
When I tried to run the playbook by ansible-playbook -i inventory.ini mix_upgrade.yaml, it complains:
PLAY [base mix release upgrade Prod.] **********************************************************************************
TASK [check release bin] ***********************************************************************************************
fatal: [s0ra]: FAILED! => {"msg": "The task includes an option with an undefined variable.
The error was: 'sh_lastrel' is undefined\n\n
The error appears to be in 'xxx/ansible/mix_upgrade.yaml': line 19, column 7, but may\n
be elsewhere in the file depending on the exact syntax problem.\n\n
The offending line appears to be:\n\n\n
- name: check release bin\n ^ here\n"}
PLAY RECAP *************************************************************************************************************
s0ra : ok=0 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0
But the sh_lastrel is defined in spider.yaml actually. I don't know why it is not loaded. I tried to turn on -v mode but it does not seem to have more debugging info. Any hint of the cause or how to further debug is greatly appreciated.
My ansible version is as below:
╰─ ansible --version  ✔  22:01:57 
ansible 2.9.9
config file = None
configured module search path = ['/Users/kenchen/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /Users/kenchen/.pyenv/versions/3.8.2/lib/python3.8/site-packages/ansible
executable location = /Users/kenchen/.pyenv/versions/3.8.2/bin/ansible
python version = 3.8.2 (default, May 18 2020, 00:02:00) [Clang 10.0.1 (clang-1001.0.46.4)]
Make sure group_vars/spider.yml is available. For example,
shell> cat group_vars/spider.yml
sh_lastrel: value of sh_lastrel defined in group_vars/spider.yml
shell> cat inventory.ini
dummy
[spider]
s0ra
s0ra_slave
shell> cat mix_upgrade.yaml
- hosts: spider
gather_facts: false
tasks:
- debug:
var: sh_lastrel
shell> ansible-playbook -i inventory.ini mix_upgrade.yaml
ok: [s0ra] =>
sh_lastrel: value of sh_lastrel defined in group_vars/spider.yml
ok: [s0ra_slave] =>
sh_lastrel: value of sh_lastrel defined in group_vars/spider.yml

Getting "winrm send_input failed" when using os_server module and local connection

I'm trying to write a playbook for a Windows VM that also creates the VM with the os_server module.
I'm starting with a simple win_ping, given the VM is already there:
- name: Create instance
hosts: all
tasks:
- name: Ping machine
win_ping:
running it with ansible-playbook site.yml --inventory=10.204.0.9,
results in:
PLAY [Create instance] ************************************************************************
TASK [Gathering Facts] ************************************************************************
ok: [10.204.0.9]
TASK [Ping machine] ***************************************************************************
ok: [10.204.0.9]
PLAY RECAP ************************************************************************************
10.204.0.9 : ok=2 changed=0 unreachable=0 failed=0
Now I add the os_server task:
- name: Create Windows Instance
connection: local
os_server:
state: present
region_name: "{{ os_region_name }}"
auth: "{{ cloud.auth }}"
name: "windows-{{ inventory_hostname }}"
image: Windows 2012 R2 Datacenter
key_name: vector_ops
flavor: 1C-2GB-50GB
floating_ips:
- "{{ inventory_hostname }}"
- name: Ping machine
win_ping:
I'm setting connection to local as I want this task to be executed from the control machine, in case the VM is not created yet.
When I run this playbook again with ansible-playbook site.yml --inventory=10.204.0.9,, I get:
TASK [Create Windows Instance] ****************************************************************
[WARNING]: FATAL ERROR DURING FILE TRANSFER: Traceback (most recent call last): File
"/usr/lib/python2.7/dist-packages/ansible/plugins/connection/winrm.py", line 276, in
_winrm_exec self._winrm_send_input(self.protocol, self.shell_id, command_id, data,
eof=is_last) File "/usr/lib/python2.7/dist-packages/ansible/plugins/connection/winrm.py",
line 256, in _winrm_send_input protocol.send_message(xmltodict.unparse(rq)) File
"/usr/local/lib/python2.7/dist-packages/winrm/protocol.py", line 207, in send_message
return self.transport.send_message(message) File "/usr/local/lib/python2.7/dist-
packages/winrm/transport.py", line 202, in send_message raise WinRMTransportError('http',
error_message) WinRMTransportError: (u'http', u'Bad HTTP response returned from server. Code
500')
fatal: [10.204.0.9]: FAILED! => {"msg": "winrm send_input failed"}
I'm a bit puzzled why there is an error during a file transfer, so I ran the command with -vvv:
TASK [Create Windows Instance] ****************************************************************
task path: /home/ubuntu/basic-windows-example/trunk/playbooks/site.yml:8
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/cloud/openstack/os_server.py
<10.204.0.9> ESTABLISH WINRM CONNECTION FOR USER: Admin on PORT 5986 TO 10.204.0.9
EXEC (via pipeline wrapper)
And indeed it seems so that Ansible tries to establish a winrm connection, despite connection: local. Removing connection: local from the task brings the same result as above.
I would expect the task to return a simple "ok" since the VM is already there.
What am I missing here?
Update 2018-01-09, 9:45 GMT:
So I tried another experiment: I removed all ansible_* variables from the var file (see below) just to see what Ansible does with the os_server task when no WinRM connection is configured. Running it again with ansible-playbook site.yml --inventory=10.204.0.9, -vvv this time I get for the os_server task:
TASK [Create Windows Instance] ****************************************************************
task path: /home/ubuntu/basic-windows-example/trunk/playbooks/site.yml:9
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/cloud/openstack/os_server.py
<10.204.0.9> ESTABLISH LOCAL CONNECTION FOR USER: ubuntu
<10.204.0.9> EXEC /bin/sh -c 'echo ~ && sleep 0'
<10.204.0.9> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /home/ubuntu/.ansible/tmp/ansible-tmp-1515490597.4-208015762064624 `" && echo ansible-tmp-1515490597.4-208015762064624="` echo /home/ubuntu/.ansible/tmp/ansible-tmp-1515490597.4-208015762064624 `" ) && sleep 0'
<rest cut off for brevity>
So now a local connection does get established and the os_server task completes successfully. But of course, this is not the answer, because I need the WinRM connection configured for the Windows VM.
Update 2018-01-09, 10:00 GMT:
Following the suggestion to add gather_facts: false to the play and running ansible-playbook site.yml --inventory=10.204.0.9,, I now get:
PLAY [Create instance] ************************************************************************
META: ran handlers
TASK [Create Windows Instance] ****************************************************************
task path: /home/ubuntu/basic-windows-example/trunk/playbooks/site.yml:10
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/cloud/openstack/os_server.py
<10.204.0.9> ESTABLISH WINRM CONNECTION FOR USER: Admin on PORT 5986 TO 10.204.0.9
EXEC (via pipeline wrapper)
[WARNING]: FATAL ERROR DURING FILE TRANSFER: Traceback (most recent call last): File
"/usr/lib/python2.7/dist-packages/ansible/plugins/connection/winrm.py", line 276, in
_winrm_exec self._winrm_send_input(self.protocol, self.shell_id, command_id, data,
eof=is_last) File "/usr/lib/python2.7/dist-packages/ansible/plugins/connection/winrm.py",
line 256, in _winrm_send_input protocol.send_message(xmltodict.unparse(rq)) File
"/usr/local/lib/python2.7/dist-packages/winrm/protocol.py", line 207, in send_message
return self.transport.send_message(message) File "/usr/local/lib/python2.7/dist-
packages/winrm/transport.py", line 202, in send_message raise WinRMTransportError('http',
error_message) WinRMTransportError: (u'http', u'Bad HTTP response returned from server. Code
500')
fatal: [10.204.0.9]: FAILED! => {
"msg": "winrm send_input failed"
}
The error is the same, Ansible still tries to establish a WinRM connection.
Full Playbook (site.yml, added gather_facts: false):
- name: Create instance
hosts: all
gather_facts: false
tasks:
- name: Create Windows Instance
connection: local
os_server:
state: present
region_name: Region1
auth: "{{ cloud.auth }}"
name: "windows-{{ inventory_hostname }}"
image: Windows 2012 R2 Datacenter
key_name: mykey
flavor: 1C-2GB-50GB
floating_ips:
- "{{ inventory_hostname }}"
- name: Ping machine
win_ping:
Vars in group_vars/all (used throughout all examples):
cloud:
auth:
auth_url: https://cloud.internal:5000/v3/
domain_name: Domain_01
password: mypassword
project_name: dev-project
username: apiuser
os_region_name: Fra1
ansible_user: Admin
ansible_port: 5986
ansible_password: myvmpassword
ansible_connection: winrm
ansible_winrm_server_cert_validation: ignore
Version info:
ansible --version
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/ubuntu/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609]
If I use delegate_to: localhost instead of connection: local for the os_server task, a local connection does get established. delegate_to avoids loading the WinRM connection variables for that connection.
If someone else is facing the same issue with Ansible then check the WinRM memory setting on the host and ensure it has sufficient memory.
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024

Resources