Simplify Your Redis Deployment on GCP with Ansible
Published: 2023-05-02 21:17:58

---
title: Simplify Your Redis Deployment on GCP with Ansible
published: true
date: 2023-05-01 12:37:12 UTC
tags: 
canonical_url: https://oluwafemiakinde.dev/simplify-your-redis-deployment-on-gcp-with-ansible
---

In this article, we will learn how to install Redis on a GCP VM instance using Ansible.

### Prerequisites:

- A GCP account with a project and a VM instance.

- Ansible is installed on your local machine.

- An SSH key pair to access the VM instance.

- You must have followed my previous article [here](https://dev.to/oluwafemiakind1/streamlining-infrastructure-management-provisioning-google-cloud-vms-with-ansible-3ed7) because you will be needing to modify the playbook that provisions a VM.

### **Step 1** :

Create an inventory file Create a file named `inventory` and add the IP address or hostname of the VM instance you want to install Redis on. For example:

```
[redis]
<ip address> or <hostname>

```

### **Step 2** :

Create a playbook Create a file named `redis-playbook.yml` and add the following tasks:

```
---
- name: Redis Installation
  hosts: redis
  become: true

  tasks:
    - name: Update package repositories
      yum:
       update_cache: yes

    - name: Install Redis
      yum:
        name: redis
        state: present

    - name: Start Redis service
      systemd:
        name: redis
        state: started
        enabled: yes

```

This playbook uses the `yum` module to update the package repositories on the target system and it also installs the Redis package. The `state` parameter is set to `present` to ensure that the package is installed if it is not already present.

After that, the Redis service is started with the `systemd` module.

### **Step 3** :

Run the playbook using the following command:

```
ansible-playbook redis-playbook.yml -i inventory --private-key=/path/to/ssh/key

```

This command runs the `redis-playbook.yml` playbook on the hosts specified in the `inventory` file and uses the SSH key specified in `--private-key` to access the VM instance.

### **Step 4:**

Verify that Redis is installed and running by connecting to the VM instance using SSH and running the following command:

```
redis-cli ping

```

**TIP** : You can use the command to ssh into your instance

```
ssh <external-ip-address> -i path/to/private/key

```

If Redis is running, the command should return `PONG`.

![redis pong response](https://cdn.hashnode.com/res/hashnode/image/upload/v1682859591306/68fa0c18-083f-4310-843b-7516247d65cf.png)

Now that we've confirmed that Redis is running in the VM instance, we'll need to connect to it outside the instance. Right now, if we try to do it, we're going to get an error (or it will most likely timeout). So this means we need to enable remote access to Redis and also update our firewall to accept TCP connections on port `6379`.

You first need to install the community versions of Ansible's firewall and google modules with the command:

```
ansible-galaxy collection install community.general community.google

```

### **Step 5:**

You will need to add `apache-libcloud` to the list of requirements in `requirements.yml`

```
 pip_package_requirements:
       ...
      - "apache-libcloud"

```

Once that is successful then copy the following tasks:

```
- name: Configure Redis
  become: yes
  lineinfile:
    path: /etc/redis/redis.conf #or /etc/redis.conf if you get an error that /etc/redis/redis.conf does not exist
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
  with_items:
    - { regexp: "^bind .*", line: "bind 0.0.0.0" }
    - { regexp: "^port .*", line: "port 6379" }
    - { regexp: "^# requirepass .*", line: "requirepass your_password_here" }
  notify: Restart Redis service

 - name: Allow incoming connections on port 6379
   community.general.ufw:
     rule: allow
     port: 6379
     proto: tcp

 - name: Reload firewall rules
   community.general.ufw:
     state: enabled

```

The task above updates the Redis configuration file and you'll notice that we also set a password. Remember to replace `your_password_here` with your preferred password.

This is the full Ansible playbook for Redis configuration:

{% embed https://gist.github.com/SirPhemmiey/8a7c7949468a5f12de1f0e5b7b272ff7 %}

### **Step 6:**

We will also need to create a GCP compute firewall by adding the following tasks in the playbook we created in my previous article [here](https://dev.to/oluwafemiakind1/streamlining-infrastructure-management-provisioning-google-cloud-vms-with-ansible-3ed7).

Copy the following tasks into your playbook. Be careful of indentation though :)

```
  - name: Create firewall policy for Redis
      gcp_compute_firewall:
        name: "{{ firewall_policy_name }}"
        priority: 1000
        direction: "INGRESS"
        project: "{{ gcp_project }}"
        service_account_file: "{{ gcp_cred_file }}"
        auth_kind: "{{ gcp_cred_kind }}"
        allowed:
        - ip_protocol: "tcp"
          ports:
            - 6379
        target_tags:
          - "redis"
        state: present
      register: firewall_policy_result
      #when: firewall_policy_result is not defined

    - name: Print firewall_policy_result
      debug:
        var: firewall_policy_result

    - name: Add firewall policy to Redis instance
      community.google.gce_tag:
        instance_name: "{{ instance_name }}"
        tags: redis
        zone: "{{ zone }}"
        project_id: "{{ gcp_project }}"
        state: present

```

In the tasks above, we're creating a GCP compute firewall policy and we're assigning the policy to our Redis instance.

This is the full Ansible playbook for VM provisioning and firewall policy creation:


{% embed https://gist.github.com/SirPhemmiey/ed299b4afd6c95a294e89be2ba9347f5 %}

The content of requirements.yml is this:

{% embed https://gist.github.com/SirPhemmiey/ac4dbb1d61acacae7c6a16dc16be71c7 %}

_It's important to note that you'll have to grant your service account permission to create/manage a firewall by assigning the_ **_Compute Network Admin_** _role in GCP's IAM page_ [_here_](https://console.cloud.google.com/iam-admin/iam?project=ajar-dev).

### **Step 7:**

Verify the remote connection by connecting remotely to the Redis instance with the command:

```
redis-cli -h <ip> -p <port> -a <password> ping

```

And you should be able to connect and get a `PONG`.

![redis pong response 2](https://cdn.hashnode.com/res/hashnode/image/upload/v1682976288362/0be4cace-690d-4776-bd88-fcab02330ce6.png)

Congratulations! You have successfully installed Redis on a GCP VM instance using Ansible. You can now use Redis as a database, cache, or message broker in your application.

I know this must have been a lot. And that's because this is the first time. Trust me, this can save you and anyone else hours of time because with just this file, you can repeat your tasks and you can deploy the same configuration to multiple VM instances at once.

## **Conclusion**

In this article, we learned how to install Redis on a GCP VM instance using Ansible. We also learned how to configure Redis by updating the configuration file, allow incoming connections, create firewall rules and policy. Ansible provides a simple and efficient way to automate the deployment and configuration of Redis on GCP VM instances.

Thank you for reading my article on **Simplifying Your Redis Deployment with Ansible!** Stay tuned for my upcoming articles on adding monitoring to your Redis server and the many advantages of creating a Redis cluster using Ansible. Don't miss out on the benefits of high availability, scalability, and fault tolerance that a Redis cluster can provide for your applications.