I have an Ansible script where i am simply using junos_command module to get users list from Juniper switch, below is the snippet of my code. I keep getting the RuntimeWarning whenever i try to run this. Moreover I have been successfully able to run commands like 'show version' using the below code itself. Please help
Script:
name: / GET USERS / Get list of all the current users on switch
action: junos_command
args: { commands: 'show configuration system login',
provider: "{{ netconf }}" }
register: curr_users_on_switch
Error:
TASK [/ GET USERS / Get list of all the current users on switch] ***************
fatal: [rlab-er1]: FAILED! => {"changed": false, "failed": true, "module_stderr": "/home/mbhadoria/.local/lib/python2.7/site-packages/jnpr/junos/device.py:429: RuntimeWarning: CLI command is for debug use only!
\n warnings.warn(\"CLI command is for debug use only!\", RuntimeWarning)\nTraceback (most recent call last):
\n File \"/tmp/ansible_lVOmPp/ansible_module_junos_command.py\", line 261, in <module>
\n main()
\n File \"/tmp/ansible_lVOmPp/ansible_module_junos_command.py\", line 233, in main
\n xmlout.append(xml_to_string(response[index]))
\n File \"/tmp/ansible_lVOmPp/ansible_modlib.zip/ansible/module_utils/junos.py\", line 79, in xml_to_string\n File \"src/lxml/lxml.etree.pyx\", line 3350, in lxml.etree.tostring (src/lxml/lxml.etree.c:84534)\nTypeError: Type 'str' cannot be serialized.
\n", "module_stdout": "", "msg": "MODULE FAILURE", "parsed": false}
junos_command only support operation junos commands. What you are trying to run is configurational command. Hence you see "show version" which is operational command working but not "show configuration system login".
For such configuration data you can should use rpc option (get-configuration) with junos_command.
junos_command:
rpcs:
- "get_configuration
You can also use junos_get_config.
http://junos-ansible-modules.readthedocs.io/en/latest/junos_get_config.html
or junos_rpc
https://github.com/Juniper/ansible-junos-stdlib/blob/master/library/junos_rpc
ex:
- name: Junos OS version
hosts: all
connection: local
gather_facts: no
tasks:
- name: Get rpc run
junos_rpc:
host={{ inventory_hostname }}
user=xxxx
passwd=xxx
rpc=get-config
dest=get_config.conf
filter_xml="<configuration><system><login/></system></configuration>"
register: junos
or
tasks:
- name: Get rpc run
junos_get_config:
host: "{{ inventory_hostname }}"
user: xxxx
passwd: xxxx
logfile: get_config.log
dest: "{{ inventory_hostname }}.xml"
format: xml
filter: "system/login"
TASK [Get rpc run] *************************************************************
......
PLAY RECAP *********************************************************************
xxxk : ok=1 changed=1 unreachable=0 failed=0
Related
I am executing a PS script on a windows host and want to store its stdout in a file on an ansible local machine. I have a playbook like following:
---
- name: Check Antivirus software
hosts: all
become: false
gather_facts: no
tasks:
- name: Get AV details
win_shell: |
echo "script printing data on stdout"
register: result
- name: save response
copy:
content: '{{ result.stdout }}'
dest: '{{ response_file }}'
delegate_to: localhost
From the above playbook, 1st task gets executed without any issues. But 2nd task gives the following error.
TASK [save response] *******************************************************************************************************************************************
fatal: [20.15.102.192 -> localhost]: UNREACHABLE! => {"changed": false, "msg": "ntlm: HTTPSConnectionPool(host='localhost', port=5986): Max retries exceeded with url: /wsman (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f4940760208>: Failed to establish a new connection: [Errno 111] Connection refused',))", "unreachable": true}
I also tried local_action which is also giving the same error.
I am trying to save the output of commands using ansible ios_command module. This work well when all the commands are executed and cisco device doesnt throw error. But as soon as if i have any command which doesnt run on that device, playbook fails and doesnt save the ouput of rest of the commans which executed successfully. If command fail, i would like to have my task running without fail.
---
- name: Backup Play
hosts: all
gather_facts: false
connection: network_cli
tasks:
- name: Execute Commands on the device
ios_command:
commands:
- show run
- show version
- show inventory
- show ip bgp summary
ignore_errors: true
register: config
- name: save output to file
copy:
content: "{{ config.stdout | replace('\\n', '\n') }}"
dest: "/DEVICE_CONFIGS/CISCO/{{ ansible_host }}.cfg"
While executing the above play, i am getting below error
server01 playbooks]$ ansible-playbook cisco-backups.yml --limit Site_01 --ask-vault-pass -e 'ansible_python_interpreter=/usr/bin/python3'
Vault password:
PLAY [Backup Play] ***********************************************************************************************************************
TASK [Execute Commands on the device] *********************************************************************************************************************************
fatal: [Switch_01]: FAILED! => {"changed": false, "msg": "show ip bgp summary\r\nshow ip bgp summary\r\n ^\r\n% Invalid input detected at '^' marker.\r\n\r\nSwitch_01#"}
...ignoring
TASK [save output to file] *****************************************************************************************************************
fatal: [Switch_01]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'\n\nThe error appears to be in '/etc/ansible/playbooks/cisco-backups.yml': line 62, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: save output to /etc/ansible/backups\n ^ here\n"}
PLAY RECAP *************************************************************************************************************************************************
Switch_01 : ok=3 changed=2 unreachable=0 failed=1 skipped=0 rescued=0 ignored=1
Output of Config when debugged:
TASK [Print output] ************************************************************************************************
task path: /etc/ansible/playbooks/cisco-backups.yml:64
ok: [switch-01] => {
"config": {
"changed": false,
"exception": " File \"/tmp/ansible_ios_command_payload_gluy0xuc/ansible_ios_command_payload.zip/ansible/module_utils/network/ios/ios.py\", line 135, in run_commands\n return connection.run_commands(commands=commands, check_rc=check_rc)\n File \"/tmp/ansible_ios_command_payload_gluy0xuc/ansible_ios_command_payload.zip/ansible/module_utils/connection.py\", line 190, in __rpc__\n raise ConnectionError(to_text(msg, errors='surrogate_then_replace'), code=code)\n",
"failed": true,
"msg": "show switch\r\nshow switch\r\n ^\r\n% Invalid input detected at '^' marker.\r\n\r\nswitch-01#"
}
}
Using Terraform code I have created Other type of secrets in AWS Secrets Manager.
I need to use these AWS secrets in Ansible code. I found this below link but I am unable to proceed it.
https://docs.ansible.com/ansible/2.8/plugins/lookup/aws_secret.html
I have below Ansible code:-
database.yml
- name: Airflow | DB | Create MySQL DB
mysql_db:
login_user: "{{ mysql_user }}"
# login_password: "{{ mysql_root_password }}"
login_password: "{{ lookup('ca_dev', 'mysql_root_password') }}"
# config_file: /etc/my.cnf
# login_unix_socket: /var/lib/mysql/mysql.sock
# encrypted: yes
name: "airflow"
state: "present"
How can I incorporate AWS secret Manager in my ansible code?
Error message:-
TASK [../../roles/airflow : Airflow | DB | Create MySQL DB] **************************************************************************************************************************************************************************
task path: /home/ec2-user/cng-ansible/roles/airflow/tasks/database.yml:25
The full traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 140, in run
res = self._execute()
File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 539, in _execute
self._task.post_validate(templar=templar)
File "/usr/lib/python2.7/site-packages/ansible/playbook/task.py", line 267, in post_validate
super(Task, self).post_validate(templar)
File "/usr/lib/python2.7/site-packages/ansible/playbook/base.py", line 364, in post_validate
value = templar.template(getattr(self, name))
File "/usr/lib/python2.7/site-packages/ansible/template/__init__.py", line 540, in template
disable_lookups=disable_lookups,
File "/usr/lib/python2.7/site-packages/ansible/template/__init__.py", line 495, in template
disable_lookups=disable_lookups,
File "/usr/lib/python2.7/site-packages/ansible/template/__init__.py", line 746, in do_template
res = j2_concat(rf)
File "<template>", line 8, in root
File "/usr/lib/python2.7/site-packages/jinja2/runtime.py", line 193, in call
return __obj(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/ansible/template/__init__.py", line 631, in _lookup
instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self)
File "/usr/lib/python2.7/site-packages/ansible/plugins/loader.py", line 381, in get
obj = getattr(self._module_cache[path], self.class_name)
AttributeError: 'module' object has no attribute 'LookupModule'
fatal: [127.0.0.1]: FAILED! => {
"msg": "Unexpected failure during module execution.",
"stdout": ""
}
RUNNING HANDLER [../../roles/airflow : restart rabbitmq-server]
task path: /home/ec2-user/cng-ansible/roles/airflow/handlers/main.yml:28
to retry, use: --limit #/home/ec2-user/cng-ansible/plays/airflow/installAirflow.retry
PLAY RECAP
127.0.0.1 : ok=39 changed=7 unreachable=0 failed=1
ansible-doc -t lookup -l output
The error {"msg": "lookup plugin (ca_dev) not found"} suggests your issue is the misuse of the lookup command.
The following line:
login_password: "{{ lookup('ca_dev', 'mysql_root_password') }}"
Should look something like
login_password: "{{ lookup('aws_secret', 'mysql_root_password') }}"
ca_dev is not a valid lookup type, whereas aws_secret is.
You can see a list of supported lookup plugins for Ansible 2.8 in the Lookup Plugins section of the official documentation.
If you are using a custom lookup plugin, or backporting a plugin from a future version of ansible to an older version, you must make sure that it is in a directory visible to ansible.
You can either place the custom file in the default location ansible looks in ~/.ansible/plugins/lookup:/usr/share/ansible/plugins/lookup or configure your ansible.cfg to look in a different place using the following lookup_plugins ini key under the defaults section.
DEFAULT_LOOKUP_PLUGIN_PATH
Description: Colon separated paths in which Ansible will search for Lookup Plugins.
Type: pathspec
Default: ~/.ansible/plugins/lookup:/usr/share/ansible/plugins/lookup
Ini Section: defaults
Ini Key: lookup_plugins
Environment: ANSIBLE_LOOKUP_PLUGINS
Documentation for this can be found in the Ansible Configuration section of the official documentation
I am trying to use ansible to telnet into cisco switches and apply a copy startup-config disk0 command.
Ansible seems to never be able to pass
(?i)"Destination filename": "work please" through the expect command
---
- hosts: all
gather_facts: false
connection: local
tasks:
- name: telnet,login and execute command
ignore_errors: true
expect:
command: telnet "{{ inventory_hostname }}"
responses:
(?i)password: "{{ password}}"
(?i)#: copy startup-config disk0
(?i)"Destination filename": "{{ lookup('pipe','date') }"
echo: yes
register: telnet_output
What i am getting as an output
ansible-playbook 2.7.6
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.5 (default, Oct 30 2018, 23:45:53) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
/var/lib/awx/projects/6500/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
/var/lib/awx/projects/6500/hosts did not meet script requirements, check plugin documentation if this is unexpected
PLAYBOOK: copy-startup.yml *************************************************************************************************************************************************************************************************************
1 plays in copy-startup.yml
PLAY [all] *****************************************************************************************************************************************************************************************************************************
META: ran handlers
TASK [telnet,login and execute command] ************************************************************************************************************************************************************************************************
task path: /var/lib/awx/projects/6500/copy-startup.yml:6
fatal: [66.90.19.18]: FAILED! => {"changed": true, "cmd": "telnet \"66.90.19.18\"", "delta": "0:00:30.370396", "end": "2019-02-12 10:09:41.473716", "msg": "command exceeded timeout", "rc": null, "start": "2019-02-12 10:09:11.103320", "stdout": "Trying 66.90.19.18...\r\r\nConnected to 66.90.19.18.\r\r\nEscape character is '^]'.\r\r\n\r\n\r\nUser Access Verification\r\n\r\nPassword: \r\nLAB-6500-SUP2T#copy startup-config disk0\r\nDestination filename [disk0]? ", "stdout_lines": ["Trying 66.90.19.18...", "", "Connected to 66.90.19.18.", "", "Escape character is '^]'.", "", "", "", "User Access Verification", "", "Password: ", "LAB-6500-SUP2T#copy startup-config disk0", "Destination filename [disk0]? "]}
...ignoring
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
66.90.19.18 : ok=2 changed=1 unreachable=0 failed=0
It seems to never want to write the Destination Filename[disk0]?
Any ideas
(?i)"Destination filename" matches for string with double quotes.
You need:
responses:
'(?i)password': "{{ password}}"
'(?i)#': copy startup-config disk0
'(?i)Destination filename': "{{ lookup('pipe','date') }"
---
- hosts: '6500'
gather_facts: true
connection: local
tasks:
- name: telnet,login and execute command
ignore_errors: true
expect:
command: telnet "{{ inventory_hostname }}"
responses:
(?i)Password: {{ password }}
(?i)Destination filename [disk0]? : "{{ lookup('pipe','date +%Y-%m-%d-%H-%M') }} {{ inventory_hostname }}"
(?i)#: copy startup-config disk0
(?i){{COMMAND}}: exit
echo: yes
register: telnet_output
This seems to be the best solution to what I need. I changed the order of operations and it was rocking,
Using Ansible, to host server(172.19.113.104) I want to copy files ( ansibletest & MariaDB-client-5.1.67-122.el5.x86_64.rpm ) from remote server(172.19.113.87), but it should not copy if file exist already.
I tried like below but throwing error:
- hosts: webservers
vars:
ip: 172.19.113.87
tasks:
- name: this is to pull
local_action: shell 'ls /opt/ansibletest'
register: result
- name: ts2
synchronize: src={{ item }} dest=/opt/ mode=pull
with_items:
- "/opt/ansibletest"
- "/opt/MariaDB-client-5.1.67-122.el5.x86_64.rpm"
when: result.shell.exists == true
[root#rbtstaging ansible]# ansible-playbook fetch.yml
PLAY [webservers] ************************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************************
ok: [172.19.113.87]
TASK [this is to pull] *******************************************************************************************************************************************
changed: [172.19.113.87]
TASK [ts2] *******************************************************************************************************************************************************
fatal: [172.19.113.87]: FAILED! => {"msg": "The conditional check 'result.stat.exists == True' failed. The error was: error while evaluating conditional (result.stat.exists == True): 'dict object' has no attribute 'stat'\n\nThe error appears to have been in '/RND/sudhir/ansible/fetch.yml': line 9, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: ts2\n ^ here\n"}
to retry, use: --limit #/RND/sudhir/ansible/fetch.retry
PLAY RECAP *******************************************************************************************************************************************************
172.19.113.87 : ok=2 changed=1 unreachable=0 failed=1
Note: Files exist with permission
You can prepend the fetch (fetch file from remote server - copy will send the file to the remove server) by a local "stat" operation, and check for existence of the local file.
local_action:
module: stat
path: /path/to/local/file
register: local_file
become: no
fetch:
src: /path/to/remote/file
dest: /path/to/local/file
flat: yes
when: local_file.stat.exists == False