Is it possible to use a state for ansible?

Viewed 1458

You might not understand what I am trying to say in the question. Before stating the problem, I would give an example to understand even more.

Let's take terraform for the example.

Imagine we use terraform to spin up an EC2 instance in the aws. So, we are currently storing the state locally. Let's say we need to add a tag to the ec2 instance.

So what we do is, we add the this small block to achieve that.

tags = {
    Name = "HelloWorld"
  }

Nothing complex, just simple as it is. So, as we add a tag, the terraform will look for any changes in the state and as it found a tag has been added, it runs and only add the tag without recreating the whole instance. (There can be other scenarios where it needs to recreate the instance but let's leave those for now)

So, as I mentioned, terraform doesn't recreate the instance for adding a tag. If we want to add another tag, it will add the tag without recreating the instance. Just as simple as that. doesn't matter how many times we run the terraform apply it doesn't do any changes to existing resources unless we made any in the terraform files.

So, let's now come to the real question.

Let's say we want to install a httpd using ansible. So I write ansible playbook. And it will use the yum package and install and then start and enable the service.

Okay it is simple like that.

Let's say we we run the same playbook for the second time, now will try to execute the same commands from scratch without checking first whether it has executed this playbook before?

I have couple of experiences where I try to install some services and when I try to execute the same playbook again, it fails.

Is it possible to preserve the state in ansible just like we do in terraform so it always only execute the newer changes other than executing from the start on the second run?

1 Answers

You seem to be describing idempotence:

Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.

It's up to you to make sure your playbooks are idempotent in ansible. You could do this for your example using the package and service modules.

- name: Setup Apache
  hosts: webservers
  tasks:
    - name: Install Apache
      package:
        name: httpd
        state: present
    - name: Start and enable Apache
      service:
        name: httpd
        state: started
        enabled: yes

Ansible doesn't achieve idempotence by retaining state on the the controller. Each module should check the state of the host it's operating on to determine what changes it needs to make to achieve the state specified by the playbook. If it determines that it doesn't need to make any changes then that's what it should report back to the controller.

Related