shellsceptre

Unable to set environment variable with Sceptre pre hooks


I'm trying to set an environment variable using sceptre !cmd hooks(before create/update), which can be then resolved by sceptre_user_data with !environment_variable resolver within the same config file.

The command works well, when executed from shell, but for some reason, the !cmd hook doesn't perform assignment during runtime

Don't know, if I'm missing anything here

hooks:
  before_create:
    - !cmd "export OBJECT_VERSION=$(aws s3api put-object --body file --bucket bucket-name --key path --query 'VersionId')"

sceptre_user_data:
  ObjectVersion: !environment_variable OBJECT_VERSION


Solution

  • Unfortunately you'd need a custom resolver for that at the moment

    sceptre_plugins_cmd_extras.py

    import os
    import subprocess
    from sceptre.resolvers import Resolver
    
    
    class CmdResolver(Resolver):
        """
        Resolver for running shell commands and returning the value
        :param argument: Name of the environment variable to return.
        :type argument: str
        """
    
        def resolve(self):
            """
            Runs a command and returns the output as a string
            :returns: Value of the environment variable.
            :rtype: str
            """
            return subprocess.check_output(self.argument, shell=True)
    

    setup.py

    from setuptools import setup
    
    setup(
        name='sceptre-plugins-cmd-extras',
        description="Extra Sceptre Plguins (Hook & Resolver) for subprocess",
        keywords="sceptre,cloudformation",
        version='0.0.1',
        author="Cloudreach",
        author_email="juan.canham@cloudreach.com",
        license='Apache2',
        url="https://github.com/cloudreach/sceptre",
        entry_points={
            'sceptre.resolvers': [
                'cmd = sceptre_plugins_cmd_extras:CmdResolver',
            ],
        },
        py_modules=['sceptre_plugins_cmd_extras'],
        install_requires=["sceptre"],
        classifiers=[
            "Development Status :: 3 - Alpha",
            "Intended Audience :: Developers",
            "Intended Audience :: System Administrators"
            "Natural Language :: English",
            "Environment :: Plugins",
            "Programming Language :: Python :: 2.6",
            "Programming Language :: Python :: 2.7",
            "Programming Language :: Python :: 3.5",
            "Programming Language :: Python :: 3.6",
            "Programming Language :: Python :: 3.7"
        ]
    )
    

    But you'd then need to make your command idempotent (something like)

    sceptre_user_data:
      ObjectVersion: !cmd aws s3api get-object --bucket bucket-name --key path --query 'VersionId' || aws s3api put-object --body file --bucket bucket-name --key path --query 'VersionId'