Skip to content

Instantly share code, notes, and snippets.

@hinchliff
Created April 19, 2019 12:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hinchliff/64cae9120a248c6e3ddc8b10ec3bd157 to your computer and use it in GitHub Desktop.
Save hinchliff/64cae9120a248c6e3ddc8b10ec3bd157 to your computer and use it in GitHub Desktop.
Run a Cloud Custodian policy file from a Python script. Most useful perhaps to be able to run Cloud Custodian from AWS Lambda.
import os
import logging
from c7n.commands import run
from c7n.config import Config
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Capture our current directory
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
OUT_DIR = '/tmp'
assumed_role = 'arn:aws:iam::{{ account_id }}:{{ target_role }}'
filename = 'my-policy.yml'
default_c7n_config = {
'skip-validation': True,
'vars': None,
'debug': True,
'assume': assumed_role,
'output_dir': os.path.join(OUT_DIR, 'out'),
'region': 'us-east-1',
'configs': [filename]
}
run_config = Config.empty(**default_c7n_config)
logger.info('Running policy: ' + filename)
run(run_config)
@pavantheavenger
Copy link

Hello there,

It's really great, your script have helped me out a lot.

I have made few modifications to the same code so that it can be ran using c7n_org module where we can run it onto multiple accounts and regions accordingly.

Can you please correct my modifications so that it would be executable on c7n_org as well.

Error Msg I am getting is :
Error: Missing option '-c' / '--config'.
test

Thank You !

Regards

Pavan

@gsl-ghassengabsi
Copy link

hello, i tested your script and i had the same problem, did you find a solution please? Thanks

@k-nelis
Copy link

k-nelis commented Mar 22, 2023

Hello,

try switching the dict parameters to a list with a sequential one. Ex:

`
import c7n_org.cli

commands_ex = [
"--config", "cloudcustodian/c7n-org-config/accounts.yml",
"--use", "cloudcustodian/aws/policies/s3-check-buckets-public",
"--output-dir", "output",
"--region", "sa-east-1"
]

test = c7n_org.cli

if name == "main":
ab = test.run.main(args=commands_ex, standalone_mode=True, prog_name="run")

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment