Network Automation Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

We start by creating the public and private SSH keys on the Ansible control machine, using the SSH-keygen command and specifying the following options:

  • We specify the encryption algorithm with the -t option, and we set it to rsa
  • We specify the size of the encryption key using the -b option, and we set the size to 2048 bits.
  • We specify the location to save the private and public keys using the -f option, and we specify the name for the public and private key that will be generated, which will be Ansible_SSH_key

Once we run the command, we will see that the following two files (the private and public SSH keys) are generated, as shown here:

$ ls -la | grep Ansible_SSH_key
-rw------- 1 Ansible Ansible 1679 Dec 31 23:41 Ansible_SSH_key
-rw-r--r-- 1 Ansible Ansible 409 Dec 31 23:41 Ansible_SSH_key.pub

On all the Juniper devices in our inventory, we create the admin user and we specify that we will use SSH keys for authentication. We paste the contents of the public key that we have created on the Ansible control machine under the authentication stanza for this new user. With this configuration, any host who has the corresponding private key can authenticate and log in to the Juniper devices as the admin user.

In order to test and validate that we have successfully logged in to the Junos OS devices from the compute nodes, we can test this using the Ansible command shown in the following code:

$ Ansible all -m ping -u admin --private-key Ansible_SSH_key -c network_cli

mxp02 | SUCCESS => {
"changed": false,
"ping": "pong"
}
mxpe02 | SUCCESS => {
"changed": false,
"ping": "pong"
}
mxpe01 | SUCCESS => {
"changed": false,
"ping": "pong"
}
mxp01 | SUCCESS => {
"changed": false,
"ping": "pong"
}

We specify the username to connect to the devices using the -u option and we specify the private SSH key using the –private-key option. Finally, we use the -c option in order to specify the connection plugin used to connect to the managed devices, and, in this case, we use the network_cli connection plugin to open an SSH session with the managed Juniper devices.