Skip to content

Instantly share code, notes, and snippets.

@SirPhemmiey
Created May 1, 2023 21:12
Show Gist options
  • Save SirPhemmiey/ed299b4afd6c95a294e89be2ba9347f5 to your computer and use it in GitHub Desktop.
Save SirPhemmiey/ed299b4afd6c95a294e89be2ba9347f5 to your computer and use it in GitHub Desktop.
Full ansible playbook version to provision vm instance and allowing remote access to redis
- import_playbook: requirements.yml #you can find the file content in my gist
- name: Provision a GCP VM
hosts: localhost
gather_facts: false
vars:
gcp_cred_file: <your json service account>
gcp_project: <project-id>
machine_type: "e2-medium"
gcp_cred_kind: serviceaccount
instance_name: "my-vm-instance"
zone: "us-central1-a"
region: "us-central1"
image: "https://www.googleapis.com/compute/v1/projects/rocky-linux-cloud/global/images/rocky-linux-8-optimized-gcp-v20230411"
ssh_key_file: "{{ lookup('env','HOME') + '/.ssh/id_rsa.pub' }}"
ssh_key_user: <ssh user>
firewall_policy_name: "redis-firewall"
tasks:
- name: Create an external address associated with the instance
gcp_compute_address:
name: "{{ zone }}-ip"
region: "{{ region }}"
project: "{{ gcp_project }}"
service_account_file: "{{ gcp_cred_file }}"
auth_kind: "{{ gcp_cred_kind }}"
register: gce_ip
- name: Create the GCP VM
gcp_compute_instance:
name: "{{ instance_name }}"
machine_type: "{{ machine_type }}"
zone: "{{ zone }}"
project: "{{ gcp_project }}"
service_account_file: "{{ gcp_cred_file }}"
auth_kind: "{{ gcp_cred_kind }}"
tags:
items:
- http-server
- https-server
disks:
- auto_delete: true
boot: true
initialize_params:
source_image: "{{ image }}"
network_interfaces:
- access_configs: # if you don't add this then the VM instance will have no external address attached to it
- name: External NAT
nat_ip: "{{ gce_ip }}"
type: ONE_TO_ONE_NAT
metadata:
ssh-keys: "{{ssh_key_file}}"
register: result
- name: Print the VM's IP address
debug:
var: gce_ip.address
- name: Run ssh-keyscan to add keys to known_hosts
local_action: shell ssh-keyscan {{ gce_ip.address }} >> ~/.ssh/known_hosts
- 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 }}"
pem_file: "{{gcp_cred_file}}"
state: present
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment