How to Execute Directives with the Ansible Command Module

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

Ansible was developed by Michael DeHaan and the open source community, which is why it’s so popular for its simplicity. Ansible allows you to configure your servers in an easy way without having to jump through hoops with a text editor or use complicated software like Chef.

Ansible is a configuration management tool that allows users to configure systems and automate the deployment of software. The Ansible Command Module allows users to execute directives within their playbooks.

How to Execute Directives with the Ansible Command Module

Want to use Ansible for automation and efficiency, but can’t seem to discover the correct module for the activities you need to complete? Try out the Ansible Command module. You may use the Command module to swiftly run arbitrary instructions across several nodes.

In this video, you’ll learn how to use the Ansible command module to execute directives by executing ad-hoc commands and efficiently developing a playbook.

Enough with the introduction; let’s get to work!

Prerequisites

Hands-on demonstrations are included in this session. If you want to follow along, make sure you have the following items on hand:

  • Ansible v2.12.1 or later is required.

How to Setup Ansible is a related article (Ubuntu, RHEL, CentOS, macOS)

  • Ansible control node (Linux host) – Fedora 35 is used in this tutorial, and the hostname is my-fed.
  • This tutorial utilizes Fedora 35 as the remote host, using the hostname medsvr.
  • A user account with remote system access — The username for this lesson is meduser.

Making Your Own Inventory File

After you’ve completed the requirements, begin this course by using an ad-hoc command to create a list of machines in an inventory file. An inventory file is used by Ansible to keep track of which devices it may communicate with. Ansible enables you to manage personal inventory in addition to the global inventory file.

Ad-hoc commands, as defined by the Ansible binary, are commands that are performed separately and directly on the command line. They’re fast to use, but they’re not reusable since they’re not written in files that can be shared and versioned.

Open the terminal on your control node and perform the command below. The remote node (medsvr) is written to a file named inventory using this command. While following this guide, the inventory file will come in helpful when dealing with distant machines.

Because it may be referred to as localhost, the control node can be omitted from the inventory file.

Creating a List of Files and Directories

You may run commands to execute directives now that you have the inventory file in place. It’s possible that you’ll need to list the files and folders in the current working directory. If that’s the case, you may use the command module to perform the ls command.

To list (ls) the contents of the current working directory on the control node, use the ansible command below using the command module (localhost).

The -m option instructs Ansible to utilize the command module, while the -a switch specifies the command or directive to be executed.

localhost -m command -a “ls” ansible

You’ll see a list of files and folders, prepended by Ansible’s status summary, as in the output below, when it’s completed successfully.

Creating a List of Files and Directories using the command module Creating a List of Files and Directories using the command module

Checking the Memory of a Remote System

Perhaps you’d want to see a distant system’s RAM statistics. Running the free command is one method to do so.

To show the memory utilization of the remote system in gibibytes, run the command below, which combines the command module and the free command (-g).

The user (-u) meduser conducts the tests on the remote node (medsvr) indicated in the custom inventory file for remote access (-i inventory). The -k option instructs Ansible to ask you for the user’s SSH password.

ansible medsvr -m command -a “free -g” -u meduser -k -i inventory ansible medsvr -m command -a “free -g” ansible medsvr -m command -a “free -g

As a general guideline, wherever possible, utilize a specific module to get benefits like idempotence. When you need extensive shell functionality, use Shell, but when you need directives that can be performed outside of a shell context, use Command.

How to Use the Ansible Shell Module to Execute Remote Commands

The memory statistics for the remote node are shown in a tabular manner below.

The memory statistics of a remote system are shown. The memory statistics of a remote system are shown.

Based on the existence of a file, the Httpd service is started.

Let’s say you only want the Apache httpd service to start on your webservers if a file you just uploaded to one of them exists. However, if the file does not exist, it is best to leave the system alone.

Only if the /var/www/html/index.html file exists, use the ansible command below to start (systemctl start) the httpd service on the remote node (medsvr). The removes keyword is used to identify the file that must be present in order for the directive to be performed.

While running the process, the -K and -b options are used to request elevation with a password prompt for meduser.

ansible medsvr -m command -a “systemctl start httpd removes=/var/www/html/index.html” ansible medsvr -m command -a “systemctl start httpd removes=/var/www/html/index.html” -kbK -i inventory -u meduser

The result should look like the one below if the file is present.

When a file exists, the httpd service is started. When a file exists, the httpd service is started.

If the /var/www/html/index.html file does not exist, you will see the following output instead.

Because a file does not exist, the command will be skipped. Because a file does not exist, the command will be skipped.

Installing a Package That Doesn’t Exist

You may run any directive, just as in the previous example, only this time only if a file does not exist. If Flameshot’s binary isn’t discovered on the remote system, for example, you may install it.

Install Flameshot (dnf install -y flameshot) on the remote node using the ansible command below (medsvr). The creates keyword instructs Ansible to only run the command if the /usr/bin/flameshot file is missing.

medsvr -m command -a “dnf install -y flameshot creates=/usr/bin/flameshot” -i inventory -u meduser -kbK ansible medsvr -m command -a “dnf install -y flameshot creates=/usr/bin/flameshot creates=/usr/bin/flameshot creates=/usr/bin/flameshot creates

If the /usr/bin/flameshot file is missing, you’ll see something like this, where Ansible installs Flameshot.

Using the Command Module to Install Flameshot Using the Command Module to Install Flameshot

Creating a File and Changing the Working Directory

The command module in Ansible enables you to guarantee that a command is only run when the working directory has been updated. This capability comes in useful whether you’re executing scripts, building from source, or producing files that need to be in a certain environment.

To create the hello.txt file, run the command below to change (chdir) to the /opt/ directory on the control node.

-a “touch hello.txt chdir=/opt/” -bK ansible localhost -m command

Before running a directive, change the working directory. Before running a directive, change the working directory.

To see the contents of the /opt/ directory, use the ls command.

The hello.txt file you produced is located in the /opt/ directory, as seen below.

To display a freshly generated file, list the contents of the directory. To display a freshly generated file, list the contents of the directory.

Using a Playbook to Execute Directives

Ad-hoc commands are useful, but they aren’t the only thing Ansible can do. Playbooks are useful for storing and reusing a set of activities.

All of the preceding examples on the remote computer will be combined into a single playbook with a sequence of activities. However, to make it simpler to follow along, the different tasks are segregated for examination. At the Conclusion of this part, you’ll run the playbook in its entirety.

1. Using your preferred text editor, create a YAML file and fill in the code below. The file is named command-training.yml in our example, but you may name it anything you like.

The task runs the free command to display memory usage in gibibytes in the code below, which uses the command module (ansible.builtin.command).

—- – name: Using Command Module hosts to run commands on a remote server: localhost # The value is set to “no” to speed up execution by avoiding the data collection process that every playbook goes through when it is performed. no tasks: gather facts – name: ansible.builtin: Check Memory on Remote Machine “free -g” is a command.

2. In the command-training.yml file, add the following code under tasks. If an index.html file has been uploaded to a web server, the code below will start the httpd service.

The simplest method to express this assignment is to use every option as the single argument to the module, as demonstrated in the example below. However, this approach degrades readability and, in the long run, your ability to communicate or debug successfully.

– name: Only start Httpd if ansible file exists. builtin. “systemctl start httpd removes=/var/www/html/index.html” is the command. Yes becomes:

Another method to define the directive is to use the args keyword to separate the command into its component components, as seen below. The primary command takes up one line, which cmd has assigned, while the options take up succeeding lines, which have been suitably marked.

The selection of tags for each line is not random. They were picked by the Ansible team to represent the module’s typical arguments.

– name: Only run httpd if the file is present ansible.builtin.command: removes: /var/www/html/index.html args: cmd: systemctl start httpd Yes becomes:

3. In the command-training.yml file, add the code below under tasks, same like you did in step two.

The code below utilizes the argv parameter instead of going straight or utilizing a list of named arguments. To make reading and debugging easier, use the argv option to divide the main command into a list.

The argv argument is unique to the command module, but args, like become, is a task-level term. Argv must be indented considerably farther to demonstrate it is a child of the command module, while args is indented to the level of the module name.

If the flameshot binary (/usr/bin/flameshot) is missing from the system, the code following uses argv to install it.

– name: Only install a package if a file is missing from ansible. builtin.command: argv: – dnf – install – -y – argv: – dnf – install – -y – argv: – /usr/bin/flameshot is created by flameshot. Yes becomes:

The fact that argv quotes every entry means that you may safely use objects that would normally need quotes while missing the quotations. But keep in mind that, once reassembled on the command line, you must guarantee that each item is quotable.

You’ve seen at least three different methods to write tasks using the command module by following each step. You may utilize any of the aforementioned styles depending on your goal. Just be cautious when it comes to indentation levels.

And, as promised, here is the whole playbook (command-training.yml):

— – name: Running commands on remote server using Command Module # Set remote machine as target host hosts: medsvr gather_facts: no tasks: – name: Check Memory on remote machine ansible.builtin.command: “free -g” – name: Only run httpd if the file is present ansible.builtin.command: removes: /var/www/html/index.html args: cmd: systemctl start httpd Yes becomes: – name: Install a package only if file does not exist ansible.builtin.command: argv: – dnf – install – -y – flameshot creates: /usr/bin/flameshot become: yes

4. Finally, run the ansible-playbook command to put the playbook into action (command-training.yml). To guarantee that Ansible runs the playbook with suitable credentials, provide the custom inventory(inventory) file and the correct set of switches (-bkK).

meduser -i inventory command-training.yml -bkK ansible-playbook

When the command is finished, you should see something like this.

Playbook comprising command module tasks is being executed. Playbook comprising command module tasks is being executed.

Using the with items plugin to execute several directives

Perhaps you need to execute numerous directives at the same time. If that’s the case, Ansible’s with items plugin allows you to run several directives in a single job. The key is to use the looping construct with items.

Make a small.yml file and fill it with the code below.

The following code creates a directory (/test/work) and saves the sshd configuration file to it. Before going on to the next job, Ansible runs each element in the list.

– name: ansible.builtin.command: “item” with items: “item” with items: “item” with items: “item” with items: “item” with items: “item” with items: – copy /etc/ssh/sshd config /test/work/sshd config.bk – mkdir -p /test/work Yes becomes:

To run the playbook, use the command below (small.yml)

meduser -i inventory small.yml -bkK ansible-playbook

Using with items to run many commands in a playbook Using with items to run many commands in a playbook

Conclusion

You’ve learned how to combine different aspects of the Ansible command module to conduct a variety of tasks during this lesson. Only your imagination can define the precise limits of this tool’s value.

You’re in a good position to start taking use of Ansible’s capabilities at this stage. So why not utilize the Ansible User module to manage your users?

The “ansible run command on remote host” is a useful feature of the Ansible command module. This allows users to execute commands on remote hosts.

Related Tags

  • ansible playbook change directory and run command
  • ansible basic commands
  • ansible command module examples
  • ansible-playbook dry run command
  • ansible run command example

Table of Content