Ad-hoc Commands

Document Control

TODO:

  • Overall structure.
  • Initial draft complete
  • Testing
  • Ready

Gathering Facts

Run the ansible setup module against localhost

Find out where ansible is in your PATH.

ansible-doc localhost -m setup
lots of output

What just happened?

  • Ansible ran a single module called setup against localhost.
  • No parameters were provided (defaults).
  • Looking at ansible-doc -s setup we can see it supports a number of options such as filter.
  • Looking at ansible-doc setup EXAMPLES section, we can test filtering.
  • When providing an ansible inventory file, you can run a command against multiple hosts, or groups.

Running a module with options

The general syntax is ansible -m module_name -a 'option=value'. For example:

Run the ansible setup module against localhost with an option
ansible localhost -m setup -a 'filter=*arch*'
- name: Ansible playbook
  site: localhost
  connection: local
  tasks:
    - name: "Collect facts. Normally, this can be done with gather_facts in the play"
      setup:
        filter: "*arch*"
localhost | SUCCESS => {
    "ansible_facts": {
        "ansible_architecture": "x86_64",
        "ansible_userspace_architecture": "x86_64"
    },
    "changed": false
}

Connecting to other hosts

Normally, hosts are specified in an inventory file (can be a static inventory, such as a yaml or ini, or dynamic, such as a shell or python script).

You can also specifiy hosts inline. Let's say we want to test connection to two systems. You should be able to access them with ssh centos7 or ssh centos8.

You can use the --user REMOTE_USER --ask-pass flags, or, before running the ping command, you can copy your SSH key:

ssh-copy-id cmihai@centos7
ssh-copy-id cmihai@centos8

Test connectivity with ansible ping

ping hosts
ansible all -i 'centos7,centos8,' --list-hosts
ansible all -i 'centos7,centos8,' -m ping
hosts (2):
  centos7
  centos8
centos8 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
centos7 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false,
    "ping": "pong"
}

Notice the discovered_interpreter_python

Ansible requires PYTHON to run. If there is no python, most modules except for raw will fail. You can set ansible_platform_python to match the desired platform python (ex: python2 or 3) of your system.

Due to the way yum and selinux work, on RHEL 7 / CentOS 7 systems, you are expected to use Python 2, and on RHEL 8 / Fedora (dnf) systems, you should use Python 3.


Last update: 2020-01-19