Skip to content

Instantly share code, notes, and snippets.

@caleb15
Last active July 27, 2022 23:59
Show Gist options
  • Save caleb15/152b1624106e697076e9c9c0538bb847 to your computer and use it in GitHub Desktop.
Save caleb15/152b1624106e697076e9c9c0538bb847 to your computer and use it in GitHub Desktop.
ansible callback plugin for warning if you are running against wrong environment
import os
from typing import List
import sys
from ansible.plugins.callback import CallbackBase
# this file goes in a "callback_plugins" folder next to your playbook file
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate' # no idea what this var does, can't find documentation :(
CALLBACK_NAME = 'env_warning'
def v2_playbook_on_play_start(self, play):
env_name: str = os.environ.get('ENV_NAME')
vpc_name: str = os.environ.get('VPC_NAME')
ansible_vars: dict = play.get_variable_manager().get_vars()
inventory_sources: List[str] = ansible_vars["ansible_inventory_sources"]
if not env_name:
print('no ENV_NAME var found - have you sourced secrets?')
sys.exit(1)
if not vpc_name:
print('no VPC_NAME var found - have you sourced secrets?')
sys.exit(2)
# we are running against a local test env, no need for warning
if any(['molecule' in s for s in inventory_sources]):
return
if all([vpc_name not in inventory_source
for inventory_source in inventory_sources]):
print(f"The VPC_NAME env var {vpc_name} doesn't match any of your inventory sources. "
"Please check that you have sourced the correct secrets folder "
"and are using the right inventory file.")
sys.exit(3)
if env_name == "production":
env_name = f"πŸ’€πŸ’€πŸ’€ {env_name.upper()} πŸ’€πŸ’€πŸ’€"
print(f"You are running in {env_name}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment