Introduction To Ad-Hoc Commands

    What’s an ad-hoc command?

    An ad-hoc command is something that you might type in to do something reallyquick, but don’t want to save for later.

    This is a good place to start to understand the basics of what Ansible can doprior to learning the playbooks language – ad-hoc commands can also be usedto do quick things that you might not necessarily want to write a full playbook for.

    Generally speaking, the true power of Ansible lies in playbooks.Why would you use ad-hoc tasks versus playbooks?

    For instance, if you wanted to power off all of your lab for Christmas vacation,you could execute a quick one-liner in Ansible without writing a playbook.

    For configuration management and deployments, though, you’ll want to pick up onusing ‘/usr/bin/ansible-playbook’ – the concepts you will learn here willport over directly to the playbook language.

    (See Working With Playbooks for more information about those)

    If you haven’t read already, please look that over a bit firstand then we’ll get going.

    Arbitrary example.

    Let’s use Ansible’s command line tool to reboot all web servers in Atlanta, 10 at a time. First, let’sset up SSH-agent so it can remember our credentials:

    If you don’t want to use ssh-agent and want to instead SSH with apassword instead of keys, you can with (-k), butit’s much better to just use ssh-agent.

    Now to run the command on all servers in a group, in this case,atlanta, in 10 parallel forks:

    1. $ ansible atlanta -a "/sbin/reboot" -f 10

    /usr/bin/ansible will default to running from your user account. If you do not like thisbehavior, pass in “-u username”. If you want to run commands as a different user, it looks like this:

    1. $ ansible atlanta -a "/usr/bin/foo" -u username

    Often you’ll not want to just do things from your user account. If you want to run commands through privilege escalation:

    1. $ ansible atlanta -a "/usr/bin/foo" -u username --become [--ask-become-pass]

    Use —ask-become-pass (-K) if you are not using a passwordless privilege escalation method (sudo/su/pfexec/doas/etc).This will interactively prompt you for the password to use.Use of a passwordless setup makes things easier to automate, but it’s not required.

    It is also possible to become a user other than root using—become-user:

      Note

      Ok, so those are basics. If you didn’t read about patterns and groups yet, go back and read Working with Patterns.

      The -f 10 in the above specifies the usage of 10 simultaneousprocesses to use. You can also set this in to avoid setting it again. The default is actually 5, whichis really small and conservative. You are probably going to want to talk to a lot more simultaneous hosts so feel freeto crank this up. If you have more hosts than the value set for the fork count, Ansible will talk to them, but it willtake a little longer. Feel free to push this value as high as your system can handle!

      You can also select what Ansible “module” you want to run. Normally commands also take a for module name, butthe default module name is ‘command’, so we didn’t need tospecify that all of the time. We’ll use -m in later examples torun some other Working With Modules.

      Note

      The does not support extended shell syntax like piping andredirects (although shell variables will always work). If your command requires shell-specificsyntax, use the shell module instead. Read more about the differences on theWorking With Modules page.

      Using the looks like this:

      1. $ ansible raleigh -m shell -a 'echo $TERM'

      When running any command with the Ansible ad hoc CLI (as opposed toPlaybooks), pay particular attention to shell quoting rules, sothe local shell doesn’t eat a variable before it gets passed to Ansible.For example, using double rather than single quotes in the above example wouldevaluate the variable on the box you were on.

      So far we’ve been demoing simple command execution, but most Ansible modules are not simple imperative scripts. Instead, they use a declarative model,calculating and executing the actions required to reach a specified final state.Furthermore, they achieve a form of idempotence by checking the current statebefore they begin, and if the current state matches the specified final state,doing nothing.However, we also recognize that running arbitrary commands can be valuable, so Ansible easily supports both.

      File Transfer

      Here’s another use case for the /usr/bin/ansible command line. Ansible can SCP lots of files to multiple machines in parallel.

      To transfer a file directly to many servers:

      1. $ ansible atlanta -m copy -a "src=/etc/hosts dest=/tmp/hosts"

      If you use playbooks, you can also take advantage of the template module,which takes this another step further. (See module and playbook documentation).

      The file module allows changing ownership and permissions on files. Thesesame options can be passed directly to the copy module as well:

      The file module can also create directories, similar to :

      1. $ ansible webservers -m file -a "dest=/path/to/c mode=755 owner=mdehaan group=mdehaan state=directory"

      As well as delete directories (recursively) and delete files:

      1. $ ansible webservers -m file -a "dest=/path/to/c state=absent"

      There are modules available for yum and apt. Here are some exampleswith yum.

      Ensure a package is installed, but don’t update it:

      1. $ ansible webservers -m yum -a "name=acme state=present"

      Ensure a package is installed to a specific version:

      1. $ ansible webservers -m yum -a "name=acme-1.5 state=present"
      1. $ ansible webservers -m yum -a "name=acme state=latest"

      Ensure a package is not installed:

      1. $ ansible webservers -m yum -a "name=acme state=absent"

      Ansible has modules for managing packages under many platforms. If there isn’ta module for your package manager, you can install packages using thecommand module or (better!) contribute a module for your package manager.Stop by the mailing list for info/details.

      Users and Groups

      The ‘user’ module allows easy creation and manipulation ofexisting user accounts, as well as removal of user accounts that mayexist:

      See the section for details on all of the available options, includinghow to manipulate groups and group membership.

      Deploy your webapp straight from git:

      1. $ ansible webservers -m git -a "repo=https://foo.example.org/repo.git dest=/srv/myapp version=HEAD"

      Since Ansible modules can notify change handlers it is possible totell Ansible to run specific tasks when the code is updated, such asdeploying Perl/Python/PHP/Ruby directly from git and then restartingapache.

      Managing Services

      Ensure a service is started on all webservers:

      1. $ ansible webservers -m service -a "name=httpd state=started"

      Alternatively, restart a service on all webservers:

      1. $ ansible webservers -m service -a "name=httpd state=restarted"

      Ensure a service is stopped:

      1. $ ansible webservers -m service -a "name=httpd state=stopped"

      Long running operations can be run in the background, and it is possible tocheck their status later. For example, to execute long_running_operationasynchronously in the background, with a timeout of 3600 seconds (-B),and without polling (-P):

        If you do decide you want to check on the job status later, you can use theasync_status module, passing it the job id that was returned when you ranthe original job in the background:

        1. $ ansible web1.example.com -m async_status -a "jid=488359678239.2844"

        Polling is built-in and looks like this:

        The above example says “run for 30 minutes max (-B 30*60=1800),poll for status (-P) every 60 seconds”.

        Poll mode is smart so all jobs will be started before polling will begin on any machine.Be sure to use a high enough value if you want to get all of your jobs startedvery quickly. After the time limit (in seconds) runs out (-B), the process onthe remote nodes will be terminated.

        Typically you’ll only be backgrounding long-runningshell commands or software upgrades. Backgrounding the copy module does not do a background file transfer. Playbooks also support polling, and have a simplified syntax for this.

        Gathering Facts

        Facts are described in the playbooks section and represent discovered variables about asystem. These can be used to implement conditional execution of tasks but also just to get ad-hoc information about your system. You can see all facts via:

        1. $ ansible all -m setup

        It’s also possible to filter this output to just export certain facts, see the “setup” module documentation for details.

        See also

        • All about the Ansible config file
        • All modules
        • A list of available modules
        • Using Ansible for configuration management & deployment
        • Mailing List
        • Questions? Help? Ideas? Stop by the list on Google Groups
        • ansible IRC chat channel