Optionally filter by role in gen_key script

This commit is contained in:
sfigato 2020-11-04 01:12:05 +01:00
parent 01eb5ace25
commit 2e4466d8f3
Signed by: blallo
GPG Key ID: 0CBE577C9B72DC3F

View File

@ -35,10 +35,12 @@ yaml.SafeLoader.add_constructor("!vault", DummyVault.from_yaml)
yaml.SafeDumper.add_multi_representer(DummyVault, DummyVault.to_yaml)
def load_hosts(inventory: T.Text) -> T.List[T.Text]:
def load_hosts(inventory: T.Text, role: T.Optional[T.Text]) -> T.List[T.Text]:
with open(inventory, "r") as f:
data = yaml.load(f, Loader=yaml.SafeLoader)
if role:
return [k for k in data["all"]["children"][role]["hosts"].keys()]
return [k for k in data["all"]["hosts"].keys()]
@ -81,7 +83,7 @@ def _encrypt_string_vault(
plaintext: T.Text, vault_passfile: T.Text, passfile_dir: T.Text
) -> bytes:
return subprocess.check_output(
["ansible-vault", "encrypt_string", f"--vault-id={vault_passfile}", plaintext,],
["ansible-vault", "encrypt_string", f"--vault-id={vault_passfile}", plaintext],
cwd=passfile_dir,
)
@ -129,8 +131,14 @@ if __name__ == "__main__":
type=str,
help="path where the passfile is located",
)
parser.add_argument(
"--role",
metavar="ROLE",
type=str,
help="an optional key to use to filter the search for hosts in the inventory",
)
args = parser.parse_args()
for host in load_hosts(args.inventory):
for host in load_hosts(args.inventory, args.role):
gen_key(host)
to_vault(host, args.passfile, args.vault_id, args.passfile_dir)
result = yaml.dump(HOSTS, Dumper=yaml.SafeDumper)